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
use super::{Money,Amount, ItemList, BillItem, BillProduct};
use tax::Tax;
use std::collections::BTreeMap;
use std::ops::Deref;
#[derive(Debug)]
#[cfg_attr(feature = "serialization", derive(Serialize))]
pub struct Bill<P> {
pub items_by_tax: BTreeMap<Tax, ItemList<P>>,
}
impl<P: BillProduct> Deref for Bill<P> {
type Target = BTreeMap<Tax, ItemList<P>>;
fn deref(&self) -> &BTreeMap<Tax, ItemList<P>> {
&self.items_by_tax
}
}
impl<P:BillProduct> Bill<P> {
pub fn new() -> Self {
Bill { items_by_tax: BTreeMap::new() }
}
pub fn to_items_with_tax(&self) -> BTreeMap<Tax, &BillItem<P>> {
self.as_items_with_tax().into_iter().collect()
}
pub fn as_items_with_tax(&self) -> Vec<(Tax, &BillItem<P>)> {
let mut out = Vec::new();
for (tax, items) in self.items_by_tax.iter().rev() {
for item in items.iter(){
out.push((tax.to_owned(), item));
}
}
out
}
pub fn as_items(&self) -> Vec<&BillItem<P>> {
self.as_items_with_tax().into_iter().map(|(_,item)|item).collect()
}
pub fn add(&mut self, item:BillItem<P>) {
let tax = item.product.tax();
self.items_by_tax.entry(tax).or_insert_with(ItemList::new).push(item);
}
pub fn add_item(&mut self, amount: Amount, product: P) {
let item = BillItem {
amount: amount,
product: product,
};
self.add(item)
}
pub fn sums_by_tax(&self) -> BTreeMap<Tax, Money> {
self.items_by_tax
.iter()
.map(|(tax, items)| (*tax, items.gross_sum()) )
.collect()
}
pub fn gross_total(&self) -> Money {
self.items_by_tax
.iter()
.map(|(_, items)| items.gross_sum())
.fold(Money::default(), |acc, x| acc + x)
}
pub fn tax_total(&self) -> Money {
self.items_by_tax
.iter()
.map(|(_, items)| items.tax_sum())
.fold(Money::default(), |acc, x| acc + x)
}
pub fn net_total(&self) -> Money {
self.items_by_tax
.iter()
.map(|(_, items)| items.net_sum())
.fold(Money::default(), |acc, x| acc + x)
}
}