voucher change
All checks were successful
Build and Publish / Metadata (push) Successful in 9s
Build and Publish / BuildAndDeployAmd64 (push) Successful in 1m13s
Build and Publish / BuildAndDeployArm64 (push) Successful in 4m30s

This commit is contained in:
matst80
2025-10-18 14:33:21 +02:00
parent 915d845014
commit dc352e3b74
9 changed files with 313 additions and 247 deletions

View File

@@ -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
}