-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathtax.go
71 lines (56 loc) · 1.26 KB
/
tax.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"
)
// ErrInvalidTax when percent and amount are empty
var ErrInvalidTax = errors.New("invalid tax")
// Tax types
const (
TaxTypeAmount string = "amount"
TaxTypePercent string = "percent"
)
// Tax define tax as percent or fixed amount
type Tax struct {
Percent string `json:"percent,omitempty"` // Tax in percent ex 17
Amount string `json:"amount,omitempty"` // Tax in amount ex 123.40
_percent decimal.Decimal
_amount decimal.Decimal
}
// Prepare convert strings to decimal
func (t *Tax) Prepare() error {
if len(t.Percent) == 0 && len(t.Amount) == 0 {
return ErrInvalidTax
}
// Percent
if len(t.Percent) > 0 {
percent, err := decimal.NewFromString(t.Percent)
if err != nil {
return err
}
t._percent = percent
}
// Amount
if len(t.Amount) > 0 {
amount, err := decimal.NewFromString(t.Amount)
if err != nil {
return err
}
t._amount = amount
}
return nil
}
// getTax return the tax type and value
func (t *Tax) getTax() (string, decimal.Decimal) {
tax := "0"
taxType := TaxTypePercent
if len(t.Percent) > 0 {
tax = t.Percent
}
if len(t.Amount) > 0 {
tax = t.Amount
taxType = TaxTypeAmount
}
decVal, _ := decimal.NewFromString(tax)
return taxType, decVal
}