public async Task ApplyVoucherAsync(string voucherCode) { var basket = GetCurrentBasket(); if (basket.VoucherApplied == true) { return; } var voucher = await _voucherService.GetAsync(voucherCode); if (voucher != null && voucher.ExpiryDate >= DateTime.UtcNow.Date) { var discountToBeApplied = voucher.Discount; if (basket.NumberOfItems > 0) { var hasNonGiftItems = basket.LineItems.Any(li => li.IsGiftVoucherItem == false); if (hasNonGiftItems) { var giftItemsTotal = basket.LineItems.Where(li => li.IsGiftVoucherItem).Sum(li => li.LineItemPrice); var giftItemDiscount = basket.LineItems.Where(li => li.IsGiftVoucherItem).Sum(li => li.LineItemDiscount); var nonGiftItemsTotal = basket.LineItems.Where(li => li.IsGiftVoucherItem == false).Sum(li => li.LineItemPrice); var nonGiftItemDiscount = basket.LineItems.Where(li => li.IsGiftVoucherItem == false).Sum(li => li.LineItemDiscount); var discountAfterApplyingVoucher = nonGiftItemDiscount + voucher.Discount; var priceAfterApplyinVoucher = nonGiftItemsTotal - voucher.Discount; if (priceAfterApplyinVoucher < 0) { priceAfterApplyinVoucher = 0; } basket.TotalDiscount = giftItemDiscount + discountAfterApplyingVoucher; basket.TotalPrice = giftItemsTotal + priceAfterApplyinVoucher - giftItemDiscount - nonGiftItemDiscount; if (basket.TotalPrice < 0) { basket.TotalPrice = 0; } basket.VoucherApplied = true; basket.VoucherDiscount = voucher.Discount; } //var notGiftedLineItemsPrice = basket. // LineItems. // Where(li => li.IsGiftVoucherItem == false). // Sum(li => li.LineItemPrice); //var maxVoucherDisount = notGiftedLineItemsPrice - voucher.Discount; //if(maxVoucherDisount > 0) //{ // basket.TotalDiscount = basket.TotalDiscount + voucher.Discount; // basket.TotalPrice = basket.TotalPrice - discountToBeApplied; //} //if (basket.TotalPrice < 0) //{ // basket.TotalPrice = 0; //} //basket.VoucherApplied = true; //basket.VoucherDiscount = voucher.Discount; } } }