// // GET: /Checkout/ public IActionResult AddressAndPayment() { var nameGenerator = new PersonNameGenerator(); var placeNameGenerator = new PlaceNameGenerator(); var rndNum = new Random(); var firstName = nameGenerator.GenerateRandomMaleFirstName(); var lastName = nameGenerator.GenerateRandomLastName(); var orderCreateDto = new CheckoutDto { FirstName = firstName, LastName = lastName, Address = rndNum.Next(1000, 9999) + " " + placeNameGenerator.GenerateRandomPlaceName(), PostalCode = rndNum.Next(10000, 99999).ToString(), City = placeNameGenerator.GenerateRandomPlaceName(), State = "OH", Phone = "(" + rndNum.Next(100, 999) + ")" + rndNum.Next(100, 999) + "-" + rndNum.Next(1000, 9999), Email = firstName + "@" + "hotmail.com", CreditCardNumber = "4111 1111 1111 1111", CardholderName = $"{firstName} {lastName}", SecurityCode = "123", ExpirationDate = DateTime.Today.AddYears(1), }; return(View(orderCreateDto)); }
public IHttpActionResult CreateCheckout(CheckoutDto newCheckout) { // Get the subscriber who is checking out the books var sub = _context.Subscriber.Single(s => s.Id == newCheckout.SubId); // Get all the books selected during checkout. This SQL will be as - // SELECT * From Books Where Id IN ( 3, 4, 5, 8); // 3,4,5,8 are bookids during checkout. var books = _context.Book.Where(b => newCheckout.BookIds.Contains(b.Id)); foreach (var b in books) { // create checkout object for each book var objCheckout = new Checkout { Subscriber = sub, Book = b, DateCheckout = DateTime.Now }; // Add checked out books details in the Checkout Model _context.Checkouts.Add(objCheckout); } // after checkout is complete, save all entries in the database. _context.SaveChanges(); throw new NotImplementedException(); }
public CheckoutDto CalculateTotals(Cart cart, Coupon coupon = null) { if (cart.ShippingAddress == null) { throw new MissingDataException("Cannot calculate total cost - missing Shipping method"); } var itemCost = cart.Items.Sum(item => item.Price * item.Quantity); var shippingCost = _shippingCalculator.CalculateShippingCost(cart); var customerDiscount = 0.0; if (cart.CustomerType == CustomerType.Premium) { customerDiscount = 10.0; } var customerDiscountPercent = (100.0 - customerDiscount) / 100.0; var total = (itemCost + shippingCost) * customerDiscountPercent; var shoppingCartDto = _mapper.Map <ShoppingCartDto>(cart); var checkoutDto = new CheckoutDto(shoppingCartDto, shippingCost, customerDiscount, total); if (coupon != null) { return(checkoutDto with { TotalAfterCoupon = _couponEngine.CalculateDiscount(checkoutDto, coupon) }); } else { return(checkoutDto); } }
public double CalculateDiscount(CheckoutDto checkout, Coupon coupon) { if (checkout == null || coupon == null) { return(0); } if (DateTime.Now.Subtract(coupon.ExpiryDate).Days > 30) { throw new CouponExpiredException("Coupon past 30 days and has expired."); } if (coupon.Amount > checkout.Total) { throw new InvalidCouponException("Coupon amount cannot be greater than total."); } if (coupon.Amount < 0) { throw new InvalidCouponException("Coupon amount cannot be negative."); } if (coupon.Type == CouponType.Percentage && coupon.Amount >= 100) { throw new InvalidCouponException("Coupon amount cannot be equal to 100."); } return(checkout.Total * coupon.Amount); }
public async Task <ActionResult <CheckoutDto> > PostCheckout(CheckoutDto checkoutDto) { OrderDto order = checkoutDto.Order; Customer customer = checkoutDto.Customer.ToCustomer(); await _orderService.CheckoutOrder(order, customer); return(Created($"/api/orders/{order.OrderId}", order)); }
public async Task <IActionResult> Index(CheckoutDto _) { if (ModelState.IsValid) { return(RedirectToRoute(new { Controller = "CreditCard", Action = "ChooseCreditCardOrProceed" })); } return(RedirectToAction("AddressCreateOrChoose")); }
public double CalculateAmount(CheckoutDto checkoutDto, Coupon coupon) { if (IsValid(checkoutDto, coupon)) { return(_calculateAmountFunc(checkoutDto, coupon)); } throw new InvalidCouponException("Coupon amount not valid"); }
public void CreateCheckout_Creates_Checkout() { var entity = new CheckoutEntity(); var dto = new CheckoutDto(); mockMapper.Setup(m => m.Map <CheckoutEntity>(dto)).Returns(entity); checkoutService.CreateCheckout(dto); mockRepo.Verify(r => r.Insert(entity), Times.Once); }
public Checkout(Page page, CheckoutDto checkoutDto) : base(page) { if (checkoutDto == null) { throw new ArgumentNullException(nameof(checkoutDto)); } _checkoutDto = checkoutDto; TemplateName = "_GTM-checkout.cshtml"; }
public void CreateCheckout_Returns_CheckoutDto() { var entity = new CheckoutEntity(); var dto = new CheckoutDto(); mockRepo.Setup(r => r.Insert(It.IsAny <CheckoutEntity>())).Returns(entity); mockMapper.Setup(m => m.Map <CheckoutDto>(entity)).Returns(dto); var actual = checkoutService.CreateCheckout(dto); Assert.AreEqual(dto, actual); }
public void UpdateCheckout(CheckoutDto checkoutDto) { var checkout = _checkoutRepository.Get(checkoutDto.Id); checkout.ReservationId = checkoutDto.ReservationId; checkout.BikeCheckoutId = checkoutDto.BikeCheckoutId; checkout.ReservedDateTime = checkoutDto.ReservedDateTime; checkout.CheckoutDateTime = checkoutDto.CheckoutDateTime; checkout.ExpectedReturnDateTime = checkoutDto.ExpectedReturnDateTime; _checkoutRepository.Update(checkout); }
public async Task <IActionResult> ProceedToCheckout(int id) { List <CartItem> _checkoutItems = null; if (HttpContext?.Session != null) { _checkoutItems = HttpContext?.Session.GetObjectFromJson <List <CartItem> >("cart"); } if (_checkoutItems == null) { return(RedirectToRoute(new { controller = "Cart" })); } if (id < 0) { return(RedirectToAction("AddressCreateOrChoose")); } var user = await _userManager.GetUserAsync(HttpContext.User); var addressList = _uow.GetGenericRepository <Address>().Find(x => x.UserId == user.CustomerId)?.ToList(); if (addressList != null && addressList.Count > id) { SessionHelper.SetObjectAsJson(HttpContext.Session, "addressId", id); var address = addressList[id]; var model = new CheckoutDto() { FirstName = user.FirstName, LastName = user.LastName, AddressInfo = new AddressDto() { AddressDetail = address.AddressDetail, City = address.City, Province = address.Province, ZipCode = address.ZipCode }, Phone = user.PhoneNumber, Email = user.Email, IsAgreeTermsAndConditions = false, CheckoutItems = _checkoutItems?.Select(x => new CheckoutItem() { Price = x.ItemPrice * x.ItemQuantity, ProductName = x.ItemName }) }; return(View("Index", model)); } return(RedirectToAction("AddressCreateOrChoose")); }
public void UpdateCheckout_Calls_Update_In_Repo() { var entity = new CheckoutEntity(); var dto = new CheckoutDto { Id = Guid.NewGuid() }; mockRepo.Setup(r => r.Get(It.IsAny <Guid>())).Returns(entity); checkoutService.UpdateCheckout(dto); mockRepo.Verify(r => r.Update(It.IsAny <CheckoutEntity>()), Times.Once); }
public void When_Coupon_Is_Null_Return_Zero() { var sut = new CouponEngine(); var shoppingCartDto = new ShoppingCartDto() { Id = "1", Items = Utility.GenerateListOfDtoItems() }; var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 100); var result = sut.CalculateDiscount(checkout, null); result.Should().Be(0); }
public void GetByReservationId_Returns_Collection_CheckoutDtos() { var reservationId = Guid.NewGuid(); var entity = new CheckoutEntity(); var dto = new CheckoutDto(); mockRepo.Setup(r => r.GetByReservationId(It.IsAny <Guid>())).Returns(entity); mockMapper.Setup(m => m.Map <CheckoutDto>(entity)).Returns(dto); var actual = checkoutService.GetByReservationId(reservationId); Assert.AreEqual(dto, actual); }
public async Task TryCheckout(CheckoutDto dto) { await Execute(async() => { using (UnitOfWork db = new UnitOfWork()) { CheckPointEntity checkPoint = await db.GetRepo <CheckPointEntity>().Get(dto.CheckPointId.Value); AccountEntity account = await db.GetRepo <AccountEntity>().Get(dto.AccountId.Value); if (dto.CurrentManufactoryId.Value != checkPoint.Manufactory1Id && dto.CurrentManufactoryId.Value != checkPoint.Manufactory2Id) { DataValidationException exception = new DataValidationException(); exception.Add( typeof(CheckoutDto), nameof(CheckoutDto.CurrentManufactoryId), $"{nameof(CheckoutDto.CurrentManufactoryId)} must be one of manufactories associated with check point" ); throw exception; } CheckPointEventEntity checkPointEvent = new CheckPointEventEntity() { account_id = account.id, check_point_id = checkPoint.id, is_direct = checkPoint.Manufactory1Id == dto.CurrentManufactoryId.Value, timespan = DateTime.Now }; ManufactoryEntity targetManufactory = checkPointEvent.is_direct ? checkPoint.Manufactory2 : checkPoint.Manufactory1; NotPermittedException ex = null; if (account.Roles.SelectMany(r => r.ManufactoryPermissions).Any(m => m.id == targetManufactory.id)) { checkPointEvent.log = $"Checkout to Manufactory #{targetManufactory.id} via Check Point ${checkPoint.id} by Account #{account.id}: SUCCESS"; } else { checkPointEvent.log = $"Checkout to Manufactory #{targetManufactory.id} via Check Point ${checkPoint.id} by Account #{account.id}: ACCESS DENIED"; ex = new NotPermittedException(checkPointEvent.log); } await db.GetRepo <CheckPointEventEntity>().Create(checkPointEvent); await db.Save(); if (ex != null) { throw ex; } } }); }
public CheckoutDto GetCheckoutByDate(GetCheckoutByDateDto data, StaffMemberDto staffMemberDto) { DateTime shiftDate = Convert.ToDateTime(data.StringDate).Date; CheckoutEntity checkoutEntity = _repository.GetCheckOutForStaffMemberForSpecificDate(shiftDate, staffMemberDto.Id, data.LunchOrDinner); if (checkoutEntity == null) { throw new KeyNotFoundException("No checkout for the provided staffmember was found for the given parameters."); } CheckoutDto checkoutDto = Mapper.Map <CheckoutDto>(checkoutEntity); return(checkoutDto); }
public async Task <bool> Add(CheckoutDto newCheckoutDto) { var checkoutEntity = _mapper.Map <Data.Models.Checkout>(newCheckoutDto); try { await _context.AddAsync(checkoutEntity); await _context.SaveChangesAsync(); return(true); } catch (Exception ex) { throw new LibraryServiceException(Reason.UncaughtError); } }
public void UpdateCheckout_Updates_Checkout() { var entity = new CheckoutEntity(); var dto = new CheckoutDto { Id = Guid.NewGuid(), CheckoutDateTime = DateTime.UtcNow }; mockRepo.Setup(r => r.Get(It.IsAny <Guid>())).Returns(entity); checkoutService.UpdateCheckout(dto); mockRepo.Verify(r => r.Update( It.Is <CheckoutEntity>(r => r.CheckoutDateTime == dto.CheckoutDateTime)), Times.Once); }
public async Task <IActionResult> AddressAndPayment( [FromForm] CheckoutDto checkoutDto, CancellationToken requestAborted) { if (!ModelState.IsValid) { return(View(checkoutDto)); } var formCollection = await HttpContext.Request.ReadFormAsync(); try { //if (string.Equals(formCollection["PromoCode"].FirstOrDefault(), PromoCode, StringComparison.OrdinalIgnoreCase) == false) return View(checkoutDto); // Abbreviate user first and last name to create the username checkoutDto.Username = $"{checkoutDto.FirstName.Substring(0, 2)}-{checkoutDto.LastName.Substring(0, 3)}"; checkoutDto.BasketId = _cookieLogic.GetBasketId(); var response = await _IRestClient.PostAsync <BasketSummaryDto>($"{baseUrl}/checkout", checkoutDto); if (response.HttpResponseMessage.IsSuccessStatusCode) { // Order is successful remove shopping basket _cookieLogic.RemoveBasketId(); } //await _IRestClient.DeleteAsync($"{baseUrl}/{checkoutDto.BasketId}"); //_cookieLogic.SetBasketId(); _logger.LogInformation($"User {checkoutDto.Username} started checkout of {checkoutDto.OrderId}."); TempData[ToastrMessage.Success] = "Thank you for your order"; TempData["BuyerEmail"] = checkoutDto.Email; TempData["BasketId"] = response.Data.BasketId; TempData["CorrelationId"] = response.Data.CorrelationId; //return RedirectToAction("index", "Home"); return(View("OrderPlaced")); } catch { ModelState.AddModelError("", "An error occured whil processing order"); //Invalid - redisplay with errors return(View(checkoutDto)); } }
public void Coupon_Cannot_Be_Greater_Than_Cart_Total() { var sut = new CouponEngine(); var shoppingCartDto = new ShoppingCartDto() { Id = "1", Items = Utility.GenerateListOfDtoItems() }; var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10); Action result = () => sut.CalculateDiscount(checkout, new Coupon() { Amount = 100, ExpiryDate = DateTime.Now.AddDays(-60) }); result.Should().Throw <CouponExpiredException>() .WithMessage("Coupon past 30 days and has expired."); }
public void Coupon_Calculated_As_A_Percentage() { var sut = new CouponEngine(); var shoppingCartDto = new ShoppingCartDto() { Id = "1", Items = Utility.GenerateListOfDtoItems() }; var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10); var result = sut.CalculateDiscount(checkout, new Coupon() { Amount = 2, Type = CouponType.Percentage, ExpiryDate = DateTime.Now.AddDays(10) }); result.Should().Be(20); }
public void Coupon_Cannot_Be_A_Negative_Number() { var sut = new CouponEngine(); var shoppingCartDto = new ShoppingCartDto() { Id = "1", Items = Utility.GenerateListOfDtoItems() }; var checkout = new CheckoutDto(shoppingCartDto, 10, 1, 10); Action result = () => sut.CalculateDiscount(checkout, new Coupon() { Amount = -2, ExpiryDate = DateTime.Now.AddDays(10) }); result.Should().Throw <InvalidCouponException>() .WithMessage("Coupon amount cannot be negative."); }
public void Coupon_No_More_Than_OneHundred() { var sut = new CouponEngine(); var shoppingCartDto = new ShoppingCartDto() { Id = "1", Items = Utility.GenerateListOfDtoItems() }; var checkout = new CheckoutDto(shoppingCartDto, 20, 10, 200); Action result = () => sut.CalculateDiscount(checkout, new Coupon() { Amount = 100, Type = CouponType.Percentage, ExpiryDate = DateTime.Now.AddDays(10) }); result.Should().Throw <InvalidCouponException>() .WithMessage("Coupon amount cannot be equal to 100."); }
public async Task <IActionResult> PostCheckOut([FromBody] CheckoutDto checkoutDto, [FromHeader(Name = "x-correlationToken")] string correlationToken) { Guard.ForNullObject(checkoutDto, "NewOrder"); Guard.ForNullOrEmpty(checkoutDto.BasketId, "BasketId in New Order"); Guard.ForNullOrEmpty(correlationToken, "CorrleationToken"); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Call into service var checkout = await _basketBusinessServices.Checkout(checkoutDto, correlationToken); // Ensure that ShoppingBasket exists before executing Checkout operation //var basket = await _basketBusinessServices.GetBasketById(checkoutDto.BasketId, correlationToken); //if (basket.Count < 1) // return null; // Map OrderDto to Order //var newOrder = Mapper.MapToOrderInformation(checkoutDto); // Call into service //await _basketBusinessServices.Checkout(newOrder, correlationToken); // Returns 202 status code //return new ObjectResult(new CheckoutDto()); //return Accepted("Order is being created"); if (checkout == null) { return(BadRequest($"Could not checkout for Basket {checkoutDto.BasketId} for Request {correlationToken}")); } return(Accepted(new BasketSummaryDto { BasketId = checkout.CheckoutSystemId, BuyerEmail = checkout.BuyerEmail, CorrelationId = checkout.CorrelationId } )); }
public IActionResult GetCheckoutByDate([FromBody] GetCheckoutByDateDto data) { try { StaffMemberDto staffDto = _staffCore.GetStaffMember(data.StaffMemberId); CheckoutDto checkout = _checkoutsCore.GetCheckoutByDate(data, staffDto); return(Ok(checkout)); } catch (Exception e) { _logger.LogError(e.Message); ModelState.AddModelError("Checkout by Date Error: ", e.Message); if (e.InnerException is KeyNotFoundException) { return(BadRequest(ModelState)); } return(StatusCode(500, ModelState)); } }
public async Task <IActionResult> CheckIn([FromBody] CheckoutDto payload, Guid id, Guid checkId) { ApiResponse <CheckoutDto> response = new ApiResponse <CheckoutDto>(); try { if (!response.Errors.Any()) { var userFromRepo = await _userSrv.GetUser(id); if (userFromRepo == null) { return(BadRequest(new { errorList = "Invalid User Id" })); } var currentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value; if (currentUserId != userFromRepo.Email) { return(BadRequest(new { errorList = "UnAuthorized" })); } (List <ValidationResult> Result, CheckoutDto Checkout)errorResult = await _checkoutServ.CheckInBook(payload, checkId); if (errorResult.Result.Any()) { return(BadRequest(new { errorList = $"{errorResult.Result.FirstOrDefault().ErrorMessage}" })); } else { response.Code = ApiResponseCodes.OK; response.Description = $"Checkout successful."; } } } catch (Exception ex) { return(BadRequest(ex.Message)); } return(Ok(response)); }
public IActionResult CreateCheckOut([FromBody] CreateCheckoutDto data) { //convert the date sent from the client into a DateTime format data.ShiftDate = Convert.ToDateTime(data.StringDate).Date; try { UtilityMethods.ValidateLunchOrDinnerSpecification(data.LunchOrDinner); StaffMemberDto staffMember = _staffCore.GetStaffMember(data.StaffMemberId); JobDto job = _jobCore.GetJobByTitle(data.JobWorkedTitle); CheckoutDto checkout = _checkoutsCore.CreateCheckout(data, staffMember, job); return(CreatedAtRoute("CreateCheckout", checkout)); } catch (Exception e) { if (e.InnerException is InvalidOperationException) { return(BadRequest(e.Message)); } _logger.LogError(e.Message); ModelState.AddModelError("Create Checkout Failure", e.Message); return(StatusCode(500, ModelState)); } }
public async Task <HttpResponseMessage> TryCheckout([FromBody] CheckoutDto dto) { return(await Execute(d => LocationService.TryCheckout(d), dto)); }
public bool IsValid(CheckoutDto checkoutDto, Coupon coupon) { return(_validationFunc(checkoutDto, coupon)); }