diff --git a/cart/application/cartCache.go b/cart/application/cartCache.go index c15e39b5b..4261a6a1f 100644 --- a/cart/application/cartCache.go +++ b/cart/application/cartCache.go @@ -3,6 +3,7 @@ package application import ( "context" "encoding/gob" + "errors" "fmt" "strings" "time" @@ -11,7 +12,6 @@ import ( "flamingo.me/flamingo/v3/core/auth" "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" ) type ( @@ -74,7 +74,7 @@ func (ci *CartCacheIdentifier) CacheKey() string { } // BuildIdentifierFromCart creates a Cache Identifier from Cart Data -// DEPRICATED +// DEPRECATED func BuildIdentifierFromCart(cart *cart.Cart) (*CartCacheIdentifier, error) { if cart == nil { return nil, errors.New("no cart") @@ -158,7 +158,7 @@ func (cs *CartSessionCache) GetCart(ctx context.Context, session *web.Session, i return nil, errors.New("cart cache contains invalid data at cache key") } - cs.logger.WithContext(ctx).Debug("Did not Found cached cart %v", id.CacheKey()) + cs.logger.WithContext(ctx).Debug("Did not find cached cart %v", id.CacheKey()) return nil, ErrNoCacheEntry } @@ -179,7 +179,7 @@ func (cs *CartSessionCache) CacheCart(ctx context.Context, session *web.Session, } // Invalidate a Cache Entry -func (cs *CartSessionCache) Invalidate(ctx context.Context, session *web.Session, id CartCacheIdentifier) error { +func (cs *CartSessionCache) Invalidate(_ context.Context, session *web.Session, id CartCacheIdentifier) error { if cache, ok := session.Load(CartSessionCacheCacheKeyPrefix + id.CacheKey()); ok { if cachedCartsEntry, ok := cache.(CachedCartEntry); ok { cachedCartsEntry.IsInvalid = true @@ -193,7 +193,7 @@ func (cs *CartSessionCache) Invalidate(ctx context.Context, session *web.Session } // Delete a Cache entry -func (cs *CartSessionCache) Delete(ctx context.Context, session *web.Session, id CartCacheIdentifier) error { +func (cs *CartSessionCache) Delete(_ context.Context, session *web.Session, id CartCacheIdentifier) error { if _, ok := session.Load(CartSessionCacheCacheKeyPrefix + id.CacheKey()); ok { session.Delete(CartSessionCacheCacheKeyPrefix + id.CacheKey()) @@ -205,7 +205,7 @@ func (cs *CartSessionCache) Delete(ctx context.Context, session *web.Session, id } // DeleteAll empties the Cache -func (cs *CartSessionCache) DeleteAll(ctx context.Context, session *web.Session) error { +func (cs *CartSessionCache) DeleteAll(_ context.Context, session *web.Session) error { deleted := false for _, k := range session.Keys() { if stringKey, ok := k.(string); ok { diff --git a/cart/application/cartReceiver_test.go b/cart/application/cartReceiver_test.go index ac7bcaa12..ff414cb37 100644 --- a/cart/application/cartReceiver_test.go +++ b/cart/application/cartReceiver_test.go @@ -2,6 +2,7 @@ package application_test import ( "context" + "errors" "fmt" "reflect" "testing" @@ -10,7 +11,6 @@ import ( authMock "flamingo.me/flamingo/v3/core/auth/mock" "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/cart/application/cartService.go b/cart/application/cartService.go index b33339774..437f14741 100644 --- a/cart/application/cartService.go +++ b/cart/application/cartService.go @@ -3,10 +3,10 @@ package application import ( "context" "encoding/gob" + "errors" "fmt" "flamingo.me/flamingo/v3/core/auth" - "github.com/pkg/errors" "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" @@ -144,7 +144,7 @@ func (cs *CartService) ValidateCurrentCart(ctx context.Context, session *web.Ses return cs.ValidateCart(ctx, session, decoratedCart), nil } -// UpdatePaymentSelection updates the paymentselection in the cart +// UpdatePaymentSelection updates the payment selection in the cart func (cs *CartService) UpdatePaymentSelection(ctx context.Context, session *web.Session, paymentSelection cartDomain.PaymentSelection) error { cart, behaviour, err := cs.cartReceiverService.GetCart(ctx, session) if err != nil { @@ -424,7 +424,7 @@ func (cs *CartService) DeleteItem(ctx context.Context, session *web.Session, ite cart, defers, err = behaviour.DeleteItem(ctx, cart, itemID, deliveryCode) if err != nil { cs.handleCartNotFound(session, err) - cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "DeleteItem").Error(errors.Wrap(err, "Trying to delete SKU :"+item.MarketplaceCode)) + cs.logger.WithContext(ctx).WithField(flamingo.LogKeySubCategory, "DeleteItem").Error(fmt.Errorf("trying to delete SKU %q: %w", item.MarketplaceCode, err)) return err } @@ -772,7 +772,7 @@ func (cs *CartService) ApplyVoucher(ctx context.Context, session *web.Session, c return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, behaviour.ApplyVoucher) } -// ApplyAny applies a voucher or giftcard to the cart +// ApplyAny applies a voucher or gift card to the cart func (cs *CartService) ApplyAny(ctx context.Context, session *web.Session, anyCode string) (*cartDomain.Cart, error) { cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "ApplyAny") if err != nil { @@ -793,7 +793,7 @@ func (cs *CartService) RemoveVoucher(ctx context.Context, session *web.Session, return cs.executeVoucherBehaviour(ctx, session, cart, couponCode, behaviour.RemoveVoucher) } -// ApplyGiftCard adds a giftcard to the cart +// ApplyGiftCard adds a gift card to the cart func (cs *CartService) ApplyGiftCard(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) { cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "ApplyGiftCard") if err != nil { @@ -805,7 +805,7 @@ func (cs *CartService) ApplyGiftCard(ctx context.Context, session *web.Session, return nil, errors.New("ApplyGiftCard not supported") } -// RemoveGiftCard removes a giftcard from the cart +// RemoveGiftCard removes a gift card from the cart func (cs *CartService) RemoveGiftCard(ctx context.Context, session *web.Session, couponCode string) (*cartDomain.Cart, error) { cart, behaviour, err := cs.getCartAndBehaviour(ctx, session, "RemoveGiftCard") if err != nil { @@ -829,7 +829,7 @@ func (cs *CartService) getCartAndBehaviour(ctx context.Context, session *web.Ses } // Executes provided behaviour regarding vouchers, this function serves to reduce duplicated code -// for voucher / giftcard behaviour as their internal logic is basically the same +// for voucher / gift card behaviour as their internal logic is basically the same func (cs *CartService) executeVoucherBehaviour(ctx context.Context, session *web.Session, cart *cartDomain.Cart, couponCode string, fn promotionFunc) (*cartDomain.Cart, error) { // cart cache must be updated - with the current value of cart var defers cartDomain.DeferEvents @@ -1033,16 +1033,16 @@ func (cs *CartService) CancelOrder(ctx context.Context, session *web.Session, or return restoredCart, nil } -func (cs *CartService) cancelOrder(ctx context.Context, session *web.Session, orderInfos placeorder.PlacedOrderInfos) error { +func (cs *CartService) cancelOrder(ctx context.Context, _ *web.Session, orderInfos placeorder.PlacedOrderInfos) error { if cs.placeOrderService == nil { return errors.New("No placeOrderService registered") } var cancelErr error - identitiy := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx)) - if identitiy != nil { - cancelErr = cs.placeOrderService.CancelCustomerOrder(ctx, orderInfos, identitiy) + identity := cs.webIdentityService.Identify(ctx, web.RequestFromContext(ctx)) + if identity != nil { + cancelErr = cs.placeOrderService.CancelCustomerOrder(ctx, orderInfos, identity) } else { cancelErr = cs.placeOrderService.CancelGuestOrder(ctx, orderInfos) } @@ -1059,7 +1059,7 @@ func (cs *CartService) CancelOrderWithoutRestore(ctx context.Context, session *w return cs.cancelOrder(ctx, session, orderInfos) } -// GetDefaultDeliveryCode returns the configured default deliverycode +// GetDefaultDeliveryCode returns the configured default delivery code func (cs *CartService) GetDefaultDeliveryCode() string { return cs.defaultDeliveryCode } diff --git a/cart/domain/cart/cart.go b/cart/domain/cart/cart.go index dc201b513..714f6e995 100644 --- a/cart/domain/cart/cart.go +++ b/cart/domain/cart/cart.go @@ -3,11 +3,10 @@ package cart import ( "bytes" "encoding/gob" + "errors" "fmt" "math/big" - "github.com/pkg/errors" - "flamingo.me/flamingo/v3/framework/web" "flamingo.me/flamingo-commerce/v3/price/domain" @@ -50,7 +49,7 @@ type ( DefaultCurrency string - // Additional non taxable totals + // Additional non-taxable totals Totalitems []Totalitem // AppliedGiftCards is a list of applied gift cards @@ -255,7 +254,7 @@ func (c Cart) GetDeliveryByItemID(itemID string) (*Delivery, error) { } } - return nil, errors.Errorf("delivery not found for %q", itemID) + return nil, fmt.Errorf("delivery not found for %q", itemID) } // GetByItemID gets an item by its id @@ -268,12 +267,12 @@ func (c Cart) GetByItemID(itemID string) (*Item, error) { } } - return nil, errors.Errorf("itemId %q in cart does not exist", itemID) + return nil, fmt.Errorf("itemId %q in cart does not exist", itemID) } // GetTotalQty for the product in the cart func (c Cart) GetTotalQty(marketPlaceCode string, variantCode string) int { - qty := int(0) + qty := 0 for _, delivery := range c.Deliveries { for _, currentItem := range delivery.Cartitems { if currentItem.MarketplaceCode == marketPlaceCode && currentItem.VariantMarketPlaceCode == variantCode { @@ -294,7 +293,7 @@ func (c Cart) GetByExternalReference(ref string) (*Item, error) { } } - return nil, errors.Errorf("uitemID %v in cart not existing", ref) + return nil, fmt.Errorf("cart item with ExternalReference %q not found", ref) } // ItemCount returns amount of cart items in the current cart @@ -576,7 +575,7 @@ func (c Cart) GetCartTeaser() *Teaser { } } -// GetPaymentReference returns a string that can be used as reference to pass to payment gateway. You may want to use it. It returns either the reserved Order id or the cart id/entityid +// GetPaymentReference returns a string that can be used as reference to pass to payment gateway. You may want to use it. It returns either the reserved Order id or the cart id/entity id func (c Cart) GetPaymentReference() string { if c.AdditionalData.ReservedOrderID != "" { return c.AdditionalData.ReservedOrderID @@ -625,7 +624,7 @@ func (c Cart) GrandTotalCharges() domain.Charges { // AddTax returns new Tax with this Tax added func (t Taxes) AddTax(tax Tax) Taxes { - newTaxes := Taxes(t) + newTaxes := t newTaxes = append(newTaxes, tax) return newTaxes @@ -633,7 +632,7 @@ func (t Taxes) AddTax(tax Tax) Taxes { // AddTaxWithMerge returns new Taxes with this Tax added func (t Taxes) AddTaxWithMerge(taxToAddOrMerge Tax) Taxes { - newTaxes := Taxes(t) + newTaxes := t for k, tax := range newTaxes { if tax.Type == taxToAddOrMerge.Type { @@ -654,7 +653,7 @@ func (t Taxes) AddTaxWithMerge(taxToAddOrMerge Tax) Taxes { // AddTaxesWithMerge returns new Taxes with the given Taxes all added or merged in func (t Taxes) AddTaxesWithMerge(taxes Taxes) Taxes { - newTaxes := Taxes(t) + newTaxes := t for _, tax := range taxes { newTaxes = newTaxes.AddTaxWithMerge(tax) @@ -819,7 +818,7 @@ func (p PricedItems) Sum() domain.Price { return sum } -// TotalItems returns the Price per Totalitem - map key is total type +// TotalItems returns the Price per total item - map key is total type func (p PricedItems) TotalItems() map[string]domain.Price { return p.totalItems } diff --git a/cart/domain/cart/cartServicePorts.go b/cart/domain/cart/cartServicePorts.go index c98a40b97..65c0c4c7e 100644 --- a/cart/domain/cart/cartServicePorts.go +++ b/cart/domain/cart/cartServicePorts.go @@ -10,11 +10,10 @@ package cart import ( "context" "encoding/json" + "errors" "flamingo.me/flamingo/v3/core/auth" "flamingo.me/flamingo/v3/framework/flamingo" - - "github.com/pkg/errors" ) type ( diff --git a/cart/infrastructure/defaultCartBehaviour.go b/cart/infrastructure/defaultCartBehaviour.go index 00fc2d320..af9a63d60 100644 --- a/cart/infrastructure/defaultCartBehaviour.go +++ b/cart/infrastructure/defaultCartBehaviour.go @@ -2,17 +2,17 @@ package infrastructure import ( "context" + "errors" "fmt" "math/big" "math/rand" "strconv" - domaincart "flamingo.me/flamingo-commerce/v3/cart/domain/cart" + cartDomain "flamingo.me/flamingo-commerce/v3/cart/domain/cart" "flamingo.me/flamingo-commerce/v3/cart/domain/events" priceDomain "flamingo.me/flamingo-commerce/v3/price/domain" "flamingo.me/flamingo-commerce/v3/product/domain" "flamingo.me/flamingo/v3/framework/flamingo" - "github.com/pkg/errors" ) type ( @@ -21,9 +21,9 @@ type ( cartStorage CartStorage productService domain.ProductService logger flamingo.Logger - itemBuilderProvider domaincart.ItemBuilderProvider - deliveryBuilderProvider domaincart.DeliveryBuilderProvider - cartBuilderProvider domaincart.BuilderProvider + itemBuilderProvider cartDomain.ItemBuilderProvider + deliveryBuilderProvider cartDomain.DeliveryBuilderProvider + cartBuilderProvider cartDomain.BuilderProvider giftCardHandler GiftCardHandler voucherHandler VoucherHandler defaultTaxRate float64 @@ -31,22 +31,22 @@ type ( // CartStorage Interface - might be implemented by other persistence types later as well CartStorage interface { - GetCart(ctx context.Context, id string) (*domaincart.Cart, error) + GetCart(ctx context.Context, id string) (*cartDomain.Cart, error) HasCart(ctx context.Context, id string) bool - StoreCart(ctx context.Context, cart *domaincart.Cart) error - RemoveCart(ctx context.Context, cart *domaincart.Cart) error + StoreCart(ctx context.Context, cart *cartDomain.Cart) error + RemoveCart(ctx context.Context, cart *cartDomain.Cart) error } // GiftCardHandler enables the projects to have specific GiftCard handling within the in-memory cart GiftCardHandler interface { - ApplyGiftCard(ctx context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, error) - RemoveGiftCard(ctx context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, error) + ApplyGiftCard(ctx context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, error) + RemoveGiftCard(ctx context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, error) } // VoucherHandler enables the projects to have specific Voucher handling within the in-memory cart VoucherHandler interface { - ApplyVoucher(ctx context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, error) - RemoveVoucher(ctx context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, error) + ApplyVoucher(ctx context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, error) + RemoveVoucher(ctx context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, error) } // DefaultGiftCardHandler implements a basic gift card handler @@ -57,9 +57,9 @@ type ( ) var ( - _ domaincart.ModifyBehaviour = (*DefaultCartBehaviour)(nil) - _ domaincart.GiftCardAndVoucherBehaviour = (*DefaultCartBehaviour)(nil) - _ domaincart.CompleteBehaviour = (*DefaultCartBehaviour)(nil) + _ cartDomain.ModifyBehaviour = (*DefaultCartBehaviour)(nil) + _ cartDomain.GiftCardAndVoucherBehaviour = (*DefaultCartBehaviour)(nil) + _ cartDomain.CompleteBehaviour = (*DefaultCartBehaviour)(nil) _ GiftCardHandler = (*DefaultGiftCardHandler)(nil) _ VoucherHandler = (*DefaultVoucherHandler)(nil) ) @@ -69,9 +69,9 @@ func (cob *DefaultCartBehaviour) Inject( CartStorage CartStorage, ProductService domain.ProductService, Logger flamingo.Logger, - itemBuilderProvider domaincart.ItemBuilderProvider, - deliveryBuilderProvider domaincart.DeliveryBuilderProvider, - cartBuilderProvider domaincart.BuilderProvider, + itemBuilderProvider cartDomain.ItemBuilderProvider, + deliveryBuilderProvider cartDomain.DeliveryBuilderProvider, + cartBuilderProvider cartDomain.BuilderProvider, voucherHandler VoucherHandler, giftCardHandler GiftCardHandler, config *struct { @@ -80,7 +80,7 @@ func (cob *DefaultCartBehaviour) Inject( ) { cob.cartStorage = CartStorage cob.productService = ProductService - cob.logger = Logger.WithField(flamingo.LogKeyCategory, "inmemorybehaviour") + cob.logger = Logger.WithField(flamingo.LogKeyCategory, "DefaultCartBehaviour") cob.itemBuilderProvider = itemBuilderProvider cob.deliveryBuilderProvider = deliveryBuilderProvider cob.cartBuilderProvider = cartBuilderProvider @@ -92,7 +92,7 @@ func (cob *DefaultCartBehaviour) Inject( } // Complete a cart and remove from storage -func (cob *DefaultCartBehaviour) Complete(ctx context.Context, cart *domaincart.Cart) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) Complete(ctx context.Context, cart *cartDomain.Cart) (*cartDomain.Cart, cartDomain.DeferEvents, error) { err := cob.cartStorage.RemoveCart(ctx, cart) if err != nil { return nil, nil, err @@ -101,7 +101,7 @@ func (cob *DefaultCartBehaviour) Complete(ctx context.Context, cart *domaincart. } // Restore supplied cart (implements CompleteBehaviour) -func (cob *DefaultCartBehaviour) Restore(ctx context.Context, cart *domaincart.Cart) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) Restore(ctx context.Context, cart *cartDomain.Cart) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -114,7 +114,7 @@ func (cob *DefaultCartBehaviour) Restore(ctx context.Context, cart *domaincart.C } // DeleteItem removes an item from the cart -func (cob *DefaultCartBehaviour) DeleteItem(ctx context.Context, cart *domaincart.Cart, itemID string, deliveryCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) DeleteItem(ctx context.Context, cart *cartDomain.Cart, itemID string, deliveryCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if !cob.cartStorage.HasCart(ctx, cart.ID) { return nil, nil, fmt.Errorf("newCart.infrastructure.DefaultCartBehaviour: Cannot delete - Guestcart with id %v not existent", cart.ID) } @@ -146,15 +146,15 @@ func (cob *DefaultCartBehaviour) DeleteItem(ctx context.Context, cart *domaincar err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "newCart.infrastructure.DefaultCartBehaviour: error on saving newCart") + return nil, nil, fmt.Errorf("error on saving newCart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } // UpdateItem updates a cart item -func (cob *DefaultCartBehaviour) UpdateItem(ctx context.Context, cart *domaincart.Cart, itemUpdateCommand domaincart.ItemUpdateCommand) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateItem(ctx context.Context, cart *cartDomain.Cart, itemUpdateCommand cartDomain.ItemUpdateCommand) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if !cob.cartStorage.HasCart(ctx, cart.ID) { - return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot add - Guestcart with id %v not existent", cart.ID) + return nil, nil, fmt.Errorf("guestcart with id %q not existent", cart.ID) } newCart, err := cart.Clone() @@ -169,14 +169,14 @@ func (cob *DefaultCartBehaviour) UpdateItem(ctx context.Context, cart *domaincar err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } // UpdateItems updates multiple cart items -func (cob *DefaultCartBehaviour) UpdateItems(ctx context.Context, cart *domaincart.Cart, itemUpdateCommands []domaincart.ItemUpdateCommand) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateItems(ctx context.Context, cart *cartDomain.Cart, itemUpdateCommands []cartDomain.ItemUpdateCommand) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if !cob.cartStorage.HasCart(ctx, cart.ID) { return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot update - Guestcart with id %v not existent", cart.ID) } @@ -195,13 +195,13 @@ func (cob *DefaultCartBehaviour) UpdateItems(ctx context.Context, cart *domainca err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } -func (cob *DefaultCartBehaviour) updateItem(ctx context.Context, cart *domaincart.Cart, itemUpdateCommand domaincart.ItemUpdateCommand) error { +func (cob *DefaultCartBehaviour) updateItem(ctx context.Context, cart *cartDomain.Cart, itemUpdateCommand cartDomain.ItemUpdateCommand) error { itemBuilder := cob.itemBuilderProvider() itemDelivery, err := cart.GetDeliveryByItemID(itemUpdateCommand.ItemID) if err != nil { @@ -243,7 +243,7 @@ func (cob *DefaultCartBehaviour) updateItem(ctx context.Context, cart *domaincar } // AddToCart add an item to the cart -func (cob *DefaultCartBehaviour) AddToCart(ctx context.Context, cart *domaincart.Cart, deliveryCode string, addRequest domaincart.AddRequest) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) AddToCart(ctx context.Context, cart *cartDomain.Cart, deliveryCode string, addRequest cartDomain.AddRequest) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if cart != nil && !cob.cartStorage.HasCart(ctx, cart.ID) { return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot add - Guestcart with id %v not existent", cart.ID) } @@ -256,7 +256,7 @@ func (cob *DefaultCartBehaviour) AddToCart(ctx context.Context, cart *domaincart // create delivery if it does not yet exist if !newCart.HasDeliveryForCode(deliveryCode) { // create delivery and add item - delivery := new(domaincart.Delivery) + delivery := new(cartDomain.Delivery) delivery.DeliveryInfo.Code = deliveryCode newCart.Deliveries = append(newCart.Deliveries, *delivery) } @@ -292,13 +292,13 @@ func (cob *DefaultCartBehaviour) AddToCart(ctx context.Context, cart *domaincart err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } -func (cob *DefaultCartBehaviour) buildItemForCart(ctx context.Context, addRequest domaincart.AddRequest) (*domaincart.Item, error) { +func (cob *DefaultCartBehaviour) buildItemForCart(ctx context.Context, addRequest cartDomain.AddRequest) (*cartDomain.Item, error) { itemBuilder := cob.itemBuilderProvider() // create and add new item @@ -328,7 +328,7 @@ func (cob *DefaultCartBehaviour) buildItemForCart(ctx context.Context, addReques } // CleanCart removes everything from the cart, e.g. deliveries, billing address, etc -func (cob *DefaultCartBehaviour) CleanCart(ctx context.Context, cart *domaincart.Cart) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) CleanCart(ctx context.Context, cart *cartDomain.Cart) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if !cob.cartStorage.HasCart(ctx, cart.ID) { return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot delete - Guestcart with id %v not existent", cart.ID) } @@ -338,25 +338,25 @@ func (cob *DefaultCartBehaviour) CleanCart(ctx context.Context, cart *domaincart return nil, nil, err } - newCart.Deliveries = []domaincart.Delivery{} + newCart.Deliveries = []cartDomain.Delivery{} newCart.AppliedCouponCodes = nil newCart.AppliedGiftCards = nil newCart.PaymentSelection = nil - newCart.AdditionalData = domaincart.AdditionalData{} + newCart.AdditionalData = cartDomain.AdditionalData{} newCart.Purchaser = nil newCart.BillingAddress = nil newCart.Totalitems = nil err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return &newCart, nil, nil } // CleanDelivery removes a complete delivery with its items from the cart -func (cob *DefaultCartBehaviour) CleanDelivery(ctx context.Context, cart *domaincart.Cart, deliveryCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) CleanDelivery(ctx context.Context, cart *cartDomain.Cart, deliveryCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if !cob.cartStorage.HasCart(ctx, cart.ID) { return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot delete - Guestcart with id %v not existent", cart.ID) } @@ -368,7 +368,7 @@ func (cob *DefaultCartBehaviour) CleanDelivery(ctx context.Context, cart *domain // create delivery if it does not yet exist if !newCart.HasDeliveryForCode(deliveryCode) { - return nil, nil, errors.Errorf("cart.infrastructure.DefaultCartBehaviour: delivery %s not found", deliveryCode) + return nil, nil, fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: delivery %s not found", deliveryCode) } var position int @@ -381,19 +381,19 @@ func (cob *DefaultCartBehaviour) CleanDelivery(ctx context.Context, cart *domain newLength := len(newCart.Deliveries) - 1 newCart.Deliveries[position] = newCart.Deliveries[newLength] - newCart.Deliveries[newLength] = domaincart.Delivery{} + newCart.Deliveries[newLength] = cartDomain.Delivery{} newCart.Deliveries = newCart.Deliveries[:newLength] err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } // UpdatePurchaser @todo implement when needed -func (cob *DefaultCartBehaviour) UpdatePurchaser(ctx context.Context, cart *domaincart.Cart, purchaser *domaincart.Person, additionalData *domaincart.AdditionalData) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdatePurchaser(ctx context.Context, cart *cartDomain.Cart, purchaser *cartDomain.Person, additionalData *cartDomain.AdditionalData) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -407,14 +407,14 @@ func (cob *DefaultCartBehaviour) UpdatePurchaser(ctx context.Context, cart *doma err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return &newCart, nil, nil } // UpdateBillingAddress - updates address -func (cob *DefaultCartBehaviour) UpdateBillingAddress(ctx context.Context, cart *domaincart.Cart, billingAddress domaincart.Address) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateBillingAddress(ctx context.Context, cart *cartDomain.Cart, billingAddress cartDomain.Address) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -424,14 +424,14 @@ func (cob *DefaultCartBehaviour) UpdateBillingAddress(ctx context.Context, cart err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return &newCart, nil, nil } // UpdateAdditionalData updates additional data -func (cob *DefaultCartBehaviour) UpdateAdditionalData(ctx context.Context, cart *domaincart.Cart, additionalData *domaincart.AdditionalData) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateAdditionalData(ctx context.Context, cart *cartDomain.Cart, additionalData *cartDomain.AdditionalData) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -441,14 +441,14 @@ func (cob *DefaultCartBehaviour) UpdateAdditionalData(ctx context.Context, cart err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on updating additional data") + return nil, nil, fmt.Errorf("error on updating additional data: %w", err) } return &newCart, nil, nil } // UpdatePaymentSelection updates payment on cart -func (cob *DefaultCartBehaviour) UpdatePaymentSelection(ctx context.Context, cart *domaincart.Cart, paymentSelection domaincart.PaymentSelection) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdatePaymentSelection(ctx context.Context, cart *cartDomain.Cart, paymentSelection cartDomain.PaymentSelection) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -464,14 +464,14 @@ func (cob *DefaultCartBehaviour) UpdatePaymentSelection(ctx context.Context, car err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return &newCart, nil, nil } // UpdateDeliveryInfo updates a delivery info -func (cob *DefaultCartBehaviour) UpdateDeliveryInfo(ctx context.Context, cart *domaincart.Cart, deliveryCode string, deliveryInfoUpdateCommand domaincart.DeliveryInfoUpdateCommand) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateDeliveryInfo(ctx context.Context, cart *cartDomain.Cart, deliveryCode string, deliveryInfoUpdateCommand cartDomain.DeliveryInfoUpdateCommand) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -485,50 +485,50 @@ func (cob *DefaultCartBehaviour) UpdateDeliveryInfo(ctx context.Context, cart *d newCart.Deliveries[key].DeliveryInfo = deliveryInfo err := cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return &newCart, nil, nil } } - newCart.Deliveries = append(newCart.Deliveries, domaincart.Delivery{DeliveryInfo: deliveryInfo}) + newCart.Deliveries = append(newCart.Deliveries, cartDomain.Delivery{DeliveryInfo: deliveryInfo}) err = cob.cartStorage.StoreCart(ctx, &newCart) if err != nil { - return nil, nil, errors.Wrap(err, "cart.infrastructure.DefaultCartBehaviour: error on saving cart") + return nil, nil, fmt.Errorf("error on saving cart: %w", err) } return cob.resetPaymentSelectionIfInvalid(ctx, &newCart) } // UpdateDeliveryInfoAdditionalData @todo implement when needed -func (cob *DefaultCartBehaviour) UpdateDeliveryInfoAdditionalData(ctx context.Context, cart *domaincart.Cart, deliveryCode string, additionalData *domaincart.AdditionalData) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) UpdateDeliveryInfoAdditionalData(_ context.Context, cart *cartDomain.Cart, _ string, _ *cartDomain.AdditionalData) (*cartDomain.Cart, cartDomain.DeferEvents, error) { return cart, nil, nil } // GetCart returns the current cart from storage -func (cob *DefaultCartBehaviour) GetCart(ctx context.Context, cartID string) (*domaincart.Cart, error) { +func (cob *DefaultCartBehaviour) GetCart(ctx context.Context, cartID string) (*cartDomain.Cart, error) { if !cob.cartStorage.HasCart(ctx, cartID) { cob.logger.Info(fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: Cannot get - cart with id %v not existent", cartID)) - return nil, domaincart.ErrCartNotFound + return nil, cartDomain.ErrCartNotFound } cart, err := cob.cartStorage.GetCart(ctx, cartID) if err != nil { cob.logger.Info(fmt.Errorf("cart.infrastructure.DefaultCartBehaviour: get cart from storage: %w ", err)) - return nil, domaincart.ErrCartNotFound + return nil, cartDomain.ErrCartNotFound } newCart, err := cart.Clone() if err != nil { cob.logger.Info(fmt.Errorf("cart clone failed: %w ", err)) - return nil, domaincart.ErrCartNotFound + return nil, cartDomain.ErrCartNotFound } return &newCart, nil } // StoreNewCart created and stores a new cart. -func (cob *DefaultCartBehaviour) StoreNewCart(ctx context.Context, newCart *domaincart.Cart) (*domaincart.Cart, error) { +func (cob *DefaultCartBehaviour) StoreNewCart(ctx context.Context, newCart *cartDomain.Cart) (*cartDomain.Cart, error) { if newCart.ID == "" { return nil, errors.New("no id given") } @@ -536,7 +536,7 @@ func (cob *DefaultCartBehaviour) StoreNewCart(ctx context.Context, newCart *doma } // ApplyVoucher applies a voucher to the cart -func (cob *DefaultCartBehaviour) ApplyVoucher(ctx context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) ApplyVoucher(ctx context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -555,20 +555,20 @@ func (cob *DefaultCartBehaviour) ApplyVoucher(ctx context.Context, cart *domainc return cob.resetPaymentSelectionIfInvalid(ctx, newCartWithVoucher) } -// ApplyAny applies a voucher or giftcard to the cart -func (cob *DefaultCartBehaviour) ApplyAny(ctx context.Context, cart *domaincart.Cart, anyCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +// ApplyAny applies a voucher or gift card to the cart +func (cob *DefaultCartBehaviour) ApplyAny(ctx context.Context, cart *cartDomain.Cart, anyCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { currentCart, deferFunc, err := cob.ApplyVoucher(ctx, cart, anyCode) if err == nil { // successfully applied as voucher return currentCart, deferFunc, nil } - // some error occurred, retry as giftcard + // some error occurred, retry as gift card return cob.ApplyGiftCard(ctx, cart, anyCode) } // RemoveVoucher removes a voucher from the cart -func (cob *DefaultCartBehaviour) RemoveVoucher(ctx context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) RemoveVoucher(ctx context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -589,7 +589,7 @@ func (cob *DefaultCartBehaviour) RemoveVoucher(ctx context.Context, cart *domain // ApplyGiftCard applies a gift card to the cart // if a GiftCard is applied, it will be added to the array AppliedGiftCards on the cart -func (cob *DefaultCartBehaviour) ApplyGiftCard(ctx context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) ApplyGiftCard(ctx context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -609,7 +609,7 @@ func (cob *DefaultCartBehaviour) ApplyGiftCard(ctx context.Context, cart *domain // RemoveGiftCard removes a gift card from the cart // if a GiftCard is removed, it will be removed from the array AppliedGiftCards on the cart -func (cob *DefaultCartBehaviour) RemoveGiftCard(ctx context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, domaincart.DeferEvents, error) { +func (cob *DefaultCartBehaviour) RemoveGiftCard(ctx context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, cartDomain.DeferEvents, error) { newCart, err := cart.Clone() if err != nil { return nil, nil, err @@ -628,25 +628,25 @@ func (cob *DefaultCartBehaviour) RemoveGiftCard(ctx context.Context, cart *domai return cob.resetPaymentSelectionIfInvalid(ctx, newCartWithOutGiftCard) } -func (cob *DefaultCartBehaviour) isCurrentPaymentSelectionValid(ctx context.Context, cart *domaincart.Cart) bool { +func (cob *DefaultCartBehaviour) isCurrentPaymentSelectionValid(ctx context.Context, cart *cartDomain.Cart) bool { return cob.checkPaymentSelection(ctx, cart, cart.PaymentSelection) == nil } // isPaymentSelectionValid checks if the grand total of the cart matches the total of the supplied payment selection -func (cob *DefaultCartBehaviour) checkPaymentSelection(ctx context.Context, cart *domaincart.Cart, paymentSelection domaincart.PaymentSelection) error { +func (cob *DefaultCartBehaviour) checkPaymentSelection(_ context.Context, cart *cartDomain.Cart, paymentSelection cartDomain.PaymentSelection) error { if paymentSelection == nil { return nil } paymentSelectionTotal := paymentSelection.TotalValue() if !cart.GrandTotal().LikelyEqual(paymentSelectionTotal) { - return errors.New("Payment Total does not match with Grandtotal") + return errors.New("payment total does not match with grand total") } return nil } -// resetPaymentSelectionIfInvalid checks for valid paymentselection on givencart and deletes in in case it is invalid -func (cob *DefaultCartBehaviour) resetPaymentSelectionIfInvalid(ctx context.Context, cart *domaincart.Cart) (*domaincart.Cart, domaincart.DeferEvents, error) { +// resetPaymentSelectionIfInvalid checks for valid payment selection on given cart and deletes it in case it is invalid +func (cob *DefaultCartBehaviour) resetPaymentSelectionIfInvalid(ctx context.Context, cart *cartDomain.Cart) (*cartDomain.Cart, cartDomain.DeferEvents, error) { if cart.PaymentSelection == nil { return cart, nil, nil } @@ -661,12 +661,12 @@ func (cob *DefaultCartBehaviour) resetPaymentSelectionIfInvalid(ctx context.Cont } // ApplyVoucher checks the voucher and adds the voucher to the supplied cart if valid -func (DefaultVoucherHandler) ApplyVoucher(_ context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, error) { +func (DefaultVoucherHandler) ApplyVoucher(_ context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, error) { if couponCode != "valid_voucher" && couponCode != "valid" { return nil, errors.New("Code invalid") } - coupon := domaincart.CouponCode{ + coupon := cartDomain.CouponCode{ Code: couponCode, } @@ -675,11 +675,11 @@ func (DefaultVoucherHandler) ApplyVoucher(_ context.Context, cart *domaincart.Ca } // RemoveVoucher removes the voucher from the cart if possible -func (DefaultVoucherHandler) RemoveVoucher(_ context.Context, cart *domaincart.Cart, couponCode string) (*domaincart.Cart, error) { +func (DefaultVoucherHandler) RemoveVoucher(_ context.Context, cart *cartDomain.Cart, couponCode string) (*cartDomain.Cart, error) { for i, coupon := range cart.AppliedCouponCodes { if coupon.Code == couponCode { cart.AppliedCouponCodes[i] = cart.AppliedCouponCodes[len(cart.AppliedCouponCodes)-1] - cart.AppliedCouponCodes[len(cart.AppliedCouponCodes)-1] = domaincart.CouponCode{} + cart.AppliedCouponCodes[len(cart.AppliedCouponCodes)-1] = cartDomain.CouponCode{} cart.AppliedCouponCodes = cart.AppliedCouponCodes[:len(cart.AppliedCouponCodes)-1] return cart, nil } @@ -689,12 +689,12 @@ func (DefaultVoucherHandler) RemoveVoucher(_ context.Context, cart *domaincart.C } // ApplyGiftCard checks the gift card and adds it to the supplied cart if valid -func (DefaultGiftCardHandler) ApplyGiftCard(_ context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, error) { +func (DefaultGiftCardHandler) ApplyGiftCard(_ context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, error) { if giftCardCode != "valid_giftcard" && giftCardCode != "valid" { return nil, errors.New("Code invalid") } - giftCard := domaincart.AppliedGiftCard{ + giftCard := cartDomain.AppliedGiftCard{ Code: giftCardCode, Applied: priceDomain.NewFromInt(10, 100, "$"), Remaining: priceDomain.NewFromInt(0, 100, "$"), @@ -705,11 +705,11 @@ func (DefaultGiftCardHandler) ApplyGiftCard(_ context.Context, cart *domaincart. } // RemoveGiftCard removes the gift card from the cart if possible -func (DefaultGiftCardHandler) RemoveGiftCard(_ context.Context, cart *domaincart.Cart, giftCardCode string) (*domaincart.Cart, error) { - for i, giftcard := range cart.AppliedGiftCards { - if giftcard.Code == giftCardCode { +func (DefaultGiftCardHandler) RemoveGiftCard(_ context.Context, cart *cartDomain.Cart, giftCardCode string) (*cartDomain.Cart, error) { + for i, giftCard := range cart.AppliedGiftCards { + if giftCard.Code == giftCardCode { cart.AppliedGiftCards[i] = cart.AppliedGiftCards[len(cart.AppliedGiftCards)-1] - cart.AppliedGiftCards[len(cart.AppliedGiftCards)-1] = domaincart.AppliedGiftCard{} + cart.AppliedGiftCards[len(cart.AppliedGiftCards)-1] = cartDomain.AppliedGiftCard{} cart.AppliedGiftCards = cart.AppliedGiftCards[:len(cart.AppliedGiftCards)-1] return cart, nil } diff --git a/checkout/domain/sourcingengine.go b/checkout/domain/sourcingengine.go index da8e50f2f..b5d6bfd0b 100644 --- a/checkout/domain/sourcingengine.go +++ b/checkout/domain/sourcingengine.go @@ -2,6 +2,7 @@ package domain import ( "context" + "errors" "fmt" "math" @@ -13,23 +14,22 @@ import ( "flamingo.me/flamingo-commerce/v3/cart/application" "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" ) type ( // SourcingService helps in retrieving item sources // Deprecated: Sourcing moved to separate module SourcingService interface { - //GetSourceID returns one source location code where the product should be sourced - //@todo will be Deprecated in future in favor of SourcingServiceDetail interface + // GetSourceID returns one source location code where the product should be sourced + // @todo will be Deprecated in future in favor of SourcingServiceDetail interface GetSourceID(ctx context.Context, session *web.Session, decoratedCart *decorator.DecoratedCart, deliveryCode string, item *decorator.DecoratedCartItem) (string, error) } // SourcingServiceDetail additional interface to return // Deprecated: Sourcing moved to separate module SourcingServiceDetail interface { - //GetSourcesForItem returns Sources for the given item in the cart + // GetSourcesForItem returns Sources for the given item in the cart GetSourcesForItem(ctx context.Context, session *web.Session, decoratedCart *decorator.DecoratedCart, deliveryCode string, item *decorator.DecoratedCartItem) (Sources, error) - //GetAvailableSources returns Sources for the product - containing the maximum possible qty per source + // GetAvailableSources returns Sources for the product - containing the maximum possible qty per source GetAvailableSources(ctx context.Context, session *web.Session, decoratedCart *decorator.DecoratedCart, deliveryCode string, product domain.BasicProduct) (Sources, error) } @@ -58,9 +58,9 @@ type ( ) var ( - // ErrInsufficientSourceQty - use to indicate that the requested qty exceeds the available qty + // ErrInsufficientSourceQty should be used to indicate that the requested qty exceeds the available qty ErrInsufficientSourceQty = errors.New("Available Source Qty insufficient") - // ErrNoSourceAvailable - use to indicate that no source for item is available at all + // ErrNoSourceAvailable should be used to indicate that no source for item is available at all ErrNoSourceAvailable = errors.New("No Available Source Qty") ) @@ -97,7 +97,7 @@ func (s Sources) Next() (Source, Sources, error) { // QtySum returns the sum of all sourced items func (s Sources) QtySum() int { - qty := int(0) + qty := 0 for _, source := range s { if source.Qty == math.MaxInt64 { return math.MaxInt64 @@ -108,11 +108,11 @@ func (s Sources) QtySum() int { } // Reduce returns new Source -func (s Sources) Reduce(reduceby Sources) Sources { +func (s Sources) Reduce(reduceBy Sources) Sources { for k, source := range s { - for _, reducebySource := range reduceby { - if source.LocationCode == reducebySource.LocationCode { - s[k].Qty = s[k].Qty - reducebySource.Qty + for _, reduceBySource := range reduceBy { + if source.LocationCode == reduceBySource.LocationCode { + s[k].Qty = s[k].Qty - reduceBySource.Qty } } } @@ -149,7 +149,7 @@ func (se *SourcingEngine) SetSourcesForCartItems(ctx context.Context, session *w err := se.Cartservice.UpdateItems(ctx, session, itemUpdateCommands) if err != nil { - return errors.Wrap(err, "Could not update cart items") + return fmt.Errorf("Could not update cart items: %w", err) } return nil diff --git a/go.mod b/go.mod index 449c19b93..6ac18dfca 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,6 @@ require ( github.com/google/uuid v1.1.2 github.com/gordonklaus/ineffassign v0.0.0-20201107091007-3b93a8888063 // indirect github.com/leekchan/accounting v0.0.0-20191104051123-0b9b0bd19c36 - github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.6.1 github.com/stvp/tempredis v0.0.0-20181119212430-b82af8480203 github.com/swaggo/swag v1.6.6-0.20200603163350-20638f327979 diff --git a/product/interfaces/controller/apicontroller.go b/product/interfaces/controller/apicontroller.go index f5a00099d..27670fef9 100644 --- a/product/interfaces/controller/apicontroller.go +++ b/product/interfaces/controller/apicontroller.go @@ -2,11 +2,11 @@ package controller import ( "context" + "errors" "flamingo.me/flamingo-commerce/v3/product/application" "flamingo.me/flamingo-commerce/v3/product/domain" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" ) type ( @@ -27,7 +27,7 @@ type ( resultError struct { Message string Code string - } //@name productResultError + } // @name productResultError ) // Inject dependencies @@ -47,12 +47,12 @@ func (c *APIController) Inject(responder *web.Responder, // @Success 200 {object} APIResult{product=domain.SimpleProduct} // @Failure 500 {object} APIResult // @Failure 404 {object} APIResult -// @Param marketplacecode path string true "the marketplace code (idendifier) for the product" +// @Param marketplacecode path string true "the marketplace code (identifier) for the product" // @Router /api/v1/products/{marketplacecode} [get] func (c *APIController) Get(ctx context.Context, r *web.Request) web.Result { product, err := c.productService.Get(ctx, r.Params["marketplacecode"]) if err != nil { - switch errors.Cause(err).(type) { + switch errors.Unwrap(err).(type) { case domain.ProductNotFound: return c.responder.Data(APIResult{ Success: false, diff --git a/product/interfaces/controller/controller.go b/product/interfaces/controller/controller.go index 74681a988..d9417f9f9 100644 --- a/product/interfaces/controller/controller.go +++ b/product/interfaces/controller/controller.go @@ -2,11 +2,11 @@ package controller import ( "context" + "errors" "net/url" "strings" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" "flamingo.me/flamingo-commerce/v3/product/application" "flamingo.me/flamingo-commerce/v3/product/domain" @@ -90,7 +90,7 @@ func (vc *View) variantSelection(configurable domain.ConfigurableProduct, active combinationsOrder[attribute] = append(combinationsOrder[attribute], variant.Attributes[attribute].Value()) } - //titles[variant.Attributes[subattribute].Value()] = variant.Attributes[subattribute].Label + // titles[variant.Attributes[subattribute].Value()] = variant.Attributes[subattribute].Label if subattribute != attribute { if _, ok := variant.Attributes[subattribute]; ok { if combinations[attribute][variant.Attributes[attribute].Value()][subattribute] == nil { @@ -184,17 +184,19 @@ func (vc *View) variantSelection(configurable domain.ConfigurableProduct, active // Get Response for Product matching sku param func (vc *View) Get(c context.Context, r *web.Request) web.Result { product, err := vc.ProductService.Get(c, r.Params["marketplacecode"]) - skipnamecheck, _ := r.Params["skipnamecheck"] + skipNameCheck, _ := r.Params["skipnamecheck"] // catch error if err != nil { - switch errors.Cause(err).(type) { - case domain.ProductNotFound: - return vc.Responder.NotFound(err) + if unwrappedErr := errors.Unwrap(err); unwrappedErr != nil { + err = unwrappedErr + } - default: - return vc.Responder.ServerError(err) + if _, ok := err.(domain.ProductNotFound); ok { + return vc.Responder.NotFound(err) } + + return vc.Responder.ServerError(err) } var viewData productViewData @@ -208,8 +210,8 @@ func (vc *View) Get(c context.Context, r *web.Request) web.Result { variantCode, ok := r.Params["variantcode"] if !ok { - //Redirect if url is not canonical - redirect := vc.getRedirectIfRequired(configurableProduct, r, skipnamecheck) + // Redirect if url is not canonical + redirect := vc.getRedirectIfRequired(configurableProduct, r, skipNameCheck) if redirect != nil { return redirect } @@ -223,8 +225,8 @@ func (vc *View) Get(c context.Context, r *web.Request) web.Result { return vc.Responder.NotFound(err) } activeVariant = &configurableProductWithActiveVariant.ActiveVariant - //Redirect if url is not canonical - redirect := vc.getRedirectIfRequired(configurableProductWithActiveVariant, r, skipnamecheck) + // Redirect if url is not canonical + redirect := vc.getRedirectIfRequired(configurableProductWithActiveVariant, r, skipNameCheck) if redirect != nil { return redirect } @@ -235,8 +237,8 @@ func (vc *View) Get(c context.Context, r *web.Request) web.Result { viewData.VariantSelection = vc.variantSelection(configurableProduct, activeVariant) } else { - //Redirect if url is not canonical - redirect := vc.getRedirectIfRequired(product, r, skipnamecheck) + // Redirect if url is not canonical + redirect := vc.getRedirectIfRequired(product, r, skipNameCheck) if redirect != nil { return redirect } @@ -264,7 +266,7 @@ func (vc *View) getRedirectIfRequired(product domain.BasicProduct, r *web.Reques if skipnamecheck != "" { return nil } - //Redirect if url is not canonical + // Redirect if url is not canonical if vc.URLService.GetNameParam(product, "") != currentNameParameter { if redirectURL, err := vc.URLService.Get(product, ""); err == nil { newURL, _ := url.Parse(redirectURL) diff --git a/product/interfaces/controller/controller_test.go b/product/interfaces/controller/controller_test.go index 64f6b1f0c..c78bbf5a1 100644 --- a/product/interfaces/controller/controller_test.go +++ b/product/interfaces/controller/controller_test.go @@ -3,6 +3,7 @@ package controller import ( "context" "errors" + "fmt" "net/http" "net/url" "testing" @@ -74,6 +75,9 @@ func (mps *MockProductService) Get(_ context.Context, marketplacecode string) (d if marketplacecode == "not_found" { return nil, domain.ProductNotFound{MarketplaceCode: "not_found"} } + if marketplacecode == "not_found_wrapped" { + return nil, fmt.Errorf("wrap it: %w", domain.ProductNotFound{MarketplaceCode: "not_found"}) + } if marketplacecode == "simple" { return domain.SimpleProduct{ BasicProductData: domain.BasicProductData{Title: "My Product Title", MarketPlaceCode: marketplacecode}, @@ -127,22 +131,29 @@ func TestViewController_GetNotFound(t *testing.T) { marketPlaceCode: "not_found", expectedStatus: http.StatusNotFound, }, + { + name: "not found wrapped error", + marketPlaceCode: "not_found_wrapped", + expectedStatus: http.StatusNotFound, + }, } for _, tt := range tests { - vc := getController() - - // call with correct name parameter and expect Rendering - ctx := context.Background() - r := web.CreateRequest(&http.Request{}, nil) - r.Request().URL = &url.URL{} - r.Params = web.RequestParams{ - "marketplacecode": tt.marketPlaceCode, - "name": tt.marketPlaceCode, - } + t.Run(tt.name, func(t *testing.T) { + vc := getController() + + // call with correct name parameter and expect Rendering + ctx := context.Background() + r := web.CreateRequest(&http.Request{}, nil) + r.Request().URL = &url.URL{} + r.Params = web.RequestParams{ + "marketplacecode": tt.marketPlaceCode, + "name": tt.marketPlaceCode, + } - result := vc.Get(ctx, r) - require.IsType(t, &web.ServerErrorResponse{}, result) - assert.Equal(t, int(tt.expectedStatus), int(result.(*web.ServerErrorResponse).Response.Status)) + result := vc.Get(ctx, r) + require.IsType(t, &web.ServerErrorResponse{}, result) + assert.Equal(t, int(tt.expectedStatus), int(result.(*web.ServerErrorResponse).Response.Status)) + }) } } diff --git a/sourcing/domain/service.go b/sourcing/domain/service.go index 9d4af5c93..7585bc7b2 100644 --- a/sourcing/domain/service.go +++ b/sourcing/domain/service.go @@ -2,6 +2,8 @@ package domain import ( "context" + "errors" + "fmt" "math" cartDomain "flamingo.me/flamingo-commerce/v3/cart/domain/cart" @@ -9,15 +11,13 @@ import ( "flamingo.me/flamingo-commerce/v3/product/domain" "flamingo.me/flamingo/v3/framework/flamingo" - - "github.com/pkg/errors" ) type ( // SourcingService describes the main port used by the sourcing logic. SourcingService interface { // AllocateItems returns Sources for the given item in the given cart - // e.g. use this during place order to know + // e.g. use this during place order to know where to source from // throws ErrInsufficientSourceQty if not enough stock is available for the amount of items in the cart // throws ErrNoSourceAvailable if no source is available at all for one of the items // throws ErrNeedMoreDetailsSourceCannotBeDetected if information on the cart (or delivery is missing) @@ -79,13 +79,13 @@ type ( var ( _ SourcingService = new(DefaultSourcingService) - // ErrInsufficientSourceQty - use to indicate that the requested qty exceeds the available qty + // ErrInsufficientSourceQty should be used to indicate that the requested qty exceeds the available qty ErrInsufficientSourceQty = errors.New("Available Source Qty insufficient") - // ErrNoSourceAvailable - use to indicate that no source for item is available at all + // ErrNoSourceAvailable should be used to indicate that no source for item is available at all ErrNoSourceAvailable = errors.New("No Available Source Qty") - // ErrNeedMoreDetailsSourceCannotBeDetected - use to indicate that informations are missing to determine a source + // ErrNeedMoreDetailsSourceCannotBeDetected should be used to indicate that information are missing to determine a source ErrNeedMoreDetailsSourceCannotBeDetected = errors.New("Source cannot be detected") ) @@ -149,7 +149,7 @@ func (d *DefaultSourcingService) GetAvailableSources(ctx context.Context, produc if len(availableSources) == 0 { if lastStockError != nil { - return availableSources, errors.Wrap(ErrNoSourceAvailable, lastStockError.Error()) + return availableSources, fmt.Errorf("%w: %s", ErrNoSourceAvailable, lastStockError.Error()) } return availableSources, ErrNoSourceAvailable } @@ -247,7 +247,7 @@ func (d *DefaultSourcingService) allocateItem(ctx context.Context, productSource } for _, source := range sources { - // if we have no stock given for source and productid we fetch it initially + // if we have no stock given for source and product id we fetch it initially if _, exists := remainingSourcestock[productID][source]; !exists { sourceStock, err := d.stockProvider.GetStock(ctx, decoratedItem.Product, source, &deliveryInfo) if err != nil { @@ -272,7 +272,7 @@ func (d *DefaultSourcingService) allocateItem(ctx context.Context, productSource // increment allocatedQty by allocated Stock allocatedQty = allocatedQty + stockToAllocate - // decrement remaining productSourceStock accordingly as its not happening by itself + // decrement remaining productSourceStock accordingly as it's not happening by itself remainingSourcestock[productID][source] = remainingSourcestock[productID][source] - stockToAllocate } } diff --git a/w3cdatalayer/application/factory.go b/w3cdatalayer/application/factory.go index 7703561cd..c9e5ed1f5 100644 --- a/w3cdatalayer/application/factory.go +++ b/w3cdatalayer/application/factory.go @@ -5,6 +5,7 @@ import ( "crypto/sha512" "encoding/base64" "encoding/hex" + "fmt" "net/url" "regexp" "strconv" @@ -14,7 +15,6 @@ import ( "flamingo.me/flamingo/v3/core/auth" "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" - "github.com/pkg/errors" "go.opencensus.io/tag" "flamingo.me/flamingo-commerce/v3/cart/domain/decorator" @@ -23,7 +23,7 @@ import ( ) type ( - // Factory is used to build new datalayers + // Factory is used to build new data layers Factory struct { router *web.Router logger flamingo.Logger @@ -128,7 +128,7 @@ func (s Factory) BuildForCurrentRequest(ctx context.Context, request *web.Reques baseURL, err := s.router.Absolute(request, request.Request().URL.Path, nil) if err != nil { - s.logger.Warn(errors.Wrap(err, "cannot build absolute url")) + s.logger.Warn(fmt.Errorf("cannot build absolute url: %w", err)) baseURL = new(url.URL) } layer.Page = &domain.Page{ @@ -456,7 +456,7 @@ func (s Factory) hashWithSHA512(value string) string { newHash.Write([]byte(value)) // the hash is a byte array result := newHash.Sum(nil) - // since we want to use it in a variable we base64 encode it (other alternative would be Hexadecimal representation "% x", h.Sum(nil) + // since we want to use it in a variable we base64 encode it (other alternative would be Hexadecimal representation "% x", h.Sum(nil)) return s.hashEncoder.EncodeToString(result) } diff --git a/w3cdatalayer/application/service.go b/w3cdatalayer/application/service.go index e29a41d0c..c71deeb5d 100644 --- a/w3cdatalayer/application/service.go +++ b/w3cdatalayer/application/service.go @@ -2,6 +2,7 @@ package application import ( "context" + "errors" "fmt" "flamingo.me/flamingo-commerce/v3/cart/domain/decorator" @@ -11,7 +12,6 @@ import ( "flamingo.me/flamingo/v3/framework/flamingo" "flamingo.me/flamingo/v3/framework/web" "flamingo.me/pugtemplate/pugjs" - "github.com/pkg/errors" ) type ( @@ -21,7 +21,7 @@ type ( // Service can be used from outside is expected to be initialized with the current request context // It stores a dataLayer Value object for the current request context and allows interaction with it Service struct { - //currentContext need to be set when using the service + // currentContext need to be set when using the service currentContext context.Context logger flamingo.Logger factory *Factory @@ -47,7 +47,7 @@ func (s *Service) Init(ctx context.Context) { s.currentContext = ctx } -// Get gets the data layer value object stored in the current context - or a freshly new build one if its the first call +// Get gets the data layer value object stored in the current context - or a freshly new build one if it's the first call func (s *Service) Get() domain.Datalayer { if s.currentContext == nil { s.logger.WithField("category", "w3cDatalayer").Error("Get called without context!") @@ -66,7 +66,7 @@ func (s *Service) Get() domain.Datalayer { return savedDataLayer } - //error + // error s.logger.WithField("category", "w3cDatalayer").Warn("Receiving datalayer from context failed") return domain.Datalayer{} }