baggins 0.2.0

Utilities to Perform Sales Calculation Operations
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
// Copyright 2023 Andrés Reyes El Programador Pobre.
//
//! baggins
//!
//! `baggins` provides a series of utilities to easily and efficiently calculate sales operations.
//! Due to the nature of monetary calculations, the Bigdecimal crate is used as a backend.
//!
//! The focus is on ease of use and learning Rust, so there are many opportunities for improvement.
//!
//! `baggins` provee una serie de utilidades para calcular facil y eficientemente totales
//! y subtotales de lineas de detalle de procesos de venta.
//! El foco está en la facilidad de uso y en aprender Rust, por lo que hay muchas oportunidades de mejora.
//!
//!
use bigdecimal::{BigDecimal, FromPrimitive, Zero};
use discount::Discounter;
use serde::Serialize;
use std::{fmt, str::FromStr};
use tax::Taxer;

pub mod discount;
pub mod tax;

/// handy utility to get 100.0 as BigDecimal
pub fn hundred() -> BigDecimal {
    BigDecimal::from_str("100.0").unwrap()
}

/// handy utility to get 1.0 as BigDecimal
pub fn one() -> BigDecimal {
    BigDecimal::from_str("1.0").unwrap()
}

/// handy utility to get -1.0 as BigDecimal
pub fn inverse() -> BigDecimal {
    BigDecimal::from_str("-1.0").unwrap()
}

/// handy utility to get 0.0 as BigDecimal. Just a wrapper for zero()
pub fn zero() -> BigDecimal {
    BigDecimal::zero()
}

#[derive(Debug)]
/// The error type for baggins operations - El tipo de error para operaciones de baggins
///
/// Everything in life can end in a huge mistake, and the operations that baggins performs
/// They are not the exception. We have tried to prepare the most common errors.
///
/// Todo en la vida puede terminar en un enorme error, y las operaciones que baggins realiza
/// no son la excepción. Hemos tratado de preparar los errores mas comunes.
///
/// # Example
///
/// ```
///  use baggins::discount::Mode;
///  use baggins::DetailCalculator;
///  use crate::baggins::Calculator;
///
///  let mut c = DetailCalculator::new();
///
///  c.add_discount_from_str("22.74", Mode::Percentual);
///
///  let r = c.compute_from_str("120.34", "-10", None);
///
///  match r {
///      Ok(calculation) => {
///          println!("this branch will not be executed");
///      }
///      Err(err) => {
///          println!("this will print a bagginsError::NegativeQty {}", err);
///      }
///  }
/// ```
///
pub enum BagginsError<S: Into<String>> {

    /// Error due to pass a negative quantity
    NegativeQty(S),

    /// Error for not being able to convert a value to [BigDecimal]
    InvalidDecimalValue(S),

    /// Any other unspecified error
    Other(S),
}

impl<S: Into<String> + Clone> fmt::Display for BagginsError<S> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            BagginsError::NegativeQty(msg) => {
                write!(f, "Negative quantity value Error: {}", msg.clone().into())
            }
            BagginsError::InvalidDecimalValue(msg) => {
                write!(f, " Invalid decimal value {}", msg.clone().into())
            }
            BagginsError::Other(msg) => write!(f, " Error {}", msg.clone().into()),
        }
    }
}

#[derive(Debug, Serialize)]
/// will contain the result of the computing of the specified subtotal
pub struct CalculationWithDiscount {
    /// stores the unit value multiplied by the quantity minus the discount
    pub net: BigDecimal,
    /// stores the net plus taxes
    pub brute: BigDecimal,
    /// stores the cumulated tax calculated over net
    pub tax: BigDecimal,
    /// stores the cumulated discount value
    pub discount_value: BigDecimal,
    /// stores the cumulated discount value
    pub discount_brute_value: BigDecimal,
    /// stores the total discount applied as a percentage
    pub total_discount_percent: BigDecimal,
    /// stores the unit value with discounts applied
    pub unit_value: BigDecimal,
}

impl CalculationWithDiscount {
    /// Creates a new [`CalculationWithDiscount`].
    pub fn new(
        net: BigDecimal,
        brute: BigDecimal,
        tax: BigDecimal,
        discount_value: BigDecimal,
        discount_brute_value: BigDecimal,
        total_discount_percent: BigDecimal,
        unit_value: BigDecimal,
    ) -> Self {
        Self {
            net,
            brute,
            tax,
            discount_value,
            discount_brute_value,
            total_discount_percent,
            unit_value,
        }
    }

    pub fn round(&self, scale: i64) -> Self {
        let scale = if !(0..=128).contains(&scale) { 128 } else { scale };
        Self { 
            net: self.net.round(scale), 
            brute: self.brute.round(scale), 
            tax: self.tax.round(scale), 
            discount_value: self.discount_value.round(scale), 
            discount_brute_value: self.discount_brute_value.round(scale), 
            total_discount_percent: self.total_discount_percent.round(scale), 
            unit_value: self.unit_value.clone(), 
        }
    }
}

impl Default for CalculationWithDiscount {
    fn default() -> Self {
        Self {
            net: zero(),
            brute: zero(),
            tax: zero(),
            discount_value: zero(),
            discount_brute_value: zero(),
            total_discount_percent: zero(),
            unit_value: zero(),
        }
    }
}

impl fmt::Display for CalculationWithDiscount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "net {}, brute {}, tax {}, discount value {}, discount brute value {}, total discount percent {}, unit_value {} )",
            self.net,
            self.brute,
            self.tax,
            self.discount_value,
            self.discount_brute_value,
            self.total_discount_percent,
            self.unit_value,
        )
    }
}

#[derive(Debug, Serialize)]
/// will contain the result of the computing of the specified subtotal without discounts
pub struct CalculationWithoutDiscount {
    /// stores the unit value multiplied by the quantity
    pub net: BigDecimal,
    /// stores the net plus taxes
    pub brute: BigDecimal,
    /// stores the cumulated tax calculated over net
    pub tax: BigDecimal,
    /// stores the used unit value
    pub unit_value: BigDecimal,
}

impl CalculationWithoutDiscount {
    /// Creates a new [`CalculationWithoutDiscount`].
    pub fn new(
        net: BigDecimal,
        brute: BigDecimal,
        tax: BigDecimal,
        unit_value: BigDecimal,
    ) -> Self {
        Self {
            net,
            brute,
            tax,
            unit_value,
        }
    }

    pub fn round(&self, scale: i64) -> Self {
        let scale = if !(0..=128).contains(&scale) { 128 } else { scale };
        Self { 
            net: self.net.round(scale), 
            brute: self.brute.round(scale), 
            tax: self.tax.round(scale), 
            unit_value: self.unit_value.clone(), 
        }
    }
}

impl Default for CalculationWithoutDiscount {
    fn default() -> Self {
        Self {
            net: zero(),
            brute: zero(),
            tax: zero(),
            unit_value: zero(),
        }
    }
}

impl fmt::Display for CalculationWithoutDiscount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "net {}, brute {}, tax {}, unit_value {})",
            self.net, self.brute, self.tax, self.unit_value,
        )
    }
}

#[derive(Debug, Serialize, Default)]
pub struct Calculation {
    without_discount_values: CalculationWithoutDiscount,
    with_discount_values: CalculationWithDiscount,
}


impl Calculation {
    pub fn new(
        without_discount_values: CalculationWithoutDiscount,
        with_discount_values: CalculationWithDiscount,
    ) -> Self {
        Self {
            without_discount_values,
            with_discount_values,
        }
    }
}

impl fmt::Display for Calculation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "without_discount_valueset {}, with_discount_values {}",
            self.without_discount_values, self.with_discount_values,
        )
    }
}

// A thing able to calculate sales values
pub trait Calculator {
    /// adds a [BigDecimal] discount value of the specified [discount::Mode] to [Calculator].
    fn add_discount(
        &mut self,
        discount: BigDecimal,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>>;

    /// adds a [f64] discount value of the specified [discount::Mode]
    /// to [Calculator] so expect some precision loss
    fn add_discount_from_f64(
        &mut self,
        discount: f64,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>>;

    /// adds an [`Into<String>`] discount value of the specified [discount::Mode]
    /// to [`Calculator`]
    fn add_discount_from_str<S: Into<String>>(
        &mut self,
        discount: S,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>>;

    /// adds a tax to the specified [tax::Stage] in [Calculator] from a [f64] value
    /// of the specified [tax::Mode] so expect some precision loss
    fn add_tax_from_f64(
        &mut self,
        tax: f64,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>>;

    /// adds a tax to the specified [tax::Stage] in [Calculator] from a [BigDecimal]
    fn add_tax(
        &mut self,
        tax: BigDecimal,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>>;

    /// adds a tax to the specified [tax::Stage] in [Calculator] from a [String]
    fn add_tax_from_str<S: Into<String>>(
        &mut self,
        tax: S,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>>;

    /// calculates and produces a [Calculation] from a [BigDecimal] brute value
    /// and a quantity of the same type
    fn compute_from_brute(
        &mut self,
        brute: BigDecimal,
        qty: BigDecimal,
        max_discount_allowed: Option<BigDecimal>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// calculates and produces a [Calculation] from a [f64] brute subtotal value
    /// and a quantity of the same type. Use of [f64] may cause precission loss
    fn compute_from_brute_f64(
        &mut self,
        brute: f64,
        qty: f64,
        max_discount_allowed: Option<f64>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// calculates and produces a [Calculation] from a [String] brute value
    /// and a quantity of the same type
    fn compute_from_brute_str<S: Into<String>>(
        &mut self,
        brute: S,
        qty: S,
        max_discount_allowed: Option<S>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// calculates and produces a [Calculation] from a [String] unit value
    /// and a quantity of the same type
    fn compute_from_str<S: Into<String>>(
        &mut self,
        unit_value: S,
        qty: S,
        max_discount_allowed: Option<S>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// calculates and produces a [Calculation] from a [f64] unit value
    /// and a quantity of the same type. Use of [f64] may cause precission loss
    fn compute_from_f64(
        &mut self,
        unit_value: f64,
        qty: f64,
        max_discount_allowed: Option<f64>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// calculates and produces a [Calculation] from a [BigDecimal] unit value
    /// and a quantity of the same type
    /// Receives an [Option<BigDecimal>] to use as a maximum discount value. If [None] the max discount value will be the
    /// equivalent to the 100% of the calculated brute subtotal. If [Some] will be validated and used the passed value.
    /// If the unwrapped [BigDecimal] is negative or greater than 100, a Bigdecimal with the 100 value will be used
    /// as maximum allowed discount.
    fn compute(
        &mut self,
        unit_value: BigDecimal,
        qty: BigDecimal,
        max_discount_allowed: Option<BigDecimal>,
    ) -> Result<Calculation, BagginsError<String>>;

    /// an utility to calculate a tax directly
    ///
    /// # Params
    ///
    /// taxable [BigDecimal] value to tax
    ///
    /// qty     [BigDecimal] quantity being sold (some tax needs to know this value to be calculated)
    ///
    /// value   [BigDecimal] percent or amount to apply as tax
    ///
    /// mode    [tax::Mode]  wheter the tax is percentual, amount by unit or amount by line
    ///
    fn line_tax(
        &mut self,
        taxable: BigDecimal,
        qty: BigDecimal,
        value: BigDecimal,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>>;

    /// an utility to calculate a tax directly using [String]s as entry.
    /// Converts values to BigDecimal.
    ///
    /// # Params
    ///
    /// taxable [String] value to tax
    ///
    /// qty     [String] quantity being sold (some tax needs to know this value to be calculated)
    ///
    /// value   [String] percent or amount to apply as tax
    ///
    /// mode    [tax::Mode]  wheter the tax is percentual, amount by unit or amount by line
    ///
    fn line_tax_from_str<S: Into<String>>(
        &mut self,
        taxable: S,
        qty: S,
        value: S,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>>;

    /// an utility to calculate a tax directly using [f64]s as entry. Some precission could be loss.
    /// Converts values to BigDecimal.
    ///
    /// # Params
    ///
    /// taxable [f64] value to tax
    ///
    /// qty     [f64] quantity being sold (some tax needs to know this value to be calculated)
    ///
    /// value   [f64] percent or amount to apply as tax
    ///
    /// mode    [tax::Mode]  wheter the tax is percentual, amount by unit or amount by line
    ///
    fn line_tax_from_f64(
        &mut self,
        taxable: f64,
        qty: f64,
        value: f64,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>>;
}

pub struct DetailCalculator {
    tax_handler: tax::TaxComputer,
    discount_handler: discount::DiscountComputer,
}

impl DetailCalculator {
    /// Creates a new [`DetailCalculator`].
    pub fn new() -> Self {
        Self {
            tax_handler: tax::TaxComputer::default(),
            discount_handler: discount::DiscountComputer::default(),
        }
    }
}

impl Default for DetailCalculator {
    fn default() -> Self {
        Self::new()
    }
}

impl Calculator for DetailCalculator {
    fn add_discount(
        &mut self,
        discount: BigDecimal,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>> {
        self.discount_handler.add_discount(discount, discount_mode)
    }

    fn add_discount_from_f64(
        &mut self,
        discount: f64,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>> {
        self.discount_handler
            .add_discount_from_f64(discount, discount_mode)
    }

    fn add_discount_from_str<S: Into<String>>(
        &mut self,
        discount: S,
        discount_mode: discount::Mode,
    ) -> Option<discount::DiscountError<String>> {
        self.discount_handler
            .add_discount_from_str(discount, discount_mode)
    }

    fn add_tax_from_f64(
        &mut self,
        tax: f64,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>> {
        self.tax_handler.add_tax_from_f64(tax, stage, tax_mode)
    }

    fn add_tax(
        &mut self,
        tax: BigDecimal,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>> {
        self.tax_handler.add_tax(tax, stage, tax_mode)
    }

    fn add_tax_from_str<S: Into<String>>(
        &mut self,
        tax: S,
        stage: tax::Stage,
        tax_mode: tax::Mode,
    ) -> Option<tax::TaxError<String>> {
        self.tax_handler.add_tax_from_str(tax, stage, tax_mode)
    }

    fn compute_from_brute(
        &mut self,
        brute: BigDecimal,
        qty: BigDecimal,
        max_discount_allowed: Option<BigDecimal>,
    ) -> Result<Calculation, BagginsError<String>> {
        match self.tax_handler.un_tax(brute.clone(), qty.clone()) {
            Ok(un_taxed) => match self
                .discount_handler
                .un_discount(un_taxed.clone(), qty.clone())
            {
                Ok(un_discounted) => self.compute(un_discounted.0, qty, max_discount_allowed),
                Err(err) => Err(BagginsError::Other(format!(
                    "undiscounting un_taxed {} {}",
                    un_taxed, err
                ))),
            },
            Err(err) => Err(BagginsError::Other(format!(
                "untaxing brute {} {}",
                brute, err
            ))),
        }
    }

    fn compute_from_brute_f64(
        &mut self,
        brute: f64,
        qty: f64,
        max_discount_allowed: Option<f64>,
    ) -> Result<Calculation, BagginsError<String>> {
        
        let max_discount_allowed: Option<BigDecimal> = BigDecimal::from_f64(max_discount_allowed.unwrap_or(100.0f64));

        self.compute_from_brute(
            BigDecimal::from_f64(brute).unwrap_or(inverse()),
            BigDecimal::from_f64(qty).unwrap_or(inverse()),
            max_discount_allowed,
        )
    }

    fn compute_from_brute_str<S: Into<String>>(
        &mut self,
        brute: S,
        qty: S,
        max_discount_allowed: Option<S>,
    ) -> Result<Calculation, BagginsError<String>> {
        let brute = brute.into();
        let qty = qty.into();

        match BigDecimal::from_str(&brute) {
            Ok(brute) => match BigDecimal::from_str(&qty) {
                Ok(qty) => match max_discount_allowed {
                    Some(max_discount_allowed) => {
                        let max_discount_allowed = max_discount_allowed.into();

                        match BigDecimal::from_str(&max_discount_allowed) {
                            Ok(max_discount_allowed) => {
                                self.compute(brute, qty, Some(max_discount_allowed))
                            }
                            Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                                "parsing max_discount_allowed: <S: Into<String>> {} {}",
                                max_discount_allowed, err,
                            ))),
                        }
                    }
                    None => self.compute(brute, qty, None),
                },
                Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                    "parsing qty: <S: Into<String>> {} {}",
                    qty, err,
                ))),
            },
            Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                "parsing unit_value: <S: Into<String>> {} {}",
                brute, err,
            ))),
        }
    }

    fn compute_from_str<S: Into<String>>(
        &mut self,
        unit_value: S,
        qty: S,
        max_discount_allowed: Option<S>,
    ) -> Result<Calculation, BagginsError<String>> {
        let unit_value = unit_value.into();
        let qty = qty.into();

        match BigDecimal::from_str(&unit_value) {
            Ok(unit_value) => match BigDecimal::from_str(&qty) {
                Ok(qty) => match max_discount_allowed {
                    Some(max_discount_allowed) => {
                        let max_discount_allowed = max_discount_allowed.into();

                        match BigDecimal::from_str(&max_discount_allowed) {
                            Ok(max_discount_allowed) => {
                                self.compute(unit_value, qty, Some(max_discount_allowed))
                            }
                            Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                                "parsing max_discount_allowed: <S: Into<String>> {} {}",
                                max_discount_allowed, err,
                            ))),
                        }
                    }
                    None => self.compute(unit_value, qty, None),
                },
                Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                    "parsing qty: <S: Into<String>> {} {}",
                    qty, err,
                ))),
            },
            Err(err) => Err(BagginsError::InvalidDecimalValue(format!(
                "parsing unit_value: <S: Into<String>> {} {}",
                unit_value, err,
            ))),
        }
    }

    fn compute_from_f64(
        &mut self,
        unit_value: f64,
        qty: f64,
        max_discount_allowed: Option<f64>,
    ) -> Result<Calculation, BagginsError<String>> {
        let max_discount_allowed: Option<BigDecimal> = BigDecimal::from_f64(max_discount_allowed.unwrap_or(100.0f64));

        self.compute(
            BigDecimal::from_f64(unit_value).unwrap_or(inverse()),
            BigDecimal::from_f64(qty).unwrap_or(inverse()),
            max_discount_allowed,
        )
    }

    fn compute(
        &mut self,
        unit_value: BigDecimal,
        qty: BigDecimal,
        max_discount_allowed: Option<BigDecimal>,
    ) -> Result<Calculation, BagginsError<String>> {
        match self
            .discount_handler
            .compute(unit_value.clone(), qty.clone(), max_discount_allowed)
        {
            Ok(discount) => {
                let net = &unit_value * &qty - &discount.0;
                let discounted_uv = &net / &qty;

                match self.tax_handler.tax(discounted_uv.clone(), qty.clone()) {
                    Ok(tax) => match self.tax_handler.tax(unit_value.clone(), qty.clone()) {
                        Ok(tax_without_discount) => {
                            let net_without_discount = &unit_value * &qty;
                            let brute_without_discount =
                                &net_without_discount + &tax_without_discount;
                            let brute = &net + &tax;

                            let calc = Calculation {
                                without_discount_values: CalculationWithoutDiscount {
                                    brute: brute_without_discount.clone(),
                                    unit_value: &net_without_discount / &qty,
                                    net: net_without_discount,
                                    tax: tax_without_discount,
                                },
                                with_discount_values: CalculationWithDiscount {
                                    discount_brute_value: &brute - &brute_without_discount,
                                    brute,
                                    unit_value: &net / &qty,
                                    net,
                                    tax,
                                    discount_value: discount.0,
                                    total_discount_percent: discount.1,
                                },
                            };

                            Ok(calc)
                        }
                        Err(err) => Err(BagginsError::Other(format!(
                            "calculating taxes {}",
                            err
                        ))),
                    },
                    Err(err) => Err(BagginsError::Other(format!(
                        "calculating taxes {}",
                        err
                    ))),
                }
            }
            Err(err) => Err(BagginsError::Other(format!(
                "calculating discount {}",
                err
            ))),
        }
    }

    fn line_tax(
        &mut self,
        taxable: BigDecimal,
        qty: BigDecimal,
        value: BigDecimal,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>> {
        self.tax_handler.line_tax(taxable, qty, value, mode)
    }

    fn line_tax_from_str<S: Into<String>>(
        &mut self,
        taxable: S,
        qty: S,
        value: S,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>> {
        self.tax_handler
            .line_tax_from_str(taxable, qty, value, mode)
    }

    fn line_tax_from_f64(
        &mut self,
        taxable: f64,
        qty: f64,
        value: f64,
        mode: tax::Mode,
    ) -> Result<BigDecimal, tax::TaxError<String>> {
        self.tax_handler
            .line_tax_from_f64(taxable, qty, value, mode)
    }
}