try new vouchers
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
messages "git.tornberg.me/go-cart-actor/pkg/messages"
|
||||
"git.tornberg.me/go-cart-actor/pkg/voucher"
|
||||
)
|
||||
|
||||
// Legacy padded [16]byte CartId and its helper methods removed.
|
||||
@@ -86,7 +87,55 @@ type Voucher struct {
|
||||
Code string `json:"code"`
|
||||
Rules []*messages.VoucherRule `json:"rules"`
|
||||
Id uint32 `json:"id"`
|
||||
Value Price `json:"value"`
|
||||
Value int64 `json:"value"`
|
||||
}
|
||||
|
||||
func (v *Voucher) AppliesTo(cart *CartGrain) ([]*CartItem, bool) {
|
||||
// No rules -> applies to entire cart
|
||||
if len(v.Rules) == 0 {
|
||||
return cart.Items, true
|
||||
}
|
||||
|
||||
// Build evaluation context once
|
||||
ctx := voucher.EvalContext{
|
||||
Items: make([]voucher.Item, 0, len(cart.Items)),
|
||||
CartTotalInc: 0,
|
||||
}
|
||||
|
||||
if cart.TotalPrice != nil {
|
||||
ctx.CartTotalInc = cart.TotalPrice.IncVat
|
||||
}
|
||||
|
||||
for _, it := range cart.Items {
|
||||
category := ""
|
||||
if it.Meta != nil {
|
||||
category = it.Meta.Category
|
||||
}
|
||||
ctx.Items = append(ctx.Items, voucher.Item{
|
||||
Sku: it.Sku,
|
||||
Category: category,
|
||||
UnitPrice: it.Price.IncVat,
|
||||
})
|
||||
}
|
||||
|
||||
// All voucher rules must pass (logical AND)
|
||||
for _, rule := range v.Rules {
|
||||
expr := rule.GetCondition()
|
||||
if expr == "" {
|
||||
// Empty condition treated as pass (acts like a comment / placeholder)
|
||||
continue
|
||||
}
|
||||
rs, err := voucher.ParseRules(expr)
|
||||
if err != nil {
|
||||
// Fail closed on parse error
|
||||
return nil, false
|
||||
}
|
||||
if !rs.Applies(ctx) {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
return cart.Items, true
|
||||
}
|
||||
|
||||
func (c *CartGrain) GetId() uint64 {
|
||||
@@ -208,9 +257,11 @@ func (c *CartGrain) UpdateTotals() {
|
||||
for _, delivery := range c.Deliveries {
|
||||
c.TotalPrice.Add(delivery.Price)
|
||||
}
|
||||
// for _, voucher := range c.Vouchers {
|
||||
// c.TotalPrice -= voucher.Value
|
||||
// c.TotalTax -= voucher.TaxValue
|
||||
// c.TotalDiscountTax += voucher.TaxValue
|
||||
// }
|
||||
for _, voucher := range c.Vouchers {
|
||||
if _, ok := voucher.AppliesTo(c); ok {
|
||||
value := NewPriceFromIncVat(voucher.Value, 25)
|
||||
|
||||
c.TotalDiscount.Add(*value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user