-
Notifications
You must be signed in to change notification settings - Fork 53
/
discount.go
71 lines (56 loc) · 1.36 KB
/
discount.go
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
package generator
import (
"errors"
"github.com/shopspring/decimal"
)
// ErrInvalidDiscount when percent and amount are empty
var ErrInvalidDiscount = errors.New("invalid discount")
// Discount types
const (
DiscountTypeAmount string = "amount"
DiscountTypePercent string = "percent"
)
// Discount define discount as percent or fixed amount
type Discount struct {
Percent string `json:"percent,omitempty"` // Discount in percent ex 17
Amount string `json:"amount,omitempty"` // Discount in amount ex 123.40
_percent decimal.Decimal
_amount decimal.Decimal
}
// Prepare convert strings to decimal
func (d *Discount) Prepare() error {
if len(d.Percent) == 0 && len(d.Amount) == 0 {
return ErrInvalidDiscount
}
// Percent
if len(d.Percent) > 0 {
percent, err := decimal.NewFromString(d.Percent)
if err != nil {
return err
}
d._percent = percent
}
// Amount
if len(d.Amount) > 0 {
amount, err := decimal.NewFromString(d.Amount)
if err != nil {
return err
}
d._amount = amount
}
return nil
}
// getDiscount as return the discount type and value
func (t *Discount) getDiscount() (string, decimal.Decimal) {
tax := "0"
taxType := DiscountTypePercent
if len(t.Percent) > 0 {
tax = t.Percent
}
if len(t.Amount) > 0 {
tax = t.Amount
taxType = DiscountTypeAmount
}
decVal, _ := decimal.NewFromString(tax)
return taxType, decVal
}