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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
/*!
 * Parser with iterators
 * 
 * Parses string tokens into model entities (Account, Transaction, Post, Amount...)
 *
 * The main idea here is to minimize memory allocations.
 * The parsing is done in functions, not objects.
 * Each parser will provide an iterator over the tokens it recognizes, i.e. Xact parser
 * will iterate over the Xact header items: date, payee, note.
 * Post parser provides an iterator over Account, Amount. Amount parser provides
 * sign, quantity, symbol, price.
 * Iterator returns None if a token is not present.
 *
 * Tokens are then handled by lexer, which creates instances of Structs and populates
 * the collections in the Journal.
 * It also creates links among the models. This functionality is from finalize() function.
 */
use core::panic;
use std::{
    env,
    io::{BufRead, BufReader, Read},
    path::PathBuf,
    str::FromStr,
    todo,
};

use chrono::NaiveDate;

use crate::{
    amount::Amount,
    journal::{Journal, XactIndex},
    pool::CommodityIndex,
    post::Post,
    scanner,
    xact::Xact,
};

pub const ISO_DATE_FORMAT: &str = "%Y-%m-%d";
pub const ISO_TIME_FORMAT: &str = "%H:%M:%S";

pub(crate) fn read_into_journal<T: Read>(source: T, journal: &mut Journal) {
    let mut parser = Parser::new(source, journal);

    parser.parse();
}

pub(crate) fn parse_date(date_str: &str) -> NaiveDate {
    // todo: support more date formats?

    NaiveDate::parse_from_str(date_str, ISO_DATE_FORMAT).expect("date parsed")
}

struct Parser<'j, T: Read> {
    pub journal: &'j mut Journal,

    reader: BufReader<T>,
    buffer: String,
}

impl<'j, T: Read> Parser<'j, T> {
    pub fn new(source: T, journal: &'j mut Journal) -> Self {
        let reader = BufReader::new(source);
        // To avoid allocation, reuse the String variable.
        let buffer = String::new();

        Self {
            reader,
            buffer,
            journal,
        }
    }

    pub fn parse(&mut self) {
        loop {
            match self.reader.read_line(&mut self.buffer) {
                Err(err) => {
                    println!("Error: {:?}", err);
                    break;
                }
                Ok(0) => {
                    // end of file
                    break;
                }
                Ok(_) => {
                    // Remove the trailing newline characters
                    // let trimmed = &line.trim_end();

                    match self.read_next_directive() {
                        Ok(_) => (), // continue
                        Err(err) => {
                            log::error!("Error: {:?}", err);
                            println!("Error: {:?}", err);
                            break;
                        }
                    };
                }
            }

            // clear the buffer before reading the next line.
            self.buffer.clear();
        }
    }

    fn read_next_directive(&mut self) -> Result<(), String> {
        // if self.buffer.is_empty() {
        //     return Ok(());
        // }
        // let length = self.buffer.len();
        // log::debug!("line length: {:?}", length);
        if self.buffer == "\r\n" || self.buffer == "\n" {
            return Ok(());
        }

        // determine what the line is
        match self.buffer.chars().peekable().peek().unwrap() {
            // comments
            ';' | '#' | '*' | '|' => {
                // ignore
                return Ok(());
            }

            '-' => {
                // option_directive
            }

            '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
                // Starts with date/number.
                self.xact_directive();
            }

            ' ' | '\t' => {
                todo!("complete")
            }

            // The rest
            c => {
                // 4.7.2 command directives

                // if !general_directive()
                match c {
                    // ACDNY
                    'P' => {
                        // price
                        self.price_xact_directive();
                    }

                    c => {
                        log::warn!("not handled: {:?}", c);
                        todo!("handle other directives");
                    }
                }
                todo!("the rest")
            }
        }

        // TODO: lexer - create model elements from tokens
        // TODO: store model elements in collections and link.

        Ok(())
    }

    /// textual.cc
    /// bool instance_t::general_directive(char *line)
    fn general_directive(&self) -> bool {
        // todo: skip if (*p == '@' || *p == '!')

        // split directive and argument
        let mut iter = self.buffer.split_whitespace();
        let Some(directive) = iter.next() else { panic!("no directive?") };
        let argument = iter.next();

        // todo: check arguments for directives that require one
        // match directive {
        //     "comment" | "end" | "python" | "test" | "year" | "Y" => {
        //         //
        //         // Year can also be specified with one letter?
        //         ()
        //     }
        //     _ => {
        //         panic!("The directive {:?} requires an argument!", directive);
        //     }
        // }

        match directive.chars().peekable().peek().unwrap() {
            'a' => {
                todo!("a");
            }

            // bcde
            'i' => match self.buffer.as_str() {
                "include" => {
                    self.include_directive(argument.unwrap());
                    return true;
                }
                "import" => {
                    todo!("import directive")
                }
                _ => (),
            },

            // ptvy
            _ => {
                todo!("handle")
            }
        }

        // lookup(DIRECTIVE, self.buffer)

        false
    }

    fn price_xact_directive(&mut self) {
        // pass on to the commodity pool
        self.journal
            .commodity_pool
            .parse_price_directive(&self.buffer);
    }

    fn xact_directive(&mut self) {
        let tokens = scanner::tokenize_xact_header(&self.buffer);
        let xact = Xact::create(tokens[0], tokens[1], tokens[2], tokens[3]);
        // Add xact to the journal
        let xact_index = self.journal.add_xact(xact);

        // Read the Xact contents (Posts, Comments, etc.)
        // Read until separator (empty line).
        loop {
            self.buffer.clear(); // empty the buffer before reading
            match self.reader.read_line(&mut self.buffer) {
                Err(e) => {
                    println!("Error: {:?}", e);
                    break;
                }
                Ok(0) => {
                    // end of file
                    log::debug!("0-length buffer");
                    break;
                }
                Ok(_) => {
                    if self.buffer.is_empty() {
                        // panic!("Unexpected whitespace at the beginning of line!")
                        todo!("Check what happens here")
                    }

                    // parse line
                    match self.buffer.chars().peekable().peek() {
                        Some(' ') => {
                            // valid line, starts with space.
                            let input = self.buffer.trim_start();

                            // if the line is blank after trimming, exit (end the transaction).
                            if input.is_empty() {
                                break;
                            }

                            // Process the Xact content line. Could be a Comment or a Post.
                            match input.chars().peekable().peek() {
                                Some(';') => {
                                    todo!("trailing note")
                                }
                                _ => {
                                    parse_post(input, xact_index, &mut self.journal);
                                }
                            }
                        }
                        Some('\r') | Some('\n') => {
                            // empty line "\r\n". Exit.
                            break;
                        }
                        _ => {
                            panic!("should not happen")
                        }
                    }
                }
            }

            // empty the buffer before exiting.
            self.buffer.clear();
        }

        // "finalize" transaction
        crate::xact::finalize(xact_index, &mut self.journal);
    }

    fn include_directive(&self, argument: &str) {
        let mut filename: PathBuf;

        // if (line[0] != '/' && line[0] != '\\' && line[0] != '~')
        if argument.starts_with('/') || argument.starts_with('\\') || argument.starts_with('~') {
            filename = PathBuf::from_str(argument).unwrap();
        } else {
            // relative path
            // TODO: get the parent path?
            // dir = parent_path()
            // if (parent_path.empty())
            // else, use current directory
            filename = env::current_dir().unwrap();

            filename.set_file_name(argument);
        }

        let mut file_found = false;
        let parent_path = filename.parent().unwrap();
        if parent_path.exists() {
            if filename.is_file() {
                // let base = filename.file_name();

                // TODO: read file
                todo!("read file")
            }
        }

        if !file_found {
            panic!("Include file not found");
        }
    }
}

/// Parses Post from the buffer, adds it to the Journal and links
/// to Xact, Account, etc.
fn parse_post(input: &str, xact_index: XactIndex, journal: &mut Journal) {
    let tokens = scanner::scan_post(input);

    let account_index;
    {
        // Create Account, add to collection
        account_index = journal.register_account(tokens[0]).unwrap();
    }

    let commodity_index: Option<CommodityIndex>;
    {
        // Create Commodity, add to collection
        let symbol = tokens[2];
        commodity_index = journal.commodity_pool.find_or_create(symbol);
    }
    // create amount
    let amount = Amount::parse(tokens[1], commodity_index);

    // handle cost (2nd amount)
    let price_commodity_index: Option<CommodityIndex>;
    {
        let symbol = tokens[4];
        price_commodity_index = journal.commodity_pool.find_or_create(symbol);
    }
    let cost = Amount::parse(tokens[3], price_commodity_index);

    let post_index;
    {
        // Create Post, link Xact, Account, Commodity
        let post = Post::new(account_index, xact_index, amount, cost);
        post_index = journal.add_post(post);
    }

    // add Post to Account.posts
    {
        let account = journal.accounts.get_mut(account_index).unwrap();
        account.post_indices.push(post_index);
    }

    {
        // add Post to Xact.
        let xact = journal.xacts.get_mut(xact_index).unwrap();
        xact.posts.push(post_index);
    }
}

#[cfg(test)]
mod tests {
    use std::{io::Cursor, todo};

    use super::Parser;
    use crate::journal::Journal;

    /// Enable this test again when the functionality is complete
    //#[test]
    fn test_general_directive() {
        let source = Cursor::new("include some-file.ledger");
        let mut journal = Journal::new();

        let parser = Parser::new(source, &mut journal);

        parser.general_directive();

        todo!("assert")
    }

    /// A transaction record, after which comes a line with spaces only.
    /// This should be parseable.
    #[test]
    fn test_xact_with_space_after() {
        let src = r#";
2023-05-05 Payee
    Expenses  25 EUR
    Assets
            
"#;
        let source = Cursor::new(src);
        let mut journal = Journal::new();
        let mut parser = Parser::new(source, &mut journal);

        // Act
        parser.parse();

        // Assert
        assert_eq!(3, journal.accounts.len());
    }
}

#[cfg(test)]
mod full_tests {
    use std::io::Cursor;

    use crate::{journal::Journal, parser::read_into_journal};

    #[test]
    fn test_minimal_parsing() {
        let input = r#"; Minimal transaction
2023-04-10 Supermarket
    Expenses  20
    Assets
"#;
        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        // Act
        super::read_into_journal(cursor, &mut journal);

        // Assert
        assert_eq!(1, journal.xacts.len());

        let xact = journal.xacts.first().unwrap();
        assert_eq!("Supermarket", xact.payee);
        assert_eq!(2, xact.posts.len());

        let post1 = &journal.posts[xact.posts[0]];
        assert_eq!("Expenses", journal.get_account(post1.account_index).name);
        assert_eq!("20", post1.amount.as_ref().unwrap().quantity.to_string());
        assert_eq!(None, post1.amount.as_ref().unwrap().commodity_index);

        let post2 = &journal.posts[xact.posts[1]];
        assert_eq!("Assets", journal.get_account(post2.account_index).name);
    }

    #[test]
    fn test_multiple_currencies_one_xact() {
        let input = r#";
2023-05-05 Payee
    Assets:Cash EUR  -25 EUR
    Assets:Cash USD   30 USD
"#;
        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        // Act
        read_into_journal(cursor, &mut journal);

        // Assert
        assert_eq!(2, journal.commodity_pool.commodities.len());
    }
}

#[cfg(test)]
mod parser_tests {
    use std::{assert_eq, io::Cursor};

    use crate::{
        journal::Journal,
        parser::{self, read_into_journal},
    };

    #[test]
    fn test_minimal_parser() {
        let input = r#"; Minimal transaction
2023-04-10 Supermarket
    Expenses  20
    Assets
"#;
        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        // Act
        parser::read_into_journal(cursor, &mut journal);

        // Assert

        assert_eq!(1, journal.xacts.len());

        let xact = journal.xacts.first().unwrap();
        assert_eq!("Supermarket", xact.payee);
        assert_eq!(2, xact.posts.len());

        // let exp_account = journal.get
        let post1 = &journal.posts[xact.posts[0]];
        assert_eq!("Expenses", journal.get_account(post1.account_index).name);
        assert_eq!("20", post1.amount.as_ref().unwrap().quantity.to_string());
        assert_eq!(None, post1.amount.as_ref().unwrap().commodity_index);

        // let post_2 = xact.posts.iter().nth(1).unwrap();
        let post2 = &journal.posts[xact.posts[1]];
        assert_eq!("Assets", journal.get_account(post2.account_index).name);
    }

    #[test]
    fn test_parse_standard_xact() {
        let input = r#"; Standard transaction
2023-04-10 Supermarket
    Expenses  20 EUR
    Assets
"#;
        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        super::read_into_journal(cursor, &mut journal);

        // Assert
        // Xact
        assert_eq!(1, journal.xacts.len());

        if let Some(xact) = journal.xacts.first() {
            // assert!(xact.is_some());

            assert_eq!("Supermarket", xact.payee);

            // Posts
            let posts = journal.get_posts(&xact.posts);
            assert_eq!(2, posts.len());

            let acc1 = journal.get_account(posts[0].account_index);
            assert_eq!("Expenses", acc1.name);
            let acc2 = journal.get_account(posts[1].account_index);
            assert_eq!("Assets", acc2.name);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn test_parse_trade_xact() {
        // Arrange
        let input = r#"; Standard transaction
2023-04-10 Supermarket
    Assets:Investment  20 VEUR @ 10 EUR
    Assets
"#;
        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        // Act
        read_into_journal(cursor, &mut journal);

        // Assert
        let xact = journal.xacts.first().unwrap();
        assert_eq!("Supermarket", xact.payee);

        let posts = journal.get_posts(&xact.posts);
        assert_eq!(2, posts.len());

        // post 1
        let p1 = posts[0];
        assert_eq!("Investment", journal.get_account(p1.account_index).name);
        // amount
        let Some(a1) = &p1.amount else {panic!()};
        assert_eq!("20", a1.quantity.to_string());
        let comm1 = journal
            .commodity_pool
            .commodity_history
            .get_commodity(a1.commodity_index.unwrap());
        assert_eq!("VEUR", comm1.symbol);
        let Some(ref cost1) = p1.cost else { panic!()};
        // cost
        assert_eq!("10", cost1.quantity.to_string());
        assert_eq!(
            "EUR",
            journal
                .commodity_pool
                .commodity_history
                .get_commodity(cost1.commodity_index.unwrap())
                .symbol
        );

        // post 2
        let p2 = posts[1];
        assert_eq!("Assets", journal.get_account(p2.account_index).name);
        // amount
        let Some(a2) = &p2.amount else {panic!()};
        assert_eq!("-20", a2.quantity.to_string());
        let comm2 = journal
            .commodity_pool
            .commodity_history
            .get_commodity(a2.commodity_index.unwrap());
        assert_eq!("VEUR", comm2.symbol);

        assert!(p2.cost.is_none());
    }

    #[test]
    fn test_parsing_account_tree() {
        let input = r#"
2023-05-23 Payee
  Assets:Eur   -20 EUR
  Assets:USD    30 USD
  Trading:Eur   20 EUR
  Trading:Usd  -30 USD
"#;

        let cursor = Cursor::new(input);
        let mut journal = Journal::new();

        // Act
        read_into_journal(cursor, &mut journal);

        // Assert
        assert_eq!(1, journal.xacts.len());
        assert_eq!(4, journal.posts.len());
        assert_eq!(7, journal.accounts.len());
        assert_eq!(2, journal.commodity_pool.commodities.len());
    }
}

#[cfg(test)]
mod posting_parsing_tests {
    use crate::{journal::Journal, amount::Decimal, utilities::create_date};

    #[test]
    fn test_parsing_buy_lot() {
        let file_path = "tests/lot.ledger";
        let mut j = Journal::new();

        // Act
        crate::parse_file(file_path, &mut j);

        // Assert
        assert_eq!(1, j.xacts.len());
        assert_eq!(4, j.accounts.len());
        assert_eq!(2, j.commodity_pool.commodities.len());
        // price
        assert_eq!(2, j.commodity_pool.commodity_history.graph.node_count());
        assert_eq!(1, j.commodity_pool.commodity_history.graph.edge_count());
        // Check price: 10 VEUR @ 12.75 EUR
        let price = j.commodity_pool.commodity_history.graph.edge_weight(0.into()).unwrap();
        let expected_date = create_date("2023-05-01").unwrap();
        // let existing_key = price.keys().nth(0).unwrap();
        assert!(price.contains_key(&expected_date));
        let value = price.get(&expected_date).unwrap();
        assert_eq!(Decimal::from(12.75), *value);
    }
}

#[cfg(test)]
mod amount_parsing_tests {
    use crate::{journal::Journal, parser::parse_post, pool::CommodityIndex, xact::Xact, amount::Decimal};

    use super::Amount;

    fn setup() -> Journal {
        let mut journal = Journal::new();
        let xact = Xact::create("2023-05-02", "", "Supermarket", "");
        journal.add_xact(xact);

        journal
    }

    #[test]
    fn test_positive_no_commodity() {
        let expected = Amount {
            quantity: 20.into(),
            commodity_index: None,
        };
        let actual = Amount::parse("20", None).unwrap();

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_negative_no_commodity() {
        let actual = Amount::parse("-20", None).unwrap();
        let expected = Amount {
            quantity: (-20).into(),
            commodity_index: None,
        };

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_pos_w_commodity_separated() {
        let expected = Amount {
            quantity: 20.into(),
            commodity_index: Some(CommodityIndex::new(0)),
        };
        let mut journal = setup();

        // Act

        parse_post("  Assets  20 EUR", 0, &mut journal);
        let post = journal.posts.first().unwrap();
        let Some(amount) = &post.amount else { todo!() }; // else None;

        // assert!(actual.is_some());
        assert_eq!(expected, *amount);

        // commodity
        let c = journal
            .commodity_pool
            .commodity_history
            .get_commodity(amount.commodity_index.unwrap());
        assert_eq!("EUR", c.symbol);
    }

    #[test]
    fn test_neg_commodity_separated() {
        let expected = Amount {
            quantity: (-20).into(),
            commodity_index: Some(CommodityIndex::new(0)),
        };
        let mut journal = setup();

        // Act
        parse_post("  Assets  -20 EUR", 0, &mut journal);

        // Assert
        let post = journal.posts.first().unwrap();
        let Some(a) = &post.amount else { panic!() };
        assert_eq!(&expected, a);

        let commodity = journal
            .commodity_pool
            .commodity_history
            .get_commodity(a.commodity_index.unwrap());
        assert_eq!("EUR", commodity.symbol);
    }

    #[test]
    fn test_full_w_commodity_separated() {
        // Arrange
        let mut journal = setup();

        // Act
        parse_post("  Assets  -20000.00 EUR", 0, &mut journal);
        let post = journal.posts.first().unwrap();
        let Some(ref amount) = post.amount else { panic!()};

        // Assert
        assert_eq!("-20000.00", amount.quantity.to_string());
        assert_eq!(
            "EUR",
            journal
                .commodity_pool
                .commodity_history
                .get_commodity(amount.commodity_index.unwrap())
                .symbol
        );
    }

    #[test]
    fn test_full_commodity_first() {
        // Arrange
        let mut journal = setup();

        // Act
        parse_post("  Assets  A$-20000.00", 0, &mut journal);
        let post = journal.posts.first().unwrap();
        let Some(ref amount) = post.amount else { panic!()};

        // Assert
        assert_eq!("-20000.00", amount.quantity.to_string());
        assert_eq!(
            "A$",
            journal
                .commodity_pool
                .commodity_history
                .get_commodity(amount.commodity_index.unwrap())
                .symbol
        );
    }

    #[test]
    fn test_quantity_separators() {
        let input = "-1000000.00";
        let expected = Decimal::from(-1_000_000);

        let amount = Amount::parse(input, None);
        assert!(amount.is_some());

        let actual = amount.unwrap().quantity;

        assert_eq!(expected, actual);
    }

    #[test]
    fn test_addition() {
        //let c1 = Commodity::new("EUR");
        let left = Amount::new(10.into(), None);
        // let c2 = Commodity::new("EUR");
        let right = Amount::new(15.into(), None);

        let actual = left + right;

        assert_eq!(Decimal::from(25), actual.quantity);
        // assert!(actual.commodity.is_some());
        // assert_eq!("EUR", actual.commodity.unwrap().symbol);
    }

    #[test]
    fn test_add_assign() {
        // let c1 = Commodity::new("EUR");
        let mut actual = Amount::new(21.into(), None);
        // let c2 = Commodity::new("EUR");
        let other = Amount::new(13.into(), None);

        // actual += addition;
        actual.add(&other);

        assert_eq!(Decimal::from(34), actual.quantity);
    }

    #[test]
    fn test_null_amount() {
        let input = " ";
        let actual = Amount::parse(input, None);

        assert_eq!(None, actual);
    }

    #[test]
    fn test_copy_from_no_commodity() {
        let other = Amount::new(10.into(), None);
        let actual = Amount::copy_from(&other);

        assert_eq!(Decimal::from(10), actual.quantity);
        // assert_eq!(None, actual.commodity);
    }
}