Example #1
0
        public void Discount_Coupon_Persistance_Succeeds()
        {
            var discounts = new[]
            {
                new DiscountCoupon()
                {
                    Name                 = "Test Coupon One",
                    CalculationType      = CalculationType.FixedAmount,
                    CouponCode           = "TESTCOUPON",
                    HasCouponCode        = true,
                    DiscountValue        = 50,
                    Enabled              = true,
                    StartDate            = DateTime.UtcNow,
                    EndDate              = DateTime.UtcNow.AddDays(5),
                    NumberOfTimesPerUser = 1,
                    TotalNumberOfTimes   = 5
                },
                new DiscountCoupon()
                {
                    Name                  = "Test Coupon Two",
                    CalculationType       = CalculationType.Percentage,
                    CouponCode            = "TESTCOUPON",
                    HasCouponCode         = true,
                    DiscountValue         = 5,
                    Enabled               = true,
                    StartDate             = DateTime.UtcNow,
                    EndDate               = DateTime.UtcNow.AddDays(5),
                    NumberOfTimesPerUser  = 1,
                    TotalNumberOfTimes    = 5,
                    MaximumDiscountAmount = 10
                },
                new DiscountCoupon()
                {
                    Name                  = "Expired Coupon",
                    CalculationType       = CalculationType.Percentage,
                    HasCouponCode         = false,
                    DiscountValue         = 5,
                    Enabled               = true,
                    StartDate             = DateTime.UtcNow.AddDays(-5),
                    EndDate               = DateTime.UtcNow.AddDays(-1),
                    NumberOfTimesPerUser  = 1,
                    TotalNumberOfTimes    = 5,
                    MaximumDiscountAmount = 10
                },
            };

            //save some discounts
            _discountCouponService.Insert(discounts);


            //asserts
            Assert.AreEqual(discounts[1].Id, _discountCouponService.GetByCouponCode("testcoupon").Id);
            Assert.AreEqual(discounts[1].Id, _discountCouponService.Get(discounts[1].Id).Id);
            Assert.AreEqual(discounts[0].CouponCode, _discountCouponService.Get(discounts[0].Id).CouponCode);
            Assert.AreEqual(1, _discountCouponService.SearchDiscountCoupons("test", out var totalMatches, 1, 1).Count());
            Assert.AreEqual(2, totalMatches);
            //delete discounts
            _discountCouponService.Delete(x => x.Id > 0);
        }
        public IActionResult SaveDiscount(DiscountModel discountModel)
        {
            var discount = discountModel.Id > 0 ? _discountCouponService.Get(discountModel.Id) : new DiscountCoupon();

            if (discount == null)
            {
                return(NotFound());
            }
            discountModel.StartDate = discountModel.StartDate ?? DateTime.UtcNow;
            _modelMapper.Map(discountModel, discount);
            discount.StartDate = discountModel.StartDate.Value;
            _discountCouponService.InsertOrUpdate(discount);

            //update the restrictions
            var restrictionIdentifiers = discountModel.RestrictionValues?.Select(x => x.RestrictionIdentifier).ToList();

            _discountCouponService.SetRestrictionIdentifiers(discount.Id, restrictionIdentifiers);
            return(R.Success.With("id", discount.Id).Result);
        }
Example #3
0
        public void RefreshCartParameters(Cart cart)
        {
            //update prices if we need to
            var cartProductIds = cart.CartItems.Select(x => x.ProductId).ToList();

            if (cartProductIds.Any())
            {
                var products        = _productService.GetProducts(cartProductIds);
                var productVariants = _productVariantService.Get(x => cartProductIds.Contains(x.ProductId)).ToList();

                Transaction.Initiate(transaction =>
                {
                    //preserve autodiscounts for performance
                    IList <DiscountCoupon> discountCoupons = _discountCouponService.Get(x => x.Enabled && !x.HasCouponCode).Where(x => !x.Expired).ToList();
                    //update cart items if required
                    foreach (var ci in cart.CartItems)
                    {
                        var product = products.FirstOrDefault(x => x.Id == ci.ProductId);
                        if (product == null)
                        {
                            //remove from cart because we can't find the product
                            _cartService.RemoveFromCart(ci.Id, transaction);
                        }
                        else
                        {
                            if (!product.Published || product.Deleted)
                            {
                                //remove from cart because product shouldn't be visible
                                _cartService.RemoveFromCart(ci.Id, transaction);
                            }
                            else if (product.RestrictedToRoles)
                            {
                                var roleIds = cart.User.Roles.Select(x => x.Id).ToList();
                                if (product.EntityRoles.All(x => !roleIds.Contains(x.RoleId)))
                                {
                                    //remove because role is not allowed to buy this product
                                    _cartService.RemoveFromCart(ci.Id, transaction);
                                }
                            }
                            else if (product.TrackInventory)
                            {
                                if (!product.HasVariants && !product.IsAvailableInStock())
                                {
                                    //remove from cart because we can't find the product
                                    _cartService.RemoveFromCart(ci.Id, transaction);
                                }
                            }
                            if (ci.Quantity < product.MinimumPurchaseQuantity && product.MinimumPurchaseQuantity > 0)
                            {
                                //is there a difference in quantity that's required
                                ci.Quantity = product.MinimumPurchaseQuantity;
                            }
                            if (ci.Quantity > product.MaximumPurchaseQuantity && product.MaximumPurchaseQuantity > 0)
                            {
                                //is there a difference in quantity that's required
                                ci.Quantity = product.MaximumPurchaseQuantity;
                            }

                            var variant = product.HasVariants && ci.ProductVariantId > 0
                                ? productVariants.FirstOrDefault(x => x.Id == ci.ProductVariantId)
                                : null;
                            //are there any discounted price for product
                            var basePrice = GetAutoDiscountedPriceForUser(product, variant, cart.User, ci.Quantity, ref discountCoupons, out decimal discount);
                            if (product.HasVariants && ci.ProductVariantId > 0)
                            {
                                if (variant == null || (variant.TrackInventory && !variant.IsAvailableInStock(product)))
                                {
                                    //remove from cart because we can't find the variant or it's out of stock
                                    _cartService.RemoveFromCart(ci.Id, transaction);
                                }
                                else
                                {
                                    var comparisonPrice = variant.ComparePrice ?? product.ComparePrice;
                                    var price           = Math.Min(basePrice, variant.Price ?? product.Price);

                                    GetProductPriceDetails(product, cart.BillingAddress, price, out decimal priceWithoutTax, out decimal tax, out decimal taxRate, out var taxName);
                                    var expectedFinalPrice = priceWithoutTax * ci.Quantity + tax * ci.Quantity;
                                    //do we need an update?
                                    if (priceWithoutTax != ci.Price ||
                                        comparisonPrice != ci.ComparePrice ||
                                        tax != ci.Tax ||
                                        taxRate != ci.TaxPercent ||
                                        ci.FinalPrice == 0 ||
                                        ci.TaxName != taxName ||
                                        ci.FinalPrice != expectedFinalPrice)
                                    {
                                        ci.Price        = priceWithoutTax;
                                        ci.ComparePrice = comparisonPrice;
                                        ci.Tax          = tax * ci.Quantity;
                                        ci.TaxPercent   = taxRate;
                                        ci.Discount     = discount;
                                        ci.FinalPrice   = expectedFinalPrice;
                                        ci.TaxName      = taxName;
                                        _cartItemService.Update(ci);
                                    }
                                }
                            }
                            else
                            {
                                GetProductPriceDetails(product, cart.BillingAddress, basePrice, out decimal priceWithoutTax, out decimal tax, out decimal taxRate, out var taxName);
                                tax = tax * ci.Quantity;
                                var expectedFinalPrice = priceWithoutTax * ci.Quantity + tax * ci.Quantity;
                                //do we need an update?
                                if (priceWithoutTax != ci.Price ||
                                    product.ComparePrice != ci.ComparePrice ||
                                    tax != ci.Tax ||
                                    taxRate != ci.TaxPercent ||
                                    ci.FinalPrice == 0 ||
                                    ci.TaxName != taxName ||
                                    ci.FinalPrice != expectedFinalPrice)
                                {
                                    ci.Price        = priceWithoutTax;
                                    ci.ComparePrice = product.ComparePrice;
                                    ci.Tax          = tax;
                                    ci.TaxPercent   = taxRate;
                                    ci.Discount     = discount;
                                    ci.FinalPrice   = expectedFinalPrice;
                                    ci.TaxName      = taxName;
                                    _cartItemService.Update(ci);
                                }
                            }
                        }
                    }
                    cart.FinalAmount        = cart.CartItems.Sum(x => x.FinalPrice);
                    cart.CompareFinalAmount = cart.CartItems.Sum(x => x.ComparePrice ?? 0);

                    //do we have a discount coupon
                    if (cart.DiscountCoupon != null && cart.DiscountCoupon.Enabled && !cart.DiscountCoupon.Expired)
                    {
                        if (ApplyDiscountCoupon(cart.DiscountCoupon, cart) == DiscountApplicationStatus.Success)
                        {
                            //cart already updated so return
                            return;
                        }
                    }
                    else
                    {
                        if (cart.DiscountCoupon != null)
                        {
                            cart.DiscountCouponId = 0;
                            _cartService.Update(cart);
                        }

                        ////find coupons which should be automatically applied
                        foreach (var dc in discountCoupons)
                        {
                            if (ApplyDiscountCoupon(dc, cart) == DiscountApplicationStatus.Success)
                            {
                                break;
                            }
                        }
                    }
                });
            }
        }