public async Task <bool> AddCartItem(CartItemForCreateDTO item) { var cartItem = _mapper.Map <CartItem>(item); //Find cart of user var cart = await _cartRepo.FindCartByUserId(item.UserId); cartItem.CartId = cart.Id; var book = _bookRepo.GetBookById(item.BookId); var result = await _cartItemRepo.AddToCart(cartItem); return(result); }
public Book GetBookById(Guid id) { var result = _bookRepository.GetBookById(id); return(result); }
public async Task <CreateResult> CreateOrder(OrderForCreateDTO order) { var createResult = new CreateResult() { Result = false, ResultMessage = "" }; //Cart have no item to order if (!_cartRepo.IsCartItemExist(order.UserId)) { createResult.ResultMessage = "You have no items in cart!"; return(createResult); } Cart cart = _cartRepo.GetCartByUserId(order.UserId); User user = _userService.GetById(order.UserId); //Insert new order Order newOrder = new Order() { UserId = order.UserId, TotalPrice = cart.TotalPrice, ShippingFee = order.ShippingFee, DeliveryDate = order.DeliveryDate, DeliveryOption = order.DeliveryOption, PaymentMethod = order.PaymentMethod, Status = OrderStatus.Recorded, User = user }; var orderInsertResult = await _orderRepo.CreateOrder(newOrder); if (!orderInsertResult) { createResult.ResultMessage = "Insert new order failed!"; return(createResult); } IEnumerable <CartItem> cartItems = await _cartItemRepo.GetByUserId(order.UserId); foreach (CartItem cartItem in cartItems) { //Insert order item OrderItem orderItem = new OrderItem() { BookId = cartItem.BookId, Quantity = cartItem.Quantity, OrderId = newOrder.Id, }; var orderItemInsertResult = await _orderItemRepo.CreateOrderItem(orderItem); if (!orderItemInsertResult) { createResult.ResultMessage = "Add order item failed!"; return(createResult); } //Update book quantity var book = _bookRepo.GetBookById(cartItem.BookId); //Check quantity of book if (book.Quantity < cartItem.Quantity) { createResult.ResultMessage = "Book's quantity is not enough!"; return(createResult); } book.Quantity -= cartItem.Quantity; var updateBookResult = await _bookRepo.UpdateBook(book, cartItem.BookId); if (!updateBookResult) { createResult.ResultMessage = "Update book quantity failed!"; return(createResult); } } //Send email to user var mailContent = new EmailContent() { ToEmail = user.Email, ToName = user.Name, Message = "", Subject = "Invoid for order" }; await _emailService.SendEmailAsync(mailContent, newOrder); //Clear all cart item after create order var clearCartItemResult = _cartItemRepo.ClearAllCartItem(order.UserId); if (!clearCartItemResult) { createResult.ResultMessage = "Clear cart item failed!"; return(createResult); } createResult.Result = true; createResult.ResultMessage = "Create new order successfull!"; createResult.NewOrderId = newOrder.Id; return(createResult); }