public IActionResult Checkout(int id) { var totalPrice = cartsService.GetAllItemsInCart(id).Sum(i => i.Product.Price * i.Quantity); var model = new ShoppingCartCheckoutViewModel() { ShoppingCartId = id, Username = this.User.Identity.Name, TotalPrice = Math.Round(totalPrice, 2) }; return(View(model)); }
public IActionResult Checkout() { List <ShoppingCartItem> shoppingCart = retrieveCartFromSession(); ViewBag.CartHasItems = shoppingCart.Count() > 0 ? true : false; ViewBag.LoggedIn = false; ShoppingCartCheckoutViewModel VM = new ShoppingCartCheckoutViewModel { TotalPrice = calculateTotalPrice(shoppingCart, 1, false), PriceMinusDelivery = calculateTotalPrice(shoppingCart, 1, true), shoppingCartItems = shoppingCart }; if (User.Identity.IsAuthenticated) { string UserName = User.Identity.Name; ApplicationUser user = _userManager.Users.FirstOrDefault(x => x.UserName == UserName); ViewBag.LoggedIn = true; ViewBag.UserHasAddress = true; IEnumerable <Address> userAddresses = _addressService.Query(x => x.ApplicationUserId == user.Id); if (userAddresses.Count() < 1) { ViewBag.UserHasAddress = false; } else if (User.IsInRole("Admin")) { Address preferredAddress = userAddresses.FirstOrDefault(); VM.PreferredAddress = preferredAddress; // Set current address to session: var serialisedAddress = JsonConvert.SerializeObject(preferredAddress); HttpContext.Session.SetString(userAddress, serialisedAddress); } else { Address preferredAddress = userAddresses.Where(y => y.PreferredShippingAddress).FirstOrDefault(); VM.PreferredAddress = preferredAddress; // Set current address to session: var serialisedAddress = JsonConvert.SerializeObject(preferredAddress); HttpContext.Session.SetString(userAddress, serialisedAddress); } } return(View(VM)); }
public StandardJsonResult GetShippingMethods(ShoppingCartCheckoutViewModel model) { var result = new List <ShoppingCartShippingMethodsViewModel>(); AddressViewModel address = model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress; // Find zone for country and region (if supplied) ShippingZone zone = shippingService.FindZone(address.CountryCode, address.RegionId); if (zone != null) { List <ShippingMethod> methods = shippingService.FindMethods(zone.Id).ToList(); foreach (ShippingMethod method in methods) { decimal?cost = shippingService.CalculateShipping(method, model.ShoppingCartItems.Sum(i => i.Quantity), model.ShoppingCartItems.Sum(i => i.Quantity * db.Products.Find(i.ProductId).Weight), model.ShoppingCartItems.Sum(i => i.Quantity * i.ItemPrice), Mapper.Map <Address>(address)); if (!cost.HasValue) { continue; } var methodView = new ShoppingCartShippingMethodsViewModel { Id = method.Id, Name = method.Name, Amount = cost.Value }; result.Add(methodView); } } return(JsonSuccess(result.OrderBy(s => s.Amount))); }
public ActionResult Checkout(ShoppingCartCheckoutViewModel model) { if (!ModelState.IsValid) { return(JsonValidationError()); } // Get cart contents ShoppingCart cart = GetOrCreateCart(); if (!cart.ShoppingCartItems.Any()) { return(JsonError("Your shopping cart is empty!")); } // Check quantity foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems) { Product product = db.Products.Find(cartItem.ProductId); int? qty = null; if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Quantity.HasValue) { qty = cartItem.ProductSku.Quantity.Value; } if (qty == null && product.Quantity.HasValue) { qty = product.Quantity.Value; } if (qty.HasValue && qty < cartItem.Quantity) { return(JsonError(string.Format("The requested quantity for \"{0}\" is not available", product.Name))); } } // Get current user (or create a new one) User user = null; if (User.Identity.IsAuthenticated) { user = customerService.Find(currentUser.User.Id); } if (user == null) { var userModel = new CustomerViewModel { FirstName = model.BillingAddress.FirstName, LastName = model.BillingAddress.LastName, Company = model.BillingAddress.Company, PhoneNumber = model.BillingAddress.Phone, Email = model.Email }; try { user = customerService.AddOrUpdate(userModel); } catch (ArgumentException err) { return(JsonError(err.Message)); } customerService.LoginUser(HttpContext, user); } // Get addresses var billingAddress = Mapper.Map <Address>(model.BillingAddress); billingAddress.Type = AddressType.Billing; var shippingAddress = Mapper.Map <Address>(model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress); shippingAddress.Type = AddressType.Shipping; var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing); if (defaultBillingAddress == null) { // Add default billing address defaultBillingAddress = Mapper.Map <Address>(model.BillingAddress); defaultBillingAddress.Type = AddressType.Billing; defaultBillingAddress.IsPrimary = true; user.Addresses.Add(defaultBillingAddress); } var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping); if (defaultShippingAddress == null) { // Add default shipping address defaultShippingAddress = Mapper.Map <Address>(model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress); defaultShippingAddress.Type = AddressType.Shipping; defaultShippingAddress.IsPrimary = true; user.Addresses.Add(defaultShippingAddress); } db.SaveChanges(); // Create order var order = new Order { UserId = user.Id, BillingAddress = billingAddress, ShippingAddress = shippingAddress, DatePlaced = DateTime.Now, DateUpdated = DateTime.Now, IPAddress = Request.UserHostAddress, UserComments = model.UserComments, Status = OrderStatus.AwaitingPayment }; db.Orders.Add(order); TaxZone taxZone = taxZoneService.Find(billingAddress.CountryCode, billingAddress.RegionId); foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems) { Product product = db.Products.Find(cartItem.ProductId); ProductSku productSku = cartItem.ProductSku; if (productSku != null && productSku.Quantity.HasValue) { productSkuService.RemoveQuantity(productSku.Id, cartItem.Quantity); } else if (product.Quantity.HasValue) { productService.RemoveQuantity(product.Id, cartItem.Quantity); } decimal price = product.SalePrice ?? product.Price; if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Price.HasValue) { price = cartItem.ProductSku.Price.Value; } var cartItemOptions = JsonConvert.DeserializeObject <ShoppingCartItemOptionViewModel[]>(cartItem.Options); var orderItemOptions = Mapper.Map <OrderItemOption[]>(cartItemOptions); var orderItem = new OrderItem { Order = order, ProductId = product.Id, ProductSkuId = cartItem.ProductSkuId, Quantity = cartItem.Quantity, Options = JsonConvert.SerializeObject(orderItemOptions), ItemPrice = price }; db.OrderItems.Add(orderItem); order.Subtotal += cartItem.Quantity * price; if (taxZone != null) { order.TaxAmount += taxRateService.CalculateTax(taxZone.Id, product.TaxClassId, price * cartItem.Quantity); } } ShippingMethod shippingMethod = db.ShippingMethods.Find(model.ShippingMethodId); order.ShippingAmount = shippingService.CalculateShipping(shippingMethod, cart.ShoppingCartItems.Sum(i => i.Quantity), cart.ShoppingCartItems.Sum(i => i.Quantity * i.Product.Weight), order.Subtotal, shippingAddress).GetValueOrDefault(); order.Total = order.Subtotal + order.ShippingAmount; if (!settings.Get <bool>(SettingField.TaxIncludedInPrices)) { order.Total += order.TaxAmount; } db.SaveChanges(); return(JsonSuccess(new { orderId = order.Id, paymentMethodId = model.PaymentMethodId })); }
public StandardJsonResult GetShippingMethods(ShoppingCartCheckoutViewModel model) { var result = new List<ShoppingCartShippingMethodsViewModel>(); AddressViewModel address = model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress; // Find zone for country and region (if supplied) ShippingZone zone = shippingService.FindZone(address.CountryCode, address.RegionId); if (zone != null) { List<ShippingMethod> methods = shippingService.FindMethods(zone.Id).ToList(); foreach (ShippingMethod method in methods) { decimal? cost = shippingService.CalculateShipping(method, model.ShoppingCartItems.Sum(i => i.Quantity), model.ShoppingCartItems.Sum(i => i.Quantity*db.Products.Find(i.ProductId).Weight), model.ShoppingCartItems.Sum(i => i.Quantity*i.ItemPrice), Mapper.Map<Address>(address)); if (!cost.HasValue) continue; var methodView = new ShoppingCartShippingMethodsViewModel { Id = method.Id, Name = method.Name, Amount = cost.Value }; result.Add(methodView); } } return JsonSuccess(result.OrderBy(s => s.Amount)); }
public ActionResult Checkout(ShoppingCartCheckoutViewModel model) { if (!ModelState.IsValid) return JsonValidationError(); // Get cart contents ShoppingCart cart = GetOrCreateCart(); if (!cart.ShoppingCartItems.Any()) { return JsonError("Your shopping cart is empty!"); } // Check quantity foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems) { Product product = db.Products.Find(cartItem.ProductId); int? qty = null; if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Quantity.HasValue) qty = cartItem.ProductSku.Quantity.Value; if (qty == null && product.Quantity.HasValue) qty = product.Quantity.Value; if (qty.HasValue && qty < cartItem.Quantity) { return JsonError(string.Format("The requested quantity for \"{0}\" is not available", product.Name)); } } // Get current user (or create a new one) User user = null; if (User.Identity.IsAuthenticated) { user = customerService.Find(currentUser.User.Id); } if (user == null) { var userModel = new CustomerViewModel { FirstName = model.BillingAddress.FirstName, LastName = model.BillingAddress.LastName, Company = model.BillingAddress.Company, PhoneNumber = model.BillingAddress.Phone, Email = model.Email }; try { user = customerService.AddOrUpdate(userModel); } catch (ArgumentException err) { return JsonError(err.Message); } customerService.LoginUser(HttpContext, user); } // Get addresses var billingAddress = Mapper.Map<Address>(model.BillingAddress); billingAddress.Type = AddressType.Billing; var shippingAddress = Mapper.Map<Address>(model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress); shippingAddress.Type = AddressType.Shipping; var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing); if (defaultBillingAddress == null) { // Add default billing address defaultBillingAddress = Mapper.Map<Address>(model.BillingAddress); defaultBillingAddress.Type = AddressType.Billing; defaultBillingAddress.IsPrimary = true; user.Addresses.Add(defaultBillingAddress); } var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping); if (defaultShippingAddress == null) { // Add default shipping address defaultShippingAddress = Mapper.Map<Address>(model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress); defaultShippingAddress.Type = AddressType.Shipping; defaultShippingAddress.IsPrimary = true; user.Addresses.Add(defaultShippingAddress); } db.SaveChanges(); // Create order var order = new Order { UserId = user.Id, BillingAddress = billingAddress, ShippingAddress = shippingAddress, DatePlaced = DateTime.Now, DateUpdated = DateTime.Now, IPAddress = Request.UserHostAddress, UserComments = model.UserComments, Status = OrderStatus.AwaitingPayment }; db.Orders.Add(order); TaxZone taxZone = taxZoneService.Find(billingAddress.CountryCode, billingAddress.RegionId); foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems) { Product product = db.Products.Find(cartItem.ProductId); ProductSku productSku = cartItem.ProductSku; if (productSku != null && productSku.Quantity.HasValue) { productSkuService.RemoveQuantity(productSku.Id, cartItem.Quantity); } else if (product.Quantity.HasValue) { productService.RemoveQuantity(product.Id, cartItem.Quantity); } decimal price = product.SalePrice ?? product.Price; if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Price.HasValue) price = cartItem.ProductSku.Price.Value; var cartItemOptions = JsonConvert.DeserializeObject<ShoppingCartItemOptionViewModel[]>(cartItem.Options); var orderItemOptions = Mapper.Map<OrderItemOption[]>(cartItemOptions); var orderItem = new OrderItem { Order = order, ProductId = product.Id, ProductSkuId = cartItem.ProductSkuId, Quantity = cartItem.Quantity, Options = JsonConvert.SerializeObject(orderItemOptions), ItemPrice = price }; db.OrderItems.Add(orderItem); order.Subtotal += cartItem.Quantity * price; if (taxZone != null) order.TaxAmount += taxRateService.CalculateTax(taxZone.Id, product.TaxClassId, price * cartItem.Quantity); } ShippingMethod shippingMethod = db.ShippingMethods.Find(model.ShippingMethodId); order.ShippingAmount = shippingService.CalculateShipping(shippingMethod, cart.ShoppingCartItems.Sum(i => i.Quantity), cart.ShoppingCartItems.Sum(i => i.Quantity*i.Product.Weight), order.Subtotal, shippingAddress).GetValueOrDefault(); order.Total = order.Subtotal + order.ShippingAmount; if (!settings.Get<bool>(SettingField.TaxIncludedInPrices)) order.Total += order.TaxAmount; db.SaveChanges(); return JsonSuccess(new {orderId = order.Id, paymentMethodId = model.PaymentMethodId}); }
public IActionResult CheckoutSuccesful(ShoppingCartCheckoutViewModel VM) { if (ModelState.IsValid) { if (retrieveCartFromSession().Count() > 0) { Guid orderId = new Guid(); Order currentOrder = new Order(); currentOrder.OrderId = orderId; List <ShoppingCartItem> shoppingCartItems = retrieveCartFromSession(); List <LineItem> orderItems = new List <LineItem>(); foreach (ShoppingCartItem item in shoppingCartItems) { LineItem orderItem = new LineItem { OrderId = orderId, HamperId = item.Hamper.HamperId, Quantity = item.Quantity }; orderItems.Add(orderItem); } // Add ListItems to order: currentOrder.ShoppingCartItems = orderItems; //Retrieve user's address from session (if logged in): if (User.Identity.IsAuthenticated) { // Add User ID: string UserName = User.Identity.Name; ApplicationUser user = _userManager.Users.FirstOrDefault(x => x.UserName == UserName); currentOrder.UserId = user.Id; // Retrieve address from session: var addressInSession = HttpContext.Session.GetString(userAddress); Address shippingAddress = JsonConvert.DeserializeObject <Address>(addressInSession); // Add address details to order: currentOrder.StreetAddress = shippingAddress.StreetAddress; currentOrder.Suburb = shippingAddress.Suburb; currentOrder.State = shippingAddress.State; currentOrder.Postcode = shippingAddress.Postcode; } else { // Add [No User] ID: currentOrder.UserId = null; // Add address details to order directly from VM: currentOrder.StreetAddress = VM.PreferredAddress.StreetAddress; currentOrder.Suburb = VM.PreferredAddress.Suburb; currentOrder.State = VM.PreferredAddress.State; currentOrder.Postcode = VM.PreferredAddress.Postcode; } // Update order price: currentOrder.Price = calculateTotalPrice(shoppingCartItems, 1, true); // Add current date: currentOrder.DateOrdered = DateTime.Now; // Update order in DB: _orderService.Create(currentOrder); // Update list items in DB: _lineItemService.UpdateMultiple(orderItems); // Clear session: HttpContext.Session.Clear(); return(RedirectToAction("OrderProcessedSuccessfully", "Order")); } else { return(RedirectToAction("ViewCart", "ShoppingCart")); } } return(View(VM)); }