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

#[cfg(all(test, feature = "unstable"))]
use crate::pest_parser::{Pair, Rule};
use crate::{
    account::{account, Account},
    amount::{amount, Amount},
    string::{comment, string},
};

use super::{date, flag, Date, 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> {
    pub(crate) flag: Option<Flag>,
    pub(crate) account: Account<'a>,
    pub(crate) amount: Option<Amount<'a>>,
    pub(crate) price: Option<(PriceType, Amount<'a>)>,
    pub(crate) lot_attributes: Option<LotAttributes<'a>>,
    pub(crate) 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.lot_attributes.as_ref().and_then(|la| la.cost.as_ref())
    }

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

    #[cfg(all(test, feature = "unstable"))]
    pub(super) fn from_pair(pair: Pair<'_>) -> Posting<'_> {
        let mut flag = None;
        let mut account = None;
        let mut amount = None;
        let mut comment = None;
        for pair in pair.into_inner() {
            match pair.as_rule() {
                Rule::account => account = Some(Account::from_pair(pair)),
                Rule::amount => amount = Some(Amount::from_pair(pair)),
                Rule::transaction_flag => flag = Some(Flag::from_pair(pair)),
                Rule::comment => comment = Some(pair.as_str()),
                _ => (),
            }
        }
        Posting {
            flag,
            account: account.expect("no account in posting"),
            price: None,
            lot_attributes: None,
            comment,
            amount,
        }
    }
}

/// 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,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LotAttributes<'a> {
    cost: Option<Amount<'a>>,
    date: Option<Date>,
    label: Option<String>,
}

enum LotAttribute<'a> {
    Cost(Amount<'a>),
    Date(Date),
    Label(String),
}

fn lot_attributes(input: &str) -> IResult<&str, LotAttributes<'_>> {
    let (input, attrs) = separated_list0(
        tuple((space0, char(','), space0)),
        alt((
            map(amount, LotAttribute::Cost),
            map(date, LotAttribute::Date),
            map(string, LotAttribute::Label),
        )),
    )(input)?;

    Ok((
        input,
        attrs.iter().fold(
            LotAttributes {
                cost: None,
                date: None,
                label: None,
            },
            |acc, attr| match attr {
                LotAttribute::Cost(c) => LotAttributes {
                    cost: Some(c.clone()),
                    ..acc
                },
                LotAttribute::Date(d) => LotAttributes {
                    date: Some(*d),
                    ..acc
                },
                LotAttribute::Label(s) => LotAttributes {
                    label: Some(s.to_string()),
                    ..acc
                },
            },
        ),
    ))
}

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)),
                    lot_attributes,
                    preceded(space0, char('}')),
                ),
            )),
            opt(preceded(space1, price)),
            opt(preceded(space0, comment)),
        )),
        |(flag, account, amount, lot_attributes, price, comment)| Posting {
            flag,
            account,
            amount,
            price,
            lot_attributes,
            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 crate::account::Type as AccountType;

    use super::*;

    #[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")));
    }

    #[rstest]
    fn with_empty_cost_and_nonempty_price(
        #[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!(posting.cost().is_none());
        assert_eq!(
            posting.price(),
            Some((PriceType::Unit, &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_date_and_label() {
        let input = "Assets:A:B 10 CHF {1 EUR, 2022-10-14, \"label\"}";
        let (_, posting) = posting(input).expect("should successfully parse the posting");
        assert_eq!(posting.cost(), Some(&Amount::new(1, "EUR")));
    }

    #[test]
    fn with_cost_and_no_date_and_label() {
        let input = "Assets:A:B 10 CHF {1 EUR, \"label\"}";
        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());
    }
}