limabean 0.4.1

Beancount frontend using Rust and Clojure and the Lima parser
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
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
use beancount_parser_lima::{self as parser};
use limabean_booking::{
    Booking, Bookings, Interpolated, LimaParserBookingTypes, LimaTolerance, is_supported_method,
};

use rust_decimal::Decimal;
use std::{
    borrow::Cow,
    collections::{HashMap, HashSet, VecDeque},
    fmt::Debug,
};
use tabulator::{Align, Cell};
use time::Date;

use crate::api::types::{ElementIdx, IndexedReport, booked, raw};

#[derive(Debug)]
pub(crate) struct Accumulator<'a, 'd, 't> {
    // hashbrown HashMaps are used here for their Entry API, which is still unstable in std::collections::HashMap
    open_accounts: hashbrown::HashMap<&'a str, ElementIdx>,
    closed_accounts: hashbrown::HashMap<&'a str, ElementIdx>,
    accounts: HashMap<&'a str, AccountBuilder<'a, 'd>>,
    currency_usage: hashbrown::HashMap<&'a str, i32>,
    default_booking: Booking,
    tolerance: &'t LimaTolerance<'a>,
    warnings: Vec<IndexedReport>,
}

pub(crate) struct BookingSuccess<'a> {
    pub(crate) directives: Vec<booked::Directive<'a>>,
    pub(crate) warnings: Vec<IndexedReport>,
}

pub(crate) struct BookingFailure {
    pub(crate) errors: Vec<IndexedReport>,
}

impl<'a, 'd, 't> Accumulator<'a, 'd, 't> {
    pub(crate) fn new(default_booking: Booking, tolerance: &'t LimaTolerance<'a>) -> Self {
        Self {
            open_accounts: hashbrown::HashMap::default(),
            closed_accounts: hashbrown::HashMap::default(),
            accounts: HashMap::default(),
            currency_usage: hashbrown::HashMap::default(),
            default_booking,
            tolerance,
            warnings: Vec::default(),
        }
    }

    // generate any errors before building
    fn validate<'b>(
        self,
        directives: Vec<booked::Directive<'b>>,
        mut errors: Vec<IndexedReport>,
    ) -> Result<BookingSuccess<'b>, BookingFailure>
    where
        'a: 'b,
    {
        let Self {
            accounts, warnings, ..
        } = self;

        // check for unused pad directives
        for account in accounts.values() {
            if let Some((_, pad)) = &account.pad {
                errors.push(pad.report("unused, no balance directive"))
            }
        }

        if errors.is_empty() {
            Ok(BookingSuccess {
                directives,
                warnings,
            })
        } else {
            Err(BookingFailure { errors })
        }
    }

    pub(crate) fn collect<'r, 'b, I>(
        mut self,
        directives: I,
    ) -> Result<BookingSuccess<'b>, BookingFailure>
    where
        'a: 'r + 'b + 'd,
        'r: 'b + 'd,
        I: IntoIterator<Item = &'r raw::Directive<'a>>,
    {
        let mut errors = Vec::default();
        let mut booked_directives = Vec::default();

        for (raw_idx, raw) in directives.into_iter().enumerate() {
            match self.directive(
                raw,
                raw_idx.into(),
                booked_directives.len(),
                &mut booked_directives,
            ) {
                Ok((booked_variant, pad_txn)) => {
                    booked_directives.push(booked::Directive {
                        raw_idx,
                        date: raw.date,
                        tags: raw.tags.clone(),
                        links: raw.links.clone(),
                        metadata: raw.metadata.clone(),
                        variant: booked_variant,
                    });

                    if let Some(pad_txn) = pad_txn {
                        booked_directives.push(booked::Directive {
                            raw_idx,
                            date: raw.date,
                            tags: raw.tags.clone(),
                            links: raw.links.clone(),
                            metadata: raw.metadata.clone(),
                            variant: pad_txn,
                        });
                    }
                }
                Err(e) => {
                    errors.push(e);
                }
            }
        }

        self.validate(booked_directives, errors)
    }

    fn directive<'r, 'b>(
        &mut self,
        directive: &'r raw::Directive<'a>,
        element: ElementIdx,
        booked_idx: usize,
        booked_directives: &mut Vec<booked::Directive<'b>>,
    ) -> Result<
        (
            booked::DirectiveVariant<'b>,
            Option<booked::DirectiveVariant<'b>>,
        ),
        IndexedReport,
    >
    where
        'a: 'r + 'b + 'd,
        'r: 'b + 'd,
    {
        use booked::DirectiveVariant as BDV;
        use raw::DirectiveVariant as RDV;

        let date = directive.date;

        match &directive.variant {
            RDV::Transaction(transaction) => self
                .transaction(transaction, date, element)
                .map(|x| (x, None)),
            RDV::Price(price) => Ok((BDV::Price(price.clone()), None)),
            RDV::Balance(balance) => self
                .balance(balance, date, element, booked_directives)
                .map(|x| (x, None)),
            RDV::Open(open) => self.open(open, date, element).map(|x| (x, None)),
            RDV::Close(close) => self.close(close, date, element).map(|x| (x, None)),
            RDV::Commodity(commodity) => Ok((BDV::Commodity(commodity.clone()), None)),
            RDV::Pad(pad) => self.pad(pad, date, booked_idx, element, booked_directives),
            RDV::Document(document) => Ok((BDV::Document(document.clone()), None)),
            RDV::Note(note) => Ok((BDV::Note(note.clone()), None)),
            RDV::Event(event) => Ok((BDV::Event(event.clone()), None)),
            RDV::Query(query) => Ok((BDV::Query(query.clone()), None)),
            RDV::Custom(custom) => Ok((BDV::Custom(custom.clone()), None)),
        }
    }

    fn transaction<'r, 'b>(
        &mut self,
        transaction: &'r raw::Transaction<'a>,
        date: Date,
        element: ElementIdx,
    ) -> Result<booked::DirectiveVariant<'b>, IndexedReport>
    where
        'a: 'r + 'b + 'd,
        'r: 'b + 'd,
    {
        let description = transaction.payee.as_ref().map_or_else(
            || {
                transaction
                    .narration
                    .as_ref()
                    .map_or("post", |narration| narration.as_ref())
            },
            |payee| payee.as_ref(),
        );

        let booked_postings = self.book(date, &transaction.postings, description, element)?;

        Ok(booked::DirectiveVariant::Transaction(booked::Transaction {
            flag: transaction.flag.clone(),
            payee: transaction.payee.as_ref().map(|payee| payee.as_ref()),
            narration: transaction
                .narration
                .as_ref()
                .map(|narration| narration.as_ref()),
            postings: booked_postings,
        }))
    }

    fn book<'r, 'b>(
        &mut self,
        date: Date,
        postings: &'r [raw::PostingSpec<'a>],
        description: &'d str,
        element: ElementIdx,
    ) -> Result<Vec<booked::Posting<'a>>, IndexedReport>
    where
        'a: 'r + 'b + 'd,
        'r: 'b + 'd,
    {
        // ugh, difference of reference vs value
        let postings = postings.iter().collect::<Vec<_>>();

        match limabean_booking::book(
            date,
            &postings,
            self.tolerance,
            |accname| self.accounts.get(accname).map(|acc| &acc.positions),
            |accname| {
                self.accounts
                    .get(accname)
                    .map(|acc| acc.booking)
                    .unwrap_or(self.default_booking)
            },
        ) {
            Ok(Bookings {
                interpolated_postings,
                updated_inventory,
            }) => {
                // check all postings have valid accounts and currencies
                // returning the first error
                if let Some(error) = interpolated_postings
                    .iter()
                    .zip(&postings)
                    .enumerate()
                    .filter_map(|(posting_idx, (interpolated, posting))| {
                        let posting_element = (element, posting_idx).into();
                        self.validate_account_and_currency(
                            posting.acc,
                            interpolated.currency,
                            posting_element,
                        )
                        .map_or_else(Some, |_| None)
                    })
                    .next()
                {
                    return Err(error);
                }

                // an interpolated posting arising from a reduction with multiple costs is mapped here to several postings,
                // each with a simple cost, so we don't have to deal with composite costs for a posting elsewhere
                let booked_postings = interpolated_postings
                    .into_iter()
                    .zip(&postings)
                    .enumerate()
                    .flat_map(|(posting_idx, (interpolated, posting))| {
                        let account = posting.acc;
                        let Interpolated {
                            units,
                            currency,
                            cost,
                            price,
                            ..
                        } = interpolated;

                        if let Some(costs) = cost {
                            costs
                                .into_currency_costs()
                                .map(|(cost_cur, cost)| booked::Posting {
                                    raw_idx: Some(posting_idx),
                                    flag: posting.flag.clone(),
                                    acc: account,
                                    units: cost.units,
                                    cur: currency,
                                    cost: Some(cur_posting_cost_to_cost(cost_cur, cost)),
                                    price: None,
                                    tags: posting.tags.clone(),
                                    links: posting.links.clone(),
                                    metadata: posting.metadata.clone(),
                                })
                                .collect::<Vec<_>>()
                        } else {
                            vec![booked::Posting {
                                raw_idx: Some(posting_idx),
                                flag: posting.flag.clone(),
                                acc: account,
                                units,
                                cur: currency,
                                cost: None,
                                price: price.map(|price| (&price).into()),
                                tags: posting.tags.clone(),
                                links: posting.links.clone(),
                                metadata: posting.metadata.clone(),
                            }]
                        }
                    })
                    .collect::<Vec<_>>();

                // group postings by account and currency for balance diagnostics
                let mut account_posting_amounts =
                    hashbrown::HashMap::<&str, VecDeque<Amount<'_>>>::new();
                for booked in &booked_postings {
                    use hashbrown::hash_map::Entry::*;

                    let currency = booked.cur;
                    let units = booked.units;

                    self.tally_currency_usage(currency);

                    let account_name = booked.acc;

                    match account_posting_amounts.entry(account_name) {
                        Occupied(entry) => {
                            entry.into_mut().push_back((units, currency).into());
                        }
                        Vacant(entry) => {
                            let mut amounts = VecDeque::new();
                            amounts.push_back((units, currency).into());
                            entry.insert(amounts);
                        }
                    }
                }

                for (account_name, updated_positions) in updated_inventory {
                    let account = self.get_mut_valid_account(account_name, element)?;

                    account.positions = updated_positions;

                    if let Some(mut posting_amounts) = account_posting_amounts.remove(account_name)
                    {
                        let last_amount = posting_amounts.pop_back().unwrap();

                        for amount in posting_amounts {
                            account.balance_diagnostics.push(BalanceDiagnostic {
                                date,
                                description: Some(description),
                                amount: Some(amount),
                                positions: None,
                            });
                        }

                        account.balance_diagnostics.push(BalanceDiagnostic {
                            date,
                            description: Some(description),
                            amount: Some(last_amount),
                            positions: Some(account.positions.clone()),
                        });
                    }
                }

                Ok(booked_postings)
            }
            Err(e) => {
                use limabean_booking::BookingError::*;

                match &e {
                    Transaction(e) => Err(element.report(e.to_string())),
                    Posting(idx, e) => {
                        // TODO attach posting error to actual posting
                        // let bad_posting = postings[*idx];
                        // bad_posting.error(e.to_string()).into()
                        Err(element.report(format!("{e} on posting {idx}")))
                    }
                }
            }
        }
    }

    fn validate_account(
        &self,
        account_name: &'a str,
        element: ElementIdx,
    ) -> Result<(), IndexedReport> {
        if self.open_accounts.contains_key(account_name) {
            Ok(())
        } else if let Some(closed) = self.closed_accounts.get(account_name) {
            Err(element.report("account was closed").related_to(*closed))
        } else {
            Err(element.report("account not open"))
        }
    }

    fn get_valid_account(
        &self,
        account_name: &'a str,
        element: ElementIdx,
    ) -> Result<&AccountBuilder<'a, 'd>, IndexedReport> {
        self.validate_account(account_name, element)?;
        Ok(self.accounts.get(account_name).unwrap())
    }

    fn get_mut_valid_account(
        &mut self,
        account_name: &'a str,
        element: ElementIdx,
    ) -> Result<&mut AccountBuilder<'a, 'd>, IndexedReport> {
        self.validate_account(account_name, element)?;
        Ok(self.accounts.get_mut(account_name).unwrap())
    }

    fn validate_account_and_currency(
        &self,
        account_name: &'a str,
        currency: &'a str,
        element: ElementIdx,
    ) -> Result<(), IndexedReport> {
        let account = self.get_valid_account(account_name, element)?;
        account.validate_currency(currency, element)
    }

    fn tally_currency_usage(&mut self, currency: &'a str) {
        use hashbrown::hash_map::Entry::*;

        match self.currency_usage.entry(currency) {
            Occupied(mut usage) => {
                let usage = usage.get_mut();
                *usage += 1;
            }
            Vacant(usage) => {
                usage.insert(1);
            }
        }
    }

    // get the total units for given currency in an account
    fn total_units_for_currency(&self, account_name: &str, currency: &str) -> Decimal {
        self.accounts
            .get(account_name)
            .map(|account| {
                account
                    .positions
                    .units()
                    .iter()
                    .filter_map(|(cur, number)| (**cur == currency).then_some(*number))
                    .sum()
            })
            .unwrap_or_default()
        // }
    }

    fn balance<'r, 'b>(
        &mut self,
        balance: &'r raw::Balance<'a>,
        date: Date,
        element: ElementIdx,
        booked_directives: &mut [booked::Directive<'b>],
    ) -> Result<booked::DirectiveVariant<'b>, IndexedReport>
    where
        'a: 'r + 'b,
        'r: 'b,
    {
        let margin = calculate_balance_margin(
            balance.units,
            balance.tolerance.unwrap_or(Decimal::ZERO),
            self.total_units_for_currency(balance.acc, balance.cur),
        );

        let account = self.get_mut_valid_account(balance.acc, element)?;
        account.validate_currency(balance.cur, element)?;
        // pad can't last beyond balance
        let pad = account.pad.take();

        if margin.is_none() {
            // balance assertion is correct, and we already cleared the pad, so:

            account.balance_diagnostics.clear();

            // but if there was a pad directive, we ought to have used it, so:
            if let Some((_, pad_idx)) = pad {
                return Err(pad_idx.report("unused, no balance adjustment required"));
            } else {
                return Ok(booked::DirectiveVariant::Balance(balance.clone()));
            }
        }
        let margin = margin.unwrap();

        if pad.is_none() {
            // balance assertion is incorrect and we have no pad to take up the slack, so:

            let err = Err(construct_balance_error_and_clear_diagnostics(
                account,
                balance.cur,
                margin,
                element,
            ));

            // even though we have a balance error, we adjust the account to match, in order to localise balance failures
            adjust_account_to_match_balance(account, balance.cur, margin, Adjustment::Add);

            return err;
        }
        let (booked_pad_idx, _) = pad.unwrap();

        adjust_account_to_match_balance(account, balance.cur, margin, Adjustment::Add);
        account.balance_diagnostics.clear();

        // initialize balance diagnostics according to balance assertion
        let mut positions = Positions::default();
        positions.accumulate(balance.units, balance.cur, None, Booking::default());
        account.balance_diagnostics.push(BalanceDiagnostic {
            date,
            description: None,
            amount: None,
            positions: Some(positions),
        });

        let booked::DirectiveVariant::Pad(pad) = &booked_directives[booked_pad_idx].variant else {
            panic!(
                "directive at pad_idx {} is not a pad, is {:?}",
                booked_pad_idx, &booked_directives[booked_pad_idx]
            );
        };
        let pad_source = pad.source;

        let booked::DirectiveVariant::Transaction(txn) =
            &mut booked_directives[booked_pad_idx + 1].variant
        else {
            panic!(
                "directive at pad_idx {} is not a pad, is {:?}",
                booked_pad_idx + 1,
                &booked_directives[booked_pad_idx + 1]
            );
        };

        txn.postings = calculate_balance_pad_postings(balance.cur, margin, balance.acc, pad_source);

        let pad_account = self.accounts.get_mut(pad_source).unwrap();
        adjust_account_to_match_balance(pad_account, balance.cur, margin, Adjustment::Subtract);

        Ok(booked::DirectiveVariant::Balance(balance.clone()))
    }

    fn open<'r, 'b>(
        &mut self,
        open: &'r raw::Open<'a>,
        _date: Date,
        element: ElementIdx,
    ) -> Result<booked::DirectiveVariant<'b>, IndexedReport>
    where
        'a: 'r + 'b,
        'r: 'b,
    {
        use hashbrown::hash_map::Entry::*;
        match self.open_accounts.entry(open.acc) {
            Occupied(open_entry) => {
                return Err(element
                    .report("account already opened")
                    .related_to(*open_entry.get()));
            }
            Vacant(open_entry) => {
                open_entry.insert(element);

                // cannot reopen a closed account
                if let Some(closed) = self.closed_accounts.get(open.acc) {
                    return Err(element.report("account was closed").related_to(*closed));
                } else {
                    let mut booking = open
                        .booking
                        .map(|booking| booking.into())
                        .unwrap_or(self.default_booking);

                    if !is_supported_method(booking) {
                        let default_booking = Booking::default();
                        self.warnings.push(
                            element.report(format!( "booking method {booking} unsupported, falling back to default {default_booking}" )),
                        );
                        booking = default_booking;
                    }

                    self.accounts.insert(
                        open.acc,
                        AccountBuilder::new(
                            open.currencies.iter().flatten().copied(),
                            booking,
                            element,
                        ),
                    );
                }
            }
        }

        if let Some(booking) = open.booking {
            if is_supported_method(booking.into()) {
            } else {
                self.warnings
                    .push(element.report("booking method {} unsupported, falling back to default"));
            }
        }

        Ok(booked::DirectiveVariant::Open(open.clone()))
    }

    fn close<'r, 'b>(
        &mut self,
        close: &'r raw::Close<'a>,
        _date: Date,
        element: ElementIdx,
    ) -> Result<booked::DirectiveVariant<'b>, IndexedReport>
    where
        'a: 'r + 'b,
        'r: 'b,
    {
        use hashbrown::hash_map::Entry::*;
        match self.open_accounts.entry(close.acc) {
            Occupied(open_entry) => {
                match self.closed_accounts.entry(close.acc) {
                    Occupied(closed_entry) => {
                        // cannot reclose a closed account
                        return Err(element
                            .report("account was already closed")
                            .related_to(*closed_entry.get()));
                    }
                    Vacant(closed_entry) => {
                        open_entry.remove_entry();
                        closed_entry.insert(element);
                    }
                }
            }
            Vacant(_) => {
                return Err(element.report("account not open"));
            }
        }

        Ok(booked::DirectiveVariant::Close(close.clone()))
    }

    fn pad<'r, 'b>(
        &mut self,
        pad: &'r raw::Pad<'a>,
        _date: Date,
        idx: usize,
        element: ElementIdx,
        booked_directives: &[booked::Directive<'b>],
    ) -> Result<
        (
            booked::DirectiveVariant<'b>,
            Option<booked::DirectiveVariant<'b>>,
        ),
        IndexedReport,
    >
    where
        'a: 'r + 'b,
        'r: 'b,
    {
        let account = self.get_mut_valid_account(pad.acc, element)?;

        let unused_pad = account.pad.take();

        // unused pad directives are errors
        // https://beancount.github.io/docs/beancount_language_syntax.html#unused-pad-directives
        if let Some((_, unused_pad)) = unused_pad {
            return Err(unused_pad
                .report("unused, second pad encountered")
                .related_to(element));
        }

        account.pad = Some((idx, element));

        Ok((
            booked::DirectiveVariant::Pad(pad.clone()),
            Some(booked::DirectiveVariant::Transaction(booked::Transaction {
                flag: Cow::Borrowed(PAD_FLAG),
                payee: None,
                narration: None,
                postings: Vec::default(),
            })),
        ))
    }
}

fn calculate_balance_margin(
    balance_units: Decimal,
    balance_tolerance: Decimal,
    account_units: Decimal,
) -> Option<Decimal> {
    // what's the gap between what we have and what the balance says we should have?
    let margin = balance_units - account_units;
    (margin.abs() > balance_tolerance).then_some(margin)
}

fn calculate_balance_pad_postings<'a>(
    cur: &'a str,
    margin: Decimal,
    balance_account: &'a str,
    pad_source: &'a str,
) -> Vec<booked::Posting<'a>> {
    vec![
        booked::Posting {
            raw_idx: None,
            flag: Some(Cow::Borrowed(PAD_FLAG)),
            acc: balance_account,
            units: margin,
            cur,
            cost: None,
            price: None,
            tags: None,
            links: None,
            metadata: None,
        },
        booked::Posting {
            raw_idx: None,
            flag: Some(Cow::Borrowed(PAD_FLAG)),
            acc: pad_source,
            units: -margin,
            cur,
            cost: None,
            price: None,
            tags: None,
            links: None,
            metadata: None,
        },
    ]
}

fn construct_balance_error_and_clear_diagnostics<'a, 'd>(
    account: &mut AccountBuilder<'a, 'd>,
    cur: &'a str,
    margin: Decimal,
    element: ElementIdx,
) -> IndexedReport {
    let reason = format!(
        "accumulated {}, error {} {}",
        if account.positions.is_empty() {
            "zero".to_string()
        } else {
            account.positions.to_string()
        },
        margin,
        cur,
    );

    // determine context for error by collating postings since last balance
    let annotation = Cell::Stack(
        account
            .balance_diagnostics
            .drain(..)
            .map(|bd| {
                Cell::Row(
                    vec![
                        (bd.date.to_string(), Align::Left).into(),
                        bd.amount.map(|amt| amt.into()).unwrap_or(Cell::Empty),
                        bd.positions.map(positions_into_cell).unwrap_or(Cell::Empty),
                        bd.description
                            .map(|d| (d, Align::Left).into())
                            .unwrap_or(Cell::Empty),
                    ],
                    GUTTER_MEDIUM,
                )
            })
            .collect::<Vec<_>>(),
    );

    element
        .report(reason)
        .with_annotation(annotation.to_string())
}

#[derive(PartialEq, Eq, Debug)]
enum Adjustment {
    Add,
    Subtract,
}

fn adjust_account_to_match_balance<'a, 'd>(
    account: &mut AccountBuilder<'a, 'd>,
    cur: &'a str,
    units: Decimal,
    adjustment: Adjustment,
) {
    use Adjustment::*;

    // reset accumulated balance to what was asserted, to localise errors
    account.positions.accumulate(
        if adjustment == Add { units } else { -units },
        cur,
        None,
        Booking::default(),
    );
    // booking method doesn't matter if no cost
}

#[derive(Debug)]
struct AccountBuilder<'a, 'd> {
    allowed_currencies: HashSet<&'a str>,
    positions: Positions<'a>,
    opened: ElementIdx,
    pad: Option<(usize, ElementIdx)>,
    balance_diagnostics: Vec<BalanceDiagnostic<'a, 'd>>,
    booking: Booking,
}

impl<'a, 'd> AccountBuilder<'a, 'd> {
    fn new<I>(allowed_currencies: I, booking: Booking, opened: ElementIdx) -> Self
    where
        I: Iterator<Item = &'a str>,
    {
        AccountBuilder {
            allowed_currencies: allowed_currencies.collect(),
            positions: Positions::default(),
            opened,
            pad: None,
            balance_diagnostics: Vec::default(),
            booking,
        }
    }

    /// all currencies are valid unless any were specified during open
    fn is_currency_valid(&self, currency: &'a str) -> bool {
        self.allowed_currencies.is_empty() || self.allowed_currencies.contains(currency)
    }

    fn validate_currency(
        &self,
        currency: &'a str,
        element: ElementIdx,
    ) -> Result<(), IndexedReport> {
        if self.is_currency_valid(currency) {
            Ok(())
        } else {
            Err(element
                .report("currency incompatible with account")
                .related_to(self.opened))
        }
    }
}

#[derive(Debug)]
struct BalanceDiagnostic<'a, 'd> {
    date: Date,
    description: Option<&'d str>,
    amount: Option<Amount<'a>>,
    positions: Option<Positions<'a>>,
}

const PAD_FLAG: &str = "'P";

#[derive(PartialEq, Eq, Clone, Debug)]
struct Amount<'a> {
    number: Decimal,
    currency: &'a str,
}

impl<'a> From<(Decimal, &'a str)> for Amount<'a> {
    fn from(value: (Decimal, &'a str)) -> Self {
        Self {
            number: value.0,
            currency: value.1,
        }
    }
}

impl<'a> From<&'a parser::Amount<'a>> for Amount<'a> {
    fn from(value: &'a parser::Amount<'a>) -> Self {
        Amount {
            number: value.number().value(),
            currency: value.currency().item().into(),
        }
    }
}

impl<'a> From<Amount<'a>> for Cell<'static, 'static> {
    fn from(value: Amount) -> Self {
        Cell::Row(
            vec![
                value.number.into(),
                (value.currency.to_string(), Align::Left).into(),
            ],
            GUTTER_MINOR,
        )
    }
}

impl<'a> From<&'_ Amount<'a>> for Cell<'a, 'static> {
    fn from(value: &'_ Amount<'a>) -> Self {
        Cell::Row(
            vec![value.number.into(), (value.currency, Align::Left).into()],
            GUTTER_MINOR,
        )
    }
}

type Positions<'a> = limabean_booking::Positions<limabean_booking::LimaParserBookingTypes<'a>>;

// should be From, but both types are third-party
fn positions_into_cell<'a>(positions: Positions<'a>) -> Cell<'a, 'static> {
    Cell::Stack(
        positions
            .into_iter()
            .map(position_into_cell)
            .collect::<Vec<_>>(),
    )
}

type Position<'a> = limabean_booking::Position<limabean_booking::LimaParserBookingTypes<'a>>;

fn position_into_cell<'a>(position: Position<'a>) -> Cell<'a, 'static> {
    let Position {
        units,
        currency,
        cost,
    } = position;
    let mut cells = vec![
        units.into(),
        (Into::<&str>::into(currency), Align::Left).into(),
    ];
    if let Some(cost) = cost {
        cells.push(cost_into_cell(cost))
    }
    Cell::Row(cells, GUTTER_MINOR)
}

type Cost<'a> = limabean_booking::Cost<limabean_booking::LimaParserBookingTypes<'a>>;
fn cost_into_cell<'a>(cost: Cost<'a>) -> Cell<'a, 'static> {
    let Cost {
        date,
        per_unit,
        total: _total,
        currency,
        label,
        merge,
    } = cost;
    let mut cells = vec![
        (date.to_string(), Align::Left).into(),
        per_unit.into(),
        (Into::<&str>::into(currency), Align::Left).into(),
    ];
    if let Some(label) = label {
        cells.push((label.clone(), Align::Left).into())
    }
    if merge {
        cells.push(("*", Align::Left).into())
    }
    Cell::Row(cells, GUTTER_MINOR)
}

fn cur_posting_cost_to_cost<'a>(
    currency: &'a str,
    cost: limabean_booking::PostingCost<LimaParserBookingTypes<'a>>,
) -> booked::Cost<'a> {
    booked::Cost {
        date: cost.date,
        per_unit: cost.per_unit,
        total: cost.total,
        cur: currency,
        label: cost.label,
        merge: cost.merge,
    }
}

const GUTTER_MINOR: &str = " ";
const GUTTER_MEDIUM: &str = "  ";