Ejemplo n.º 1
0
        public ActionResult CheckoutHeaderCenter()
        {
            try
            {
                var userCookie = CookieManager.GetUserCookie();
                if (userCookie != null)
                {
                    var userEmail = userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL];

                    var cart = services.CartService.GetUserCartItems(userEmail);

                    ViewData["CartCount"] = cart.Sum(ci => ci.Quantity);
                }
                else
                {
                    ViewData["CartCount"] = 0;
                }

                return(PartialView("CheckoutHeaderCenter"));
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                return(null);
            }
        }
Ejemplo n.º 2
0
        public static RemoveCartItemWebFormDTO RemoveCartItem(int cartItemId)
        {
            try
            {
                //get cart item to remove
                var cartItem = services.CartService.GetCartItem(cartItemId);

                //create DTO to be passed to AJAX call
                RemoveCartItemWebFormDTO removeCartItemWebFormDTO = new RemoveCartItemWebFormDTO();
                removeCartItemWebFormDTO.CartItemID = cartItemId;

                //remove cart item from database
                services.CartService.DeleteCartItem(cartItem);

                //get cookie storing user information
                var userCookie = CookieManager.GetUserCookie();

                if (userCookie != null)
                {
                    var userEmail = userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL];

                    //Get cart items of user after cart item is removed
                    var userCartItems = services.CartService.GetUserCartItems(userEmail, Constants.DATABASE_TABLE_PRODUCTS);

                    //set viewmodel properties based on remaining count of items after product is removed from cart
                    if (userCartItems.Any())
                    {
                        int cartItemsCount = userCartItems.Sum(ci => ci.Quantity);

                        removeCartItemWebFormDTO.CartItemsCount = cartItemsCount;
                        removeCartItemWebFormDTO.SubTotal       = string.Format("{0:C}", userCartItems.Sum(ci => ci.Product.Price * ci.Quantity));
                        removeCartItemWebFormDTO.SubTotalLabel  = string.Format("({0} {1})", cartItemsCount, cartItemsCount == 1 ? "item" : "items");
                        removeCartItemWebFormDTO.CartLabel      = string.Format("Cart ({0})", cartItemsCount);
                    }
                    else
                    {
                        removeCartItemWebFormDTO.CartItemsCount = 0;
                        removeCartItemWebFormDTO.SubTotal       = string.Format("{0:C}", 0);
                        removeCartItemWebFormDTO.SubTotalLabel  = string.Format("({0} {1})", 0, "items");
                        removeCartItemWebFormDTO.CartLabel      = string.Format("Cart ({0})", 0);
                    }

                    //update cookie after user interacts with cart
                    CookieManager.SetUserCookie(userEmail, userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_FIRSTNAME]);

                    //return JSON object to be used for AJAX
                    return(removeCartItemWebFormDTO);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(HttpContext.Current.Request.PhysicalPath));
                HttpContext.Current.Server.Transfer(Constants.PAGE_GENERIC_ERROR);
                return(null);
            }
        }
Ejemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //get user storing user information
                    var userCookie = CookieManager.GetUserCookie();

                    if (userCookie != null)
                    {
                        //email stored in cookie
                        var userEmail = userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL];

                        //get cart items of user
                        var cartItems = services.CartService.GetUserCartItems(userEmail, Constants.DATABASE_TABLE_PRODUCTS);

                        //count of cart items (sum of quantities of all cart items)
                        var cartItemsCount = cartItems.Sum(cartItem => cartItem.Quantity);

                        //set cart item count label
                        cartItemsCountLabel.Text = string.Format("({0} {1}):", cartItemsCount, cartItemsCount == 1 ? "item" : "items");

                        //set subtotal info
                        subTotalLabel.Text = string.Format("{0:c}", cartItems.Sum(ci => ci.Product.Price * ci.Quantity));
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                Server.Transfer(Constants.PAGE_GENERIC_ERROR);
            }
        }
Ejemplo n.º 4
0
        protected void quantityDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //get dropdown of cart item sent to this event handler
                var dropDownList = (DropDownList)sender;

                //get repeater row of dropdown
                var repeaterRow = dropDownList.NamingContainer;

                //get product id from hidden field of cart item
                var productIdHiddenField = repeaterRow.FindControl("productIdHiddenField") as HiddenField;

                //get cart item from database
                var cartItem = services.CartService.GetCartItem(int.Parse(productIdHiddenField.Value));

                //set cart item quantity to quantity selected by user
                cartItem.Quantity = int.Parse(dropDownList.SelectedValue);

                //update cart item in database
                services.CartService.UpdateCartItem(cartItem);

                //get cookie storing user email
                var userCookie = CookieManager.GetUserCookie();

                if (userCookie != null)
                {
                    //get cart items after cart item quantity is updated
                    var userCartItems  = services.CartService.GetUserCartItems(userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL], Constants.DATABASE_TABLE_PRODUCTS);
                    var cartItemsCount = userCartItems.Sum(ci => ci.Quantity);

                    //update subtotal based on selected quantity
                    lblCartItemCount.Text = string.Format("({0} {1})", cartItemsCount, cartItemsCount == 1 ? "item" : "items");
                    subTotalTd.InnerText  = string.Format("{0:C}", userCartItems.Sum(ci => ci.Product.Price * ci.Quantity));

                    //update cart link text on top right of page
                    ((LinkButton)this.Master.FindControl("cartLinkButton")).Text = string.Format("Cart ({0})", userCartItems.Sum(ci => ci.Quantity));

                    //update cookie storing user information
                    CookieManager.SetUserCookie(userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL], userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_FIRSTNAME]);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                Server.Transfer(Constants.PAGE_GENERIC_ERROR);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Display checkout page with cart information
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderInfo()
        {
            try
            {
                //get
                var userCookie = CookieManager.GetUserCookie();

                //ensure that a user is logged in before an order is placed
                if (userCookie == null || !Regex.IsMatch(userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL].ToString(), Constants.REGEX_PATTERN_EMAIL))
                {
                    return(RedirectToAction("Login", "Account", new { returnUrl = Request.Url.PathAndQuery }));
                }

                //use email stored in cookie to create new CheckoutViewModel instance and pass it into view
                return(View(GetNewCheckoutViewModel(userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL])));
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                return(RedirectToAction(Constants.CONTROLLER_ERROR, Constants.CONTROLLER_ACTION_INDEX));
            }
        }
Ejemplo n.º 6
0
        public ActionResult OrderInfo(CheckoutViewModel checkoutViewModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var userCookie = CookieManager.GetUserCookie();

                    var userEmail = userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL];

                    //SmartyStreets address validation
                    #region SmartyStreets Address Validation
                    var client = new ClientBuilder(Constants.SMARTY_STREETS_AUTHENICATION_ID, Constants.SMARTY_STREETS_AUTHENICATION_TOKEN).BuildUsStreetApiClient();

                    var lookup = new Lookup
                    {
                        Street  = string.IsNullOrWhiteSpace(checkoutViewModel.AptSuiteEtc) ? checkoutViewModel.Address : string.Format("{0} {1}", checkoutViewModel.Address, checkoutViewModel.AptSuiteEtc),
                        City    = checkoutViewModel.City,
                        State   = checkoutViewModel.State,
                        ZipCode = checkoutViewModel.ZipCode
                    };

                    client.Send(lookup);

                    var candidates = lookup.Result;

                    if (candidates.Count == 0)
                    {
                        ModelState.AddModelError("addessError", "Invalid address");
                        return(View(checkoutViewModel));
                    }
                    #endregion

                    var candidateReturnFromAddressValidation = candidates[0];

                    //create order using model information
                    Order order = new Order();
                    order.Email     = userEmail;
                    order.FirstName = checkoutViewModel.FirstName;
                    order.LastName  = checkoutViewModel.LastName;
                    order.Address   = candidateReturnFromAddressValidation.DeliveryLine1;
                    order.City      = candidateReturnFromAddressValidation.Components.CityName;
                    order.State     = candidateReturnFromAddressValidation.Components.State;
                    order.ZipCode   = candidateReturnFromAddressValidation.LastLine.Split(' ')[2]; //Zip code returned from SmartyStreets address validation

                    var userCartItems = services.CartService.GetUserCartItems(userEmail, Constants.DATABASE_TABLE_PRODUCTS);
                    order.SubTotal = Math.Round(userCartItems.Sum(ci => ci.Product.Price * ci.Quantity), 2);

                    order.ShippingOptionID = checkoutViewModel.ShippingOptionID;
                    var shippingOption = services.ShippingService.GetShippingOption(checkoutViewModel.ShippingOptionID);

                    //calculate sales tax and order total based on whether or not intital selected shipping option is free
                    if (shippingOption.Price.HasValue)
                    {
                        order.SalesTax = Math.Round((order.SubTotal + shippingOption.Price.Value) * (decimal).07, 2);
                        order.Total    = order.SubTotal + order.SalesTax.Value + shippingOption.Price.Value;
                    }
                    else
                    {
                        order.SalesTax = Math.Round(order.SubTotal * (decimal).07, 2);
                        order.Total    = order.SubTotal + order.SalesTax.Value;
                    }

                    order.OrderDate = DateTime.Now;
                    services.OrderService.AddOrder(order);

                    foreach (var cartItem in userCartItems)
                    {
                        //create order detail, relating to newly created order, of cart item
                        OrderDetail orderDetail = new OrderDetail();
                        orderDetail.OrderID      = order.OrderID;
                        orderDetail.ProductID    = cartItem.ProductID;
                        orderDetail.ProductPrice = cartItem.Product.Price;
                        orderDetail.Quantity     = cartItem.Quantity;

                        //add order detail to database
                        services.OrderDetailService.AddOrderDetail(orderDetail);

                        //remove cart items from database once order detail for cart items is created
                        services.CartService.DeleteCartItem(cartItem);
                    }

                    //set properties of order confirmation dto
                    OrderConfirmationDTO orderConfirmationDto = new OrderConfirmationDTO();
                    orderConfirmationDto.Candidate            = candidateReturnFromAddressValidation;
                    orderConfirmationDto.FirstName            = checkoutViewModel.FirstName;
                    orderConfirmationDto.LastName             = checkoutViewModel.LastName;
                    orderConfirmationDto.OrderDate            = DateTime.Now;
                    orderConfirmationDto.CartItems            = userCartItems;
                    orderConfirmationDto.ShippingOptionID     = shippingOption.ShippingOptionID;
                    orderConfirmationDto.ShippingOptionName   = shippingOption.Name;
                    orderConfirmationDto.ShippingPrice        = shippingOption.Price;
                    orderConfirmationDto.ExpectedDeliveryDays = shippingOption.ExpectedDeliveryDays;

                    //redirect to order confirmation view
                    return(View("OrderConfirmation", orderConfirmationDto));
                }
                else //re-display page with validation errors
                {
                    var userCookie = CookieManager.GetUserCookie();

                    //use email stored in cookie to create new CheckoutViewModel instance and pass it into view
                    return(View(GetNewCheckoutViewModel(userCookie[Constants.COOKIE_KEY_USER_SUB_KEY_USER_EMAIL])));
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                return(RedirectToAction(Constants.CONTROLLER_ACTION_INDEX, Constants.CONTROLLER_ERROR));
            }
        }