Esempio n. 1
0
        public void HigherPriorityWins()
        {
            var frenchTax1 = GetFrenchTax();

            frenchTax1.Priority = 1;
            frenchTax1.Rate     = 0.1;
            var anyCountryTax = GetAnyCountryTax();

            anyCountryTax.Priority = 2;
            anyCountryTax.Rate     = 0.2;
            var frenchTax2 = GetFrenchTax();

            frenchTax2.Priority = 3;
            frenchTax2.Rate     = 0.3;
            var taxProvider = new FakeTaxProvider(new[] { frenchTax1, frenchTax2, anyCountryTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = frenchTax1.Country;
            var subtotal = cart.Subtotal();

            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * frenchTax2.Rate));

            anyCountryTax.Priority = 4;
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * anyCountryTax.Rate));
        }
        public async Task ShoppingCartSerializesAndDeserializes()
        {
            var cart = new ShoppingCart(
                new ShoppingCartItem(2, "product-1", prices: new[]
            {
                new PrioritizedPrice(0, new Amount(10, Currency.Euro)),
                new PrioritizedPrice(1, new Amount(7, Currency.USDollar))
            }),
                new ShoppingCartItem(1, "product-2", attributes: new IProductAttributeValue[]
            {
                new BooleanProductAttributeValue("ProductPart3.attr1", true),
                new NumericProductAttributeValue("ProductPart3.attr3", (decimal?)42.0)
            }, prices: new[]
            {
                new PrioritizedPrice(0, new Amount(12, Currency.USDollar))
            }));
            var helpers = new ShoppingCartHelpers(
                attributeProviders: new[] { new ProductAttributeProvider() },
                productService: new FakeProductService(),
                moneyService: new TestMoneyService(),
                contentDefinitionManager: new FakeContentDefinitionManager());
            string serialized = await helpers.Serialize(cart);

            ShoppingCart deserialized = await helpers.Deserialize(serialized);

            Assert.Equal(cart.Count, deserialized.Count);
            Assert.Equal(cart.ItemCount, deserialized.ItemCount);

            Assert.Equal(cart.Items, deserialized.Items);
        }
        //UNDONE POST ONLY
        //
        // POST: /Checkout/Checkout
        //[ValidateAntiForgeryToken]
        public ActionResult Checkout()
        {
            //Get current cart items
            var currentCartItems = _shoppingCartService
                                   .GetCartWithAssociatedProducts(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext)).ToList();

            //If there are no cart items, redirect to the shoppingcart index
            if (!currentCartItems.Any())
            {
                return(RedirectToAction("Index", "ShoppingCart"));
            }

            //Construct the model that will be the container for the collected checkout information
            CheckoutViewModel checkoutModel = new CheckoutViewModel(currentCartItems, Guid.NewGuid().ToString("N"));

            //Cache the container model at a well known location unique to the user, sliding expiration of 10 minutes
            CacheHelpers.InsertCheckoutInstanceIntoCache(checkoutModel, this.ControllerContext);

            //Construct & hydrate the first step viewmodel
            var availableAddressesForUser = _userService.GetUserWithAddresses(IdentityHelpers.GetUserId(User.Identity)).Addresses.AsEnumerable();

            var model = checkoutModel.GetShippingViewModel(availableAddressesForUser);

            #region TestInformation
#if DEBUG
            model.Email       = "*****@*****.**";
            model.PhoneNumber = "1234567890";
#endif
            #endregion

            return(View("ShippingInformation", model));
        }
        public ActionResult LogOff()
        {
            AuthenticationManager.SignOut();

            //Clear the shopping cart id
            ShoppingCartHelpers.SetShoppingCartID(this.ControllerContext, null);

            return(RedirectToAction("Index", "Home"));
        }
        public void AbsoluteDiscountApplies()
        {
            var absoluteDiscount = new DiscountStub(4)
            {
                Discount = 10,
                Comment  = "Absolute discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { absoluteDiscount });

            CheckDiscounts(cart, new[] { 0, 0, 0.5M }, new[] { absoluteDiscount.Comment, absoluteDiscount.Comment, absoluteDiscount.Comment });
        }
        public void ThirtyOffWholeCatalogYieldsThirtyOffRebate()
        {
            var discount = new DiscountStub(4)
            {
                DiscountPercent = 30,
                Comment         = "30% off the whole catalog"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { discount });

            CheckDiscount(cart, 0.7M, discount.Comment);
        }
        public void ExclusionPatternExcludesRightItems()
        {
            var patternDiscount = new DiscountStub(4)
            {
                DiscountPercent  = 10,
                ExclusionPattern = "foo",
                Comment          = "Pattern discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { patternDiscount });

            CheckDiscounts(cart, new[] { 1, 0.9M, 1 }, new[] { "", patternDiscount.Comment, "" });
        }
        public void PatternAppliesToRightItems()
        {
            var patternDiscount = new DiscountStub(4)
            {
                DiscountPercent = 10,
                Pattern         = "foo/ba",
                Comment         = "Pattern discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { patternDiscount });

            CheckDiscounts(cart, new[] { 0.9M, 1, 0.9M }, new[] { patternDiscount.Comment, "", patternDiscount.Comment });
        }
        public void RoleNotFoundDiscountDoesntApply()
        {
            var roleDiscount = new DiscountStub(4)
            {
                DiscountPercent = 10,
                Roles           = new[] { "Administrator", "Employee" },
                Comment         = "Role discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { roleDiscount });

            CheckDiscount(cart, 1, "");
        }
        public void RoleFoundDiscountApplies()
        {
            var roleDiscount = new DiscountStub(4)
            {
                DiscountPercent = 10,
                Roles           = new[] { "Employee", "Reseller" },
                Comment         = "Role discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { roleDiscount });

            CheckDiscount(cart, 0.9M, roleDiscount.Comment);
        }
        public void CurrentlyValidDiscountApplies()
        {
            var currentDiscount = new DiscountStub(4)
            {
                DiscountPercent = 5,
                StartDate       = new DateTime(2012, 11, 24, 10, 0, 0, DateTimeKind.Utc),
                EndDate         = new DateTime(2012, 11, 24, 14, 0, 0, DateTimeKind.Utc),
                Comment         = "Currently valid discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { currentDiscount });

            CheckDiscount(cart, 0.95M, currentDiscount.Comment);
        }
        public void WideEnoughQuantityDiscountApplies()
        {
            var wideEnoughDiscount = new DiscountStub(4)
            {
                DiscountPercent = 10,
                StartQuantity   = 3,
                EndQuantity     = 6,
                Comment         = "Wide enough discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { wideEnoughDiscount });

            CheckDiscount(cart, 0.9M, wideEnoughDiscount.Comment);
        }
        public void QuantityDiscountAppliesToRightItems()
        {
            var selectiveDiscount = new DiscountStub(4)
            {
                DiscountPercent = 10,
                StartQuantity   = 4,
                EndQuantity     = 6,
                Comment         = "4-5 item discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { selectiveDiscount });

            CheckDiscounts(cart, new[] { 1, 0.9M, 0.9M }, new[] { "", selectiveDiscount.Comment, selectiveDiscount.Comment });
        }
        public void ExclusionPatternExcludesRightItemsAfterPatternHasIncluded()
        {
            var patternDiscount = new DiscountStub(4)
            {
                DiscountPercent  = 10,
                Pattern          = "bar",
                ExclusionPattern = "baz",
                Comment          = "Pattern discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { patternDiscount });

            CheckDiscounts(cart, new[] { 0.9M, 1, 1 }, new[] { patternDiscount.Comment, "", "" });
        }
Esempio n. 15
0
        public void TaxDoesntApplyToDifferentCountry()
        {
            var oregonTax   = GetOregonTax();
            var taxProvider = new FakeTaxProvider(new[] { oregonTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = "France";
            cart.ZipCode = "97218";

            var taxes = cart.Taxes();

            Assert.That(taxes.Name, Is.Null);
            Assert.That(taxes.Amount, Is.EqualTo(0));
        }
Esempio n. 16
0
        public void AnyCountryTaxAppliesToAnyCountry()
        {
            var anyCountryTax = GetAnyCountryTax();
            var taxProvider   = new FakeTaxProvider(new[] { anyCountryTax });
            var cart          = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });
            var subtotal      = cart.Subtotal();

            cart.Country = Country.UnitedStates;
            cart.ZipCode = "98008";
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * anyCountryTax.Rate));

            cart.Country = "France";
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * anyCountryTax.Rate));
        }
Esempio n. 17
0
        public void RightTaxAppliesToTabRates()
        {
            var tabZipTax = new ZipCodeTaxPart();

            ContentHelpers.PreparePart(tabZipTax, "Tax");
            tabZipTax.Rates = TabRates;

            var taxProvider = new FakeTaxProvider(new[] { tabZipTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = "United States";
            cart.ZipCode = "52412";

            CheckTaxes(cart.Taxes().Amount, 11.12);
        }
Esempio n. 18
0
        public void RightTaxAppliesToCsvRates()
        {
            var csvZipTax = new ZipCodeTaxPart();

            ContentHelpers.PreparePart(csvZipTax, "Tax");
            csvZipTax.Rates = CsvRates;

            var taxProvider = new FakeTaxProvider(new[] { csvZipTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = "United States";
            cart.ZipCode = "52627";

            CheckTaxes(cart.Taxes().Amount, 6.95);
        }
Esempio n. 19
0
        public void NoNegativeTax()
        {
            var frenchTax = GetFrenchTax();

            frenchTax.Rate = -0.5;
            var taxProvider = new FakeTaxProvider(new[] { frenchTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = frenchTax.Country;

            var taxes = cart.Taxes();

            Assert.That(taxes.Name, Is.Null);
            Assert.That(taxes.Amount, Is.EqualTo(0));
        }
Esempio n. 20
0
        public void NoApplicableTaxesYieldsNoTax()
        {
            var frenchTax     = GetFrenchTax();
            var britishTax    = GetBritishTax();
            var washingtonTax = GetWashingtonTax();
            var oregonTax     = GetOregonTax();
            var taxProvider   = new FakeTaxProvider(new[] { washingtonTax, britishTax, frenchTax, oregonTax });
            var cart          = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = "Kazakhstan";

            var taxes = cart.Taxes();

            Assert.That(taxes.Name, Is.Null);
            Assert.That(taxes.Amount, Is.EqualTo(0));
        }
        private static void CheckDiscount(IShoppingCart cart, decimal discountRate, string comment)
        {
            const double epsilon          = 0.001;
            var          expectedSubTotal = Math.Round(ShoppingCartHelpers.OriginalQuantities.Sum(q => q.Quantity * Math.Round(q.Product.Price * discountRate, 2)), 2);

            Assert.That(Math.Abs(cart.Subtotal() - expectedSubTotal), Is.LessThan(epsilon));
            var cartContents = cart.GetProducts().ToList();

            foreach (var shoppingCartQuantityProduct in cartContents)
            {
                Assert.That(
                    Math.Abs(ShoppingCartHelpers.CartPriceOf(shoppingCartQuantityProduct.Product, cartContents) -
                             Math.Round(shoppingCartQuantityProduct.Product.Price * discountRate, 2)), Is.LessThan(epsilon));
                Assert.That(shoppingCartQuantityProduct.Comment ?? "", Is.EqualTo(comment));
            }
        }
Esempio n. 22
0
        public void TaxDoesNotApplyToNonMatchingZip()
        {
            var csvZipTax = new ZipCodeTaxPart();

            ContentHelpers.PreparePart(csvZipTax, "Tax");
            csvZipTax.Rates = CsvRates;

            var taxProvider = new FakeTaxProvider(new[] { csvZipTax });
            var cart        = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = "United States";
            cart.ZipCode = "90210";

            var taxes = cart.Taxes();

            Assert.AreEqual(0, taxes.Amount);
            Assert.IsNull(taxes.Name);
        }
        private static void CheckDiscounts(IShoppingCart cart, decimal[] discountRates, string[] comments)
        {
            const double epsilon          = 0.001;
            var          cartContents     = cart.GetProducts().ToList();
            var          i                = 0;
            var          expectedSubTotal = 0.0M;

            foreach (var shoppingCartQuantityProduct in cartContents)
            {
                var discountedPrice = Math.Round(shoppingCartQuantityProduct.Product.Price * discountRates[i], 2);
                Assert.That(
                    Math.Abs(ShoppingCartHelpers.CartPriceOf(shoppingCartQuantityProduct.Product, cartContents) - discountedPrice),
                    Is.LessThan(epsilon));
                Assert.That(shoppingCartQuantityProduct.Comment ?? "", Is.EqualTo(comments[i]));
                expectedSubTotal += shoppingCartQuantityProduct.Quantity * discountedPrice;
                i++;
            }
            Assert.That(Math.Abs(cart.Subtotal() - expectedSubTotal), Is.LessThan(epsilon));
        }
        public void OldAndFutureDiscountsDontApply()
        {
            var oldDiscount = new DiscountStub(4)
            {
                DiscountPercent = 5,
                StartDate       = new DateTime(2012, 11, 1, 12, 0, 0, DateTimeKind.Utc),
                EndDate         = new DateTime(2012, 11, 2, 12, 0, 0, DateTimeKind.Utc),
                Comment         = "Old discount"
            };
            var futureDiscount = new DiscountStub(5)
            {
                DiscountPercent = 5,
                StartDate       = new DateTime(2012, 12, 24, 12, 0, 0, DateTimeKind.Utc),
                EndDate         = new DateTime(2012, 12, 25, 12, 0, 0, DateTimeKind.Utc),
                Comment         = "Future discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { oldDiscount, futureDiscount });

            CheckDiscount(cart, 1, "");
        }
        public void TooLowAndTooHighQuantityDiscountDoesNotApply()
        {
            var tooLowDiscount = new DiscountStub(4)
            {
                DiscountPercent = 5,
                StartQuantity   = 1,
                EndQuantity     = 2,
                Comment         = "Too low discount"
            };
            var tooHighDiscount = new DiscountStub(5)
            {
                DiscountPercent = 5,
                StartQuantity   = 7,
                EndQuantity     = 10,
                Comment         = "Too high discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { tooLowDiscount, tooHighDiscount });

            CheckDiscount(cart, 1, "");
        }
        public void LowestPriceWins()
        {
            var mediocreDiscount = new DiscountStub(4)
            {
                DiscountPercent = 5,
                Comment         = "Mediocre discount"
            };
            var betterDiscount = new DiscountStub(5)
            {
                DiscountPercent = 10,
                Comment         = "Better discount"
            };
            var bestDiscount = new DiscountStub(6)
            {
                DiscountPercent = 20,
                Comment         = "Best discount"
            };
            var cart = ShoppingCartHelpers.PrepareCart(new[] { mediocreDiscount, bestDiscount, betterDiscount });

            CheckDiscount(cart, 0.8M, bestDiscount.Comment);
        }
Esempio n. 27
0
        public void RightTaxAppliesToRightCountry()
        {
            var frenchTax     = GetFrenchTax();
            var britishTax    = GetBritishTax();
            var washingtonTax = GetWashingtonTax();
            var oregonTax     = GetOregonTax();
            var taxProvider   = new FakeTaxProvider(new[] { washingtonTax, britishTax, frenchTax, oregonTax });
            var cart          = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });
            var subtotal      = cart.Subtotal();

            cart.Country = frenchTax.Country;
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * frenchTax.Rate));

            cart.Country = britishTax.Country;
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * britishTax.Rate));

            cart.Country = Country.UnitedStates;

            var taxes = cart.Taxes();

            Assert.That(taxes.Name, Is.Null);
            Assert.That(taxes.Amount, Is.EqualTo(0));
        }
Esempio n. 28
0
        public void RightTaxAppliesToRightState()
        {
            var oregonTax     = GetOregonTax();
            var washingtonTax = GetWashingtonTax();
            var taxProvider   = new FakeTaxProvider(new[] { oregonTax, washingtonTax });
            var cart          = ShoppingCartHelpers.PrepareCart(null, new[] { taxProvider });

            cart.Country = Country.UnitedStates;
            var subtotal = cart.Subtotal();

            cart.ZipCode = "98008";
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * washingtonTax.Rate));

            cart.ZipCode = "97218";
            Assert.That(cart.Taxes().Amount, Is.EqualTo(subtotal * oregonTax.Rate));

            cart.ZipCode = "92210";

            var taxes = cart.Taxes();

            Assert.That(taxes.Name, Is.Null);
            Assert.That(taxes.Amount, Is.EqualTo(0));
        }
Esempio n. 29
0
        // GET: Transactions
        public async Task <IActionResult> Index(string id)
        {
            ShoppingCartHelpers shoppingCarHelpers = new ShoppingCartHelpers(_context);

            //get urrent AspNetUser
            var currentUser = await _identityUser.GetUserAsync(User);

            Customer currentCustomer = new Customer();

            //get customer associated with AspNetUserId
            if (currentUser != null)
            {
                currentCustomer = await _context.Customers
                                  .Where(c => c.AspNetUserId == currentUser.Id)
                                  .FirstOrDefaultAsync();
            }

            // Get any open transactions
            var currentTransaction = await _context.Transactions
                                     .Where(t => t.Customer == currentCustomer && t.Completed == false)
                                     .FirstOrDefaultAsync();

            bool isTransactionNew = false;

            //get Tea that was ordered
            string strId   = HttpUtility.HtmlEncode(id);
            var    allTeas = shoppingCarHelpers.GetAllTeas();

            var selectedTea = shoppingCarHelpers.GetTea(strId);

            List <TransactionTab> transactionTabs = new List <TransactionTab>();

            // if no current open transaction, create new transaction
            if (currentTransaction == null)
            {
                //create a new transaction
                var transaction = shoppingCarHelpers.CreateNewTransaction(currentCustomer);
                currentTransaction = transaction;

                isTransactionNew = true;
            }
            else //get past transaction tabs
            {
                transactionTabs = shoppingCarHelpers.GetTransactionTabs(currentTransaction, allTeas);
            }

            //create transaction tab and add it to the db
            var newTransactionTab = shoppingCarHelpers.NewTransactionTab(selectedTea, currentTransaction);

            _context.Add(newTransactionTab[0]);


            if (transactionTabs != null)
            {
                transactionTabs.Add(newTransactionTab[0]);
            }
            else
            {
                transactionTabs = newTransactionTab;
            }

            //calculate Total, Add teas to object, etc...
            currentTransaction = shoppingCarHelpers.TransactionTotal(currentTransaction, transactionTabs);

            if (isTransactionNew == true)
            {
                _context.Add(currentTransaction);
            }
            else
            {
                _context.Update(currentTransaction);
            }

            _context.SaveChanges();

            return(View(currentTransaction));
        }
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = _userService.GetByEmailWithMembership(model.Email);

                if (user != null)
                {
                    if (user.IsAccountConfirmed)
                    {
                        if (!user.IsLockedOut)
                        {
                            if (_userService.IsPasswordMatchForUser(user.UserID, model.Password))
                            {
                                SignIn(user, model.RememberMe);

                                _userService.SuccessfulLogin(user.UserID);

                                _shoppingCartService.MigrateCart(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext), user.Email);

                                ShoppingCartHelpers.SetShoppingCartID(this.ControllerContext, user.Email);

                                _uow.Save();

                                return(RedirectToLocal(returnUrl));
                            }

                            _userService.InvalidPasswordLoginAttempt(user.UserID);

                            if (user.Membership.PasswordFailsSinceLastSuccess >= 5)
                            {
                                _userService.LockAccount(user.UserID, AccountLockReason.InvalidPasswordAttempts);

                                ModelState.AddModelError("", "Due to invalid password attempts your account has been locked for " + (user.Membership.LastPasswordFailureDate.AddMinutes(15) - DateTime.Now).Minutes + " minute(s).");
                            }
                            else
                            {
                                ModelState.AddModelError("", "Invalid password attempt. You have " + (5 - user.Membership.PasswordFailsSinceLastSuccess) + " attempt(s) left before your account is locked for 15 minutes.");
                            }

                            _uow.Save();

                            return(View(model));
                        }
                        else
                        {
                            if (user.AccountLockReason == AccountLockReason.AdministratorRequested)
                            {
                                return(View("AdministratorLockout"));
                            }

                            if (user.AccountLockReason == AccountLockReason.InvalidPasswordAttempts)
                            {
                                var unlockTime = user.Membership.LastPasswordFailureDate.AddMinutes(15);

                                if (unlockTime < DateTime.Now)
                                {
                                    _userService.UnlockAccount(user.UserID);

                                    SignIn(user, model.RememberMe);

                                    _userService.SuccessfulLogin(user.UserID);

                                    _shoppingCartService.MigrateCart(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext), user.UserID.ToString());

                                    ShoppingCartHelpers.SetShoppingCartID(this.ControllerContext, user.UserID.ToString());

                                    _uow.Save();

                                    return(RedirectToLocal(returnUrl));
                                }

                                ModelState.AddModelError("", "Due to invalid password attempts your account has been locked for " + (unlockTime - DateTime.Now).Minutes + " minute(s).");
                            }

                            return(View(model));
                        }
                    }

                    return(View("AccountNotConfirmed"));//, model.Email);
                }

                ModelState.AddModelError("", "Invalid username or password.");
            }

            return(View(model));

            //try
            //{
            //    _shoppingCartService.MigrateCart(ShoppingCartHelpers.GetShoppingCartID(this.ControllerContext), user.UserID.ToString());

            //    _uow.Save();
            //}
            //catch (Exception)
            //{
            //    //Log error, its not really a big deal if the cart items get destroyed in this process
            //    //it shouldnt happen, but such is life.
            //}

            //ShoppingCartHelpers.SetShoppingCartID(this.ControllerContext, user.UserID.ToString());

            //return RedirectToLocal(returnUrl);
        }