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
use nom::{
    branch::alt,
    bytes::complete::{tag, take_till},
    character::complete::{char, space0, space1},
    combinator::{map, opt},
    sequence::{delimited, preceded, separated_pair, terminated, tuple},
    IResult,
};

use crate::{
    account::{account, Account},
    amount::{amount, Amount},
    string::comment,
};

use super::{flag, Flag};

/// A posting
///
/// It is the association of an [`Account`] and an [`Amount`].
/// (though the amount is optional)
///
/// A posting may also have, price and cost defined after the amount.
///
/// # Examples of postings
///
/// * `Assets:A:B 10 CHF` (most common form)
/// * `! Assets:A:B 10 CHF` (with pending flag)
/// * `Assets:A:B 10 CHF @ 1 EUR` (with price)
/// * `Assets:A:B 10 CHF {2 USD}` (with cost)
/// * `Assets:A:B` (without amount)
#[derive(Debug, Clone, PartialEq)]
pub struct Posting<'a> {
    flag: Option<Flag>,
    account: Account<'a>,
    amount: Option<Amount<'a>>,
    price: Option<(PriceType, Amount<'a>)>,
    cost: Option<Amount<'a>>,
    comment: Option<&'a str>,
}

impl<'a> Posting<'a> {
    /// Returns the flag on this posting (if present)
    #[must_use]
    pub fn flag(&self) -> Option<Flag> {
        self.flag
    }

    /// Returns the account referenced by this posting
    #[must_use]
    pub fn account(&self) -> &Account<'a> {
        &self.account
    }

    /// Returns the amount of the posting (if present)
    #[must_use]
    pub fn amount(&self) -> Option<&Amount<'a>> {
        self.amount.as_ref()
    }

    /// Returns a tuple of price-type and the price (if a price was defined)
    #[must_use]
    pub fn price(&self) -> Option<(PriceType, &Amount<'a>)> {
        self.price.as_ref().map(|(t, p)| (*t, p))
    }

    /// Returns the cost (if present)
    #[must_use]
    pub fn cost(&self) -> Option<&Amount<'a>> {
        self.cost.as_ref()
    }

    /// Returns the comment (if present)
    #[must_use]
    pub fn comment(&self) -> Option<&str> {
        self.comment
    }
}

/// A price type
///
/// A price associated to an amount is either per-unit (`@`) or a total price (`@@`)
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum PriceType {
    /// Per-unit price
    Unit,
    /// Total price
    Total,
}

pub fn posting(input: &str) -> IResult<&str, Posting<'_>> {
    map(
        tuple((
            opt(terminated(flag, space1)),
            account,
            opt(preceded(space1, amount)),
            opt(preceded(
                space1,
                delimited(
                    tuple((char('{'), space0)),
                    amount,
                    tuple((
                        space0,
                        opt(tuple((char(','), take_till(|c| c == '}')))),
                        char('}'),
                    )),
                ),
            )),
            opt(preceded(space1, price)),
            opt(preceded(space0, comment)),
        )),
        |(flag, account, amount, cost, price, comment)| Posting {
            flag,
            account,
            amount,
            price,
            cost,
            comment,
        },
    )(input)
}

fn price(input: &str) -> IResult<&str, (PriceType, Amount<'_>)> {
    separated_pair(
        alt((
            map(tag("@@"), |_| PriceType::Total),
            map(char('@'), |_| PriceType::Unit),
        )),
        space1,
        amount,
    )(input)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::account::Type as AccountType;
    use rstest::rstest;

    #[test]
    fn simple_posting() {
        let input = "Assets:A:B 10 CHF";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(
            posting.account(),
            &Account::new(AccountType::Assets, ["A", "B"])
        );
        assert_eq!(posting.amount(), Some(&Amount::new(10, "CHF")));
        assert!(posting.price().is_none());
        assert!(posting.cost().is_none());
        assert!(posting.comment().is_none());
    }

    #[test]
    fn without_amount() {
        let input = "Assets:A:B";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert!(posting.amount().is_none());
    }

    #[test]
    fn with_price() {
        let input = "Assets:A:B 10 CHF @ 1 EUR";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(
            posting.price(),
            Some((PriceType::Unit, &Amount::new(1, "EUR")))
        );
    }

    #[test]
    fn with_total_price() {
        let input = "Assets:A:B 10 CHF @@ 9 EUR";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(
            posting.price(),
            Some((PriceType::Total, &Amount::new(9, "EUR")))
        );
    }

    #[rstest]
    fn with_cost(
        #[values("Assets:A:B 10 CHF {1 EUR}", "Assets:A:B 10 CHF { 1 EUR }")] input: &str,
    ) {
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(posting.cost(), Some(&Amount::new(1, "EUR")));
    }

    #[test]
    fn with_cost_and_date() {
        let input = "Assets:A:B 10 CHF {1 EUR, 2022-10-14}";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(posting.cost(), Some(&Amount::new(1, "EUR")));
    }

    #[test]
    fn with_cost_and_price() {
        let input = "Assets:A:B 10 CHF {2 USD} @ 1 EUR";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(posting.cost(), Some(&Amount::new(2, "USD")));
        assert_eq!(
            posting.price(),
            Some((PriceType::Unit, &Amount::new(1, "EUR")))
        );
    }

    #[test]
    fn with_flag() {
        let (_, posting) =
            posting("! Assets:A 1 EUR").expect("should successfully parse the posting");
        assert_eq!(posting.flag(), Some(Flag::Pending));
    }

    #[test]
    fn with_comment() {
        let input = "Assets:A:B 10 CHF ; Cool!";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(posting.comment(), Some("Cool!"));
    }

    #[rstest]
    fn invalid(#[values("")] input: &str) {
        assert!(posting(input).is_err());
    }
}