Files
go-cart-actor/pkg/voucher/service.go
matst80 dc352e3b74
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
voucher change
2025-10-18 14:33:21 +02:00

81 lines
1.4 KiB
Go

package voucher
import (
"encoding/json"
"errors"
"fmt"
"os"
"git.tornberg.me/go-cart-actor/pkg/messages"
)
type Rule struct {
Type string `json:"type"`
Value int64 `json:"value"`
}
type Voucher struct {
Code string `json:"code"`
Value int64 `json:"discount"`
rules []*messages.VoucherRule `json:"rules"`
}
type Service struct {
// Add fields here
}
var ErrInvalidCode = errors.New("invalid vouchercode")
func (s *Service) GetVoucher(code string) (*messages.AddVoucher, error) {
if code == "" {
return nil, ErrInvalidCode
}
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: 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
}