voucher change
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
package voucher
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.tornberg.me/go-cart-actor/pkg/messages"
|
||||
)
|
||||
@@ -12,11 +15,9 @@ type Rule struct {
|
||||
}
|
||||
|
||||
type Voucher struct {
|
||||
Code string `json:"code"`
|
||||
Value int64 `json:"discount"`
|
||||
TaxValue int64 `json:"taxValue"`
|
||||
TaxRate int `json:"taxRate"`
|
||||
rules []Rule `json:"rules"`
|
||||
Code string `json:"code"`
|
||||
Value int64 `json:"discount"`
|
||||
rules []*messages.VoucherRule `json:"rules"`
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
@@ -29,10 +30,51 @@ func (s *Service) GetVoucher(code string) (*messages.AddVoucher, error) {
|
||||
if code == "" {
|
||||
return nil, ErrInvalidCode
|
||||
}
|
||||
value := int64(250_00)
|
||||
sf, err := LoadStateFile("data/vouchers.json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, ok := sf.GetVoucher(code)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("no voucher found for code: %s", code)
|
||||
}
|
||||
|
||||
return &messages.AddVoucher{
|
||||
Code: code,
|
||||
Value: value,
|
||||
VoucherRules: make([]*messages.VoucherRule, 0),
|
||||
Value: v.Value,
|
||||
VoucherRules: v.rules,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type State struct {
|
||||
Vouchers []Voucher `json:"vouchers"`
|
||||
}
|
||||
|
||||
type StateFile struct {
|
||||
State State `json:"state"`
|
||||
Vercion int `json:"version"`
|
||||
}
|
||||
|
||||
func (sf *StateFile) GetVoucher(code string) (*Voucher, bool) {
|
||||
for _, v := range sf.State.Vouchers {
|
||||
if v.Code == code {
|
||||
return &v, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func LoadStateFile(fileName string) (*StateFile, error) {
|
||||
f, err := os.Open(fileName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
dec := json.NewDecoder(f)
|
||||
sf := &StateFile{}
|
||||
err = dec.Decode(sf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sf, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user