flamingo.me/flamingo-commerce/v3@v3.11.0/cart/domain/decorator/discount.go (about) 1 package decorator 2 3 import ( 4 "flamingo.me/flamingo-commerce/v3/cart/domain/cart" 5 "flamingo.me/flamingo/v3/framework/flamingo" 6 ) 7 8 const ( 9 decoratedDiscountError = "Unable to collect discounts, stopping and returning empty slice" 10 ) 11 12 type ( 13 // DecoratedWithDiscount interface for a decorated object to be able to handle discounts 14 // the difference to cart.WithDiscount is, that these functions do NOT provide the client 15 // with an error, errors are just logged 16 DecoratedWithDiscount interface { 17 HasAppliedDiscounts() bool 18 MergeDiscounts() cart.AppliedDiscounts 19 } 20 ) 21 22 var ( 23 // interface assertions 24 _ DecoratedWithDiscount = new(DecoratedCartItem) 25 _ DecoratedWithDiscount = new(DecoratedDelivery) 26 _ DecoratedWithDiscount = new(DecoratedCart) 27 ) 28 29 // HasAppliedDiscounts checks whether decorated item has discounts 30 func (dci *DecoratedCartItem) HasAppliedDiscounts() bool { 31 return hasAppliedDiscounts(dci) 32 } 33 34 // MergeDiscounts sum up discounts applied to item 35 func (dci DecoratedCartItem) MergeDiscounts() cart.AppliedDiscounts { 36 return collectDiscounts(&dci.Item, dci.logger) 37 } 38 39 // HasAppliedDiscounts checks whether decorated delivery has discounts 40 func (dc DecoratedDelivery) HasAppliedDiscounts() bool { 41 return hasAppliedDiscounts(dc) 42 } 43 44 // MergeDiscounts sum up discounts applied to delivery 45 func (dc DecoratedDelivery) MergeDiscounts() cart.AppliedDiscounts { 46 return collectDiscounts(&dc.Delivery, dc.logger) 47 } 48 49 // HasAppliedDiscounts checks whether decorated cart has discounts 50 func (dc DecoratedCart) HasAppliedDiscounts() bool { 51 return hasAppliedDiscounts(dc) 52 } 53 54 // MergeDiscounts sum up discounts applied to cart 55 func (dc DecoratedCart) MergeDiscounts() cart.AppliedDiscounts { 56 return collectDiscounts(&dc.Cart, dc.Logger) 57 } 58 59 // private helpers as all implementations of decorated entities are based on underlying 60 // interface cart.WithDiscount and can therefore be abstracted 61 62 func hasAppliedDiscounts(discountable DecoratedWithDiscount) bool { 63 return len(discountable.MergeDiscounts()) > 0 64 } 65 66 func collectDiscounts(discountable cart.WithDiscount, logger flamingo.Logger) cart.AppliedDiscounts { 67 discounts, err := discountable.MergeDiscounts() 68 if err != nil { 69 logger.Error(decoratedDiscountError) 70 return make(cart.AppliedDiscounts, 0) 71 } 72 return discounts 73 }