48 lines
956 B
Go
48 lines
956 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"slices"
|
|
|
|
"git.tornberg.me/go-cart-actor/pkg/actor"
|
|
"git.tornberg.me/go-cart-actor/pkg/messages"
|
|
"git.tornberg.me/go-cart-actor/pkg/voucher"
|
|
)
|
|
|
|
func (ctx *MutationContext) AddVoucher(g *CartGrain, m *messages.AddVoucher) error {
|
|
if m == nil {
|
|
return &actor.MutationError{
|
|
Message: "AddVoucher: nil payload",
|
|
Code: 1001,
|
|
StatusCode: 400,
|
|
}
|
|
}
|
|
|
|
if slices.ContainsFunc(g.Vouchers, func(v *voucher.Voucher) bool {
|
|
return v.Code == m.Code
|
|
}) {
|
|
return &actor.MutationError{
|
|
Message: "voucher already applied",
|
|
Code: 1002,
|
|
StatusCode: 400,
|
|
}
|
|
}
|
|
|
|
voucherData, err := ctx.VoucherService.GetVoucher(m.Code)
|
|
if err != nil {
|
|
return &actor.MutationError{
|
|
Message: fmt.Sprintf("cant find voucher: %v", err),
|
|
Code: 1003,
|
|
StatusCode: 400,
|
|
}
|
|
}
|
|
|
|
if voucherData == nil {
|
|
return nil
|
|
}
|
|
|
|
g.Vouchers = append(g.Vouchers, voucherData)
|
|
g.UpdateTotals()
|
|
return nil
|
|
}
|