private bool SaveCart(SessionCart tempCart, CartSummary summary, int userId, string transactionId, CartType cartType) { try { Cart cart = new Cart { TransactionDate = DateTime.Now, TransactionId = transactionId, UserId = userId, CartType = cartType, CartItems = new List <CartItem>(), TotalCost = summary.TotalCost }; _repository.Carts.Create(cart); _repository.SaveChanges(); foreach (var summaryItem in summary.CartItems) { CartItem newItem = new CartItem { CartId = cart.CartId, PurchaseItemId = summaryItem.PurchaseItemId, Cost = summaryItem.ItemCost, Total = summaryItem.ItemTotal, StandAloneItem = summaryItem.ProcessType == ProcessType.Individual ? true : false, LocalTaxPercentage = summaryItem.LocalTaxPercentage, LocalTaxValue = summaryItem.LocalTax, StateTaxPercentage = summaryItem.StateTaxPercentage, StateTaxValue = summaryItem.StateTax, DiscountItemId = summaryItem.DiscountItemId, DiscountValue = summaryItem.DiscountValue, DiscountType = summaryItem.DiscountType, DiscountValueTotal = summaryItem.DiscountTotal }; cart.CartItems.Add(newItem); _repository.SaveChanges(); if (summaryItem.SessionKey.HasValue && tempCart.ActionItems[summaryItem.SessionKey.Value].ActionObject != null) { ActionItem action = tempCart.ActionItems[summaryItem.SessionKey.Value]; int? discountId = summaryItem.DiscountItemId; CompleteActions(action, newItem.CartItemId, discountId, transactionId); } } IEmailService emailService = new EmailService(); emailService.SendPaymentConfirmationEmail(cart.CartId); tempCart.ResultingConfirmationCode = cart.TransactionId; return(true); } catch (Exception ex) { return(false); } }
private IGatewayResponse ChargeConsumer(CartCheckOut checkOutDetails, CartSummary cartSummary) { var paymentRequest = new AuthorizationRequest(checkOutDetails.CardNumber, string.Format("{0}{1}", checkOutDetails.ExpirationMonth, checkOutDetails.ExpirationYear), cartSummary.TotalCost, "Dirty Girl Cart Purchase", true); paymentRequest.FirstName = checkOutDetails.CardHolderFirstname; paymentRequest.LastName = checkOutDetails.CardHolderLastname; paymentRequest.Zip = checkOutDetails.CardHolderZipCode; paymentRequest.CardCode = checkOutDetails.CCVNumber; var totalTax = 0.0M; foreach (var item in cartSummary.CartItems) { paymentRequest.AddLineItem(item.PurchaseItemId.ToString(), item.ItemName, item.DiscountDescription, 1, item.ItemTotal, item.Taxable); if (item.Taxable) { totalTax += (item.StateTax + item.LocalTax); } } paymentRequest.AddTax(totalTax); var gateway = new Gateway(DirtyGirlServiceConfig.Settings.PaymentGatewayId, DirtyGirlServiceConfig.Settings.PaymentGatewayKey, true); gateway.TestMode = DirtyGirlServiceConfig.Settings.PaymentTestMode; return(gateway.Send(paymentRequest)); }
public IActionResult Load(string rules, string productObj) { try { List <CartSummary> cartSummary = new List <CartSummary>(); List <int> ids = JsonConvert.DeserializeObject <List <int> >(rules); List <Product> products = JsonConvert.DeserializeObject <List <Product> >(productObj); foreach (Product product in products) { CartSummary cart = new CartSummary(); cart.ProductId = product.ProductId; cart.Title = product.Title; cart.Qty = product.Qty; cart.TotalPrice = product.Qty * product.UnitPrice; cart.DiscountedPrice = _productService.GetDiscountedPrice(product, products, ids.Count > 0? ids : null); cartSummary.Add(cart); } ProductVM productList = new ProductVM(); productList.CartSummary = cartSummary; return(PartialView("_CartSummary", productList)); } catch (Exception ex) { _logger.LogError(ex.InnerException.ToString()); return(null); } }
public ActionResult RemoveFromCart(int id = 0) { int servicePercent = 0; int vatpercent = 0; decimal subtotal = 0; decimal service = 0; decimal vat = 0; decimal deliverycharge = 0; decimal gtotal = 0; bool isRemoved = false; var cart = new Cart(); Restaurant restaurant = (Restaurant)Session["Restaurant"]; if (restaurant.IsServiceChargeApplicable == true) { servicePercent = Convert.ToInt32(restaurant.ServiceChargePercent); } if (restaurant.IsVatApplicable == true) { vatpercent = Convert.ToInt32(restaurant.VATPercent); } CartDetail od = new CartDetail(); cart = (Cart)Session["Cart"]; List <CartDetail> listorderdetail = cart.cartDetail; CartSummary cartsummary = cart.cartSummary; //Order order = cart.Orders; foreach (CartDetail c in listorderdetail) { if (c.FoodItemId == id) { listorderdetail.Remove(c); break; } } foreach (var c in listorderdetail) { subtotal = subtotal + c.Rate * c.Quantity; } cartsummary.SubTotal = subtotal; service = (subtotal) * servicePercent / 100; cartsummary.ServiceCharge = service; vat = (service + subtotal) * vatpercent / 100; cartsummary.VAT = vat; cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; cart.cartSummary = cartsummary; cartsummary.ServiceChargePercent = servicePercent; cartsummary.VATPercent = vatpercent; cart.cartSummary = cartsummary; Session["Cart"] = cart; isRemoved = false; ViewBag.message = "Removed"; return(RedirectToAction("Index", new { message = ViewData["message"] })); }
protected void Page_PreRender(object sender, EventArgs e) { // UPDATE CART DISPLAY JUST BEFORE PAGE RENDER, TO ENSUER ALL CHANGES ARE REFLECTED CartSummary.DataSource = GetBasketItems(); CartSummary.DataBind(); InitializeBasketContents(); GiftOptionsPopup.CancelControlID = phGiftOptions.Visible ? CancelGiftOptionsButton.ClientID : DummyCancelLink.ClientID; }
// remove all the processing fees from this cart... private void RemoveProcessingFee(CartSummary cartSummary) { var fees = cartSummary.CartItems.Where( item => item.PurchaseType == PurchaseType.Fee && item.ItemName == PROCESSING_FEE).ToList(); foreach (var item in fees) { cartSummary.CartItems.Remove(item); } }
private void ApplySpecials(CartSummary cartSummary) { //Apply upsale: if there is more than one registration give half off to the lowest registration var regList = cartSummary.CartItems.Where(x => x.PurchaseType == PurchaseType.Registration && x.ItemCost > 0).OrderBy(x => x.ItemCost).ToList(); if (regList.Count > 1) { regList[0].ItemCost = regList[0].ItemCost / 2; regList[0].ItemDescription += " including upsale."; } }
public static bool IsCurrentApplicationOwner(this CartSummary cartSummary) { //For now this is an only way to identify if website user owns draft or not //We use possible owner names we investigated, which can be used in AuthToken, but it can be configured in app settings if (cartSummary == null) { return(false); } if (!cartSummary.PropertyBag.TryGetValue(Constants.OrderDraft.OwnershipPropertyBagKey, out object orderDraftOwnershipUserName)) { return(false); } var applicationNames = ConfigurationManager.AppSettings["ApplicationNames"] ?? string.Empty; return(applicationNames.ToLower().Split(',').Contains(orderDraftOwnershipUserName?.ToString().ToLower())); }
public CartSummary GenerateCartSummary(SessionCart currentCart) { CartSummary cartSummary = new CartSummary { CartItems = GenerateLineItems(currentCart), SummaryMessages = new List <string>() }; ApplySpecials(cartSummary); if (!string.IsNullOrEmpty(currentCart.DiscountCode)) { if (!ApplyDiscount(cartSummary, currentCart)) { currentCart.DiscountCode = string.Empty; } } return(cartSummary); }
public CartSummaryValidation(CartSummary cartSummary) => this.cartSummary = cartSummary;
protected void ContinueButton_Click(object sender, EventArgs e) { BasketItem basketItem = BasketItemDataSource.Load(AlwaysConvert.ToInt(GiftOptionsBasketItemId.Value)); // LOOP EACH ITEM ROW TO DETERMINE GIFT OPTIONS List <BasketItemGiftOption> giftOptions = new List <BasketItemGiftOption>(); foreach (GridViewRow row in GiftItemsGrid.Rows) { GiftWrapChoices wrapOptions = (GiftWrapChoices)row.FindControl("GiftWrapChoices"); wrapOptions.BasketItemId = basketItem.Id; int wrapStyleId = wrapOptions.WrapStyleId; string giftMessage = wrapOptions.GiftMessage; BasketItemGiftOption optionItem = new BasketItemGiftOption(basketItem, wrapStyleId, giftMessage); int existingIndex = giftOptions.IndexOf(optionItem); if (existingIndex > -1) { giftOptions[existingIndex].Quantity++; } else { giftOptions.Add(optionItem); } } // LOOP THROUGH GIFT OPTIONS AND UPDATE BASKET ITEMS Basket basket = AbleContext.Current.User.Basket; for (int i = 0; i < giftOptions.Count; i++) { BasketItemGiftOption giftOptionItem = giftOptions[i]; if (i == 0) { // FOR FIRST GIFT OPTION, UPDATE THE ORIGINAL BASKET ITEM basketItem.Quantity = giftOptionItem.Quantity; basketItem.WrapStyleId = giftOptionItem.WrapStyleId; basketItem.GiftMessage = giftOptionItem.GiftMessage; } else { // FOR ADDTIONAL GIFT OPTIONS, CREATE COPIES OF THE ORIGINAL BASKET ITEM BasketItem newItem = basketItem.Copy(); newItem.Quantity = giftOptionItem.Quantity; newItem.GiftMessage = giftOptionItem.GiftMessage; newItem.WrapStyleId = giftOptionItem.WrapStyleId; basket.Items.Add(newItem); } } // SAVE, COMBINE basket.Save(); IBasketService basketService = AbleContext.Resolve <IBasketService>(); basketService.Combine(basket); CartSummary.DataSource = GetBasketItems(); CartSummary.DataBind(); // NOW HIDE THE POPUP phGiftOptions.Visible = false; GiftOptionsPopup.Hide(); }
private bool ApplyDiscount(CartSummary cartSummary, SessionCart currentCart) { DiscountItem discount = _repository.DiscountItems.Find(x => x.Code.ToLower() == currentCart.DiscountCode.ToLower()); if (discount != null) { if (cartSummary.TotalCost == 0) { discount = null; currentCart.DiscountCode = null; cartSummary.SummaryMessages.Add("You cannot apply a discount code to this cart. There are no charges."); } if (discount is RedemptionCode) { var discountableRegList = cartSummary.CartItems.Where(x => x.PurchaseType == PurchaseType.Registration && x.Discountable == true).OrderByDescending(x => x.ItemCost).ToList(); if (discountableRegList.Count() > 0) { RedemptionCode code = (RedemptionCode)discount; IDiscountService discountService = new DiscountService(this._repository, false); ServiceResult validationResult = discountService.ValidateDiscount(code); if (validationResult.Success) { var cost = discountableRegList[0].ItemCost; var discountValue = code.DiscountType == DiscountType.Dollars ? code.Value : cost * (code.Value / 100); discountableRegList[0].DiscountItemId = code.DiscountItemId; discountableRegList[0].DiscountDescription = code.Code; discountableRegList[0].DiscountType = code.DiscountType; discountableRegList[0].DiscountValue = discountableRegList[0].ItemTotal <= 0 ? cost : discountValue; if (NeedToRemoveProcessingFee(currentCart, code)) { RemoveProcessingFee(cartSummary); } } else { cartSummary.SummaryMessages.Add(validationResult.GetServiceErrors().First().ErrorMessage); } } else { cartSummary.SummaryMessages.Add("There are no applicable items for this discount."); } } if (discount is Coupon) { Coupon coupon = (Coupon)discount; IDiscountService discountService = new DiscountService(this._repository, false); ServiceResult validationResult = discountService.ValidateDiscount(coupon); if (validationResult.Success) { switch (coupon.CouponType) { case CouponType.Registration: var discountableRegList = cartSummary.CartItems.Where( x => x.PurchaseType == PurchaseType.Registration && x.Discountable == true && x.EventId == ((coupon.EventId.HasValue) ? coupon.EventId.Value : x.EventId)).OrderByDescending(x => x.ItemCost).ToList(); if (discountableRegList.Any()) { var cost = discountableRegList[0].ItemCost; var discountValue = coupon.DiscountType == DiscountType.Dollars ? coupon.Value : cost * (coupon.Value / 100); var discountedCost = cost - discountValue; discountableRegList[0].DiscountItemId = coupon.DiscountItemId; discountableRegList[0].DiscountDescription = coupon.Code; discountableRegList[0].DiscountType = coupon.DiscountType; discountableRegList[0].DiscountValue = discountableRegList[0].ItemTotal <= 0 ? cost : discountValue; if (NeedToRemoveProcessingFee(currentCart, coupon)) { RemoveProcessingFee(cartSummary); } } else { cartSummary.SummaryMessages.Add("There are no applicable items for this discount."); } break; } } else { cartSummary.SummaryMessages.Add(validationResult.GetServiceErrors().First().ErrorMessage); } } } else { cartSummary.SummaryMessages.Add("This discount does not exist."); } return(cartSummary.SummaryMessages.Count <= 0); }
public ServiceResult ProcessCart(CartCheckOut checkOutDetails, SessionCart tempCart, int userId) { ServiceResult result = new ServiceResult(); if (checkOutDetails != null && checkOutDetails.CartSummary != null && checkOutDetails.CartSummary.TotalCost > 0) { DateTime expired = new DateTime(); expired.AddYears(checkOutDetails.ExpirationYear); expired.AddMonths(checkOutDetails.ExpirationMonth); if (DateTime.Now.CompareTo(expired) < 0) { result.AddServiceError("This credit card is expired"); } Regex rg = new Regex(@"^[a-zA-Z].*$"); if (string.IsNullOrWhiteSpace(checkOutDetails.CardHolderFirstname)) { result.AddServiceError("Cardholder first name is required."); } else if (!rg.IsMatch(checkOutDetails.CardHolderFirstname)) { result.AddServiceError("Cardholder first name is invalid."); } if (string.IsNullOrWhiteSpace(checkOutDetails.CardHolderLastname)) { result.AddServiceError("Cardholder last name is required."); } else if (!rg.IsMatch(checkOutDetails.CardHolderLastname)) { result.AddServiceError("Cardholder last name is invalid."); } } if (result.GetServiceErrors().Count > 0) { return(result); } try { CartSummary summary = GenerateCartSummary(tempCart); string transactionId = string.Empty; CartType cartType; if (summary.TotalCost == 0) { transactionId = GenerateCartCode(); cartType = CartType.Free; } else { IGatewayResponse payment; payment = ChargeConsumer(checkOutDetails, summary); if (payment.Approved) { transactionId = payment.TransactionID; cartType = CartType.Standard; } else { switch (int.Parse(payment.ResponseCode)) { case 2: result.AddServiceError("This Card has been declined."); break; case 3: result.AddServiceError(payment.Message); break; default: result.AddServiceError("Card Error"); break; } return(result); } } if (!SaveCart(tempCart, summary, userId, transactionId, cartType)) { result.AddServiceError("An error occured saving the shopping cart"); } } catch (Exception ex) { result.AddServiceError(Utilities.GetInnerMostException(ex)); } return(result); }
public ActionResult AddToCart(int id = 0, int quantity = 0) //Get Cart Collection { CartDetail cartdetail = new CartDetail(); List <CartDetail> cartdetaillist = new List <CartDetail>(); CartSummary cartsummary = new CartSummary(); Cart cart = new Cart(); FoodItem foodItem = db.FoodItems.Single(fi => fi.FoodItemId == id); Session["Restaurant"] = db.Restaurants.Single(f => f.RestaurantId == foodItem.RestaurantId); cartdetail.FoodItemId = id; cartdetail.FoodItem = foodItem.FoodItemName; cartdetail.Rate = (decimal)foodItem.FoodItemRate; cartdetail.Quantity = quantity; cartdetail.Total = (decimal)foodItem.FoodItemRate * quantity; bool isAdded = false; int servicePercent = 0; int vatpercent = 0; decimal subtotal = 0; decimal service = 0; decimal vat = 0; decimal deliverycharge = 0; decimal gtotal = 0; Restaurant restaurant = (Restaurant)Session["Restaurant"]; ViewBag.message = "Added"; if (restaurant.IsServiceChargeApplicable == true) { servicePercent = Convert.ToInt32(restaurant.ServiceChargePercent); } if (restaurant.IsVatApplicable == true) { vatpercent = Convert.ToInt32(restaurant.VATPercent); } if (Session["Cart"] != null) { Restaurant sesrest = ((Cart)Session["Cart"]).restaurantsess; if (sesrest != null) { if (sesrest.RestaurantId != restaurant.RestaurantId) { //MessageBox.Show("Alert"); Session["Cart"] = null; cartdetaillist.Add(cartdetail); cart.cartDetail = cartdetaillist; ViewData["message"] = "RestaurantChanged"; //subtotal = cartdetail.Rate * cartdetail.Quantity; //cartsummary.SubTotal = subtotal; //service = (subtotal) * servicePercent / 100; //cartsummary.ServiceCharge = service; //vat = (service + subtotal) * vatpercent / 100; //cartsummary.VAT = vat; //cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; //cart.cartSummary = cartsummary; //cartsummary.VATPercent = vatpercent; //cartsummary.ServiceChargePercent = servicePercent; //cart.cartSummary = cartsummary; cart.restaurantsess = (Restaurant)Session["Restaurant"]; Session["Cart"] = cart; isAdded = true; } } else { cart.restaurantsess = restaurant; } cart = (Cart)Session["Cart"]; cartdetaillist = cart.cartDetail; foreach (var c in cartdetaillist) { if (isAdded == false) { if (c.FoodItemId == id) { c.Quantity = c.Quantity + quantity; c.Total = c.Rate * c.Quantity; isAdded = true; } } } if (isAdded == false) { cartdetaillist.Add(cartdetail); } foreach (var c in cartdetaillist) { subtotal = subtotal + c.Rate * c.Quantity; } cartsummary.SubTotal = subtotal; service = (subtotal) * servicePercent / 100; cartsummary.ServiceCharge = service; vat = (service + subtotal) * vatpercent / 100; cartsummary.VAT = vat; cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; cartsummary.ServiceChargePercent = servicePercent; cartsummary.VATPercent = vatpercent; cart.cartSummary = cartsummary; } else { cartdetaillist.Add(cartdetail); cart.cartDetail = cartdetaillist; subtotal = cartdetail.Rate * cartdetail.Quantity; cartsummary.SubTotal = subtotal; service = (subtotal) * servicePercent / 100; cartsummary.ServiceCharge = service; vat = (service + subtotal) * vatpercent / 100; cartsummary.VAT = vat; cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; cart.cartSummary = cartsummary; cartsummary.VATPercent = vatpercent; cartsummary.ServiceChargePercent = servicePercent; cart.cartSummary = cartsummary; } cart.restaurantsess = restaurant; Session["Cart"] = cart; return(RedirectToAction("Index", new { message = ViewData["message"] })); }
public ActionResult ChangeCart(int id = 0, int quantity = 0) { CartDetail cartdetail = new CartDetail(); List <CartDetail> cartdetaillist = new List <CartDetail>(); CartSummary cartsummary = new CartSummary(); Cart cart = new Cart(); FoodItem foodItem = db.FoodItems.Single(fi => fi.FoodItemId == id); cartdetail.FoodItemId = id; cartdetail.FoodItem = foodItem.FoodItemName; cartdetail.Rate = (decimal)foodItem.FoodItemRate; cartdetail.Quantity = quantity; cartdetail.Total = (decimal)foodItem.FoodItemRate * quantity; bool isAdded = false; int servicePercent = 0; int vatpercent = 0; decimal subtotal = 0; decimal service = 0; decimal vat = 0; decimal deliverycharge = 0; decimal gtotal = 0; Restaurant restaurant = (Restaurant)Session["Restaurant"]; if (restaurant.IsServiceChargeApplicable == true) { servicePercent = Convert.ToInt32(restaurant.ServiceChargePercent); } if (restaurant.IsVatApplicable == true) { vatpercent = Convert.ToInt32(restaurant.VATPercent); } if (Session["Cart"] != null) { cart = (Cart)Session["Cart"]; cartdetaillist = cart.cartDetail; foreach (var c in cartdetaillist) { if (c.FoodItemId == id && quantity == 0) { c.Quantity = 1; } else { if (c.FoodItemId == id) { c.Quantity = quantity; c.Total = c.Rate * c.Quantity; isAdded = true; } } } foreach (var c in cartdetaillist) { subtotal = subtotal + c.Rate * c.Quantity; } cartsummary.SubTotal = subtotal; service = (subtotal) * servicePercent / 100; cartsummary.ServiceCharge = service; vat = (service + subtotal) * vatpercent / 100; cartsummary.VAT = vat; cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; cartsummary.ServiceChargePercent = servicePercent; cartsummary.VATPercent = vatpercent; cart.cartSummary = cartsummary; } else { cartdetaillist.Add(cartdetail); cart.cartDetail = cartdetaillist; subtotal = cartdetail.Rate * cartdetail.Quantity; cartsummary.SubTotal = subtotal; service = (subtotal) * servicePercent / 100; cartsummary.ServiceCharge = service; vat = (service + subtotal) * vatpercent / 100; cartsummary.VAT = vat; cartsummary.GrossTotal = subtotal + service + vat + deliverycharge; cart.cartSummary = cartsummary; cartsummary.VATPercent = vatpercent; cartsummary.ServiceChargePercent = servicePercent; cart.cartSummary = cartsummary; } Session["Cart"] = cart; ViewBag.message = "Updated"; return(RedirectToAction("Index", new { message = ViewData["message"] })); }