public async Task <ActionResult <Order_Receipt> > CreateAsync([FromForm] Order_ReceiptCreateDto Order_ReceiptCreateDto) { try { var order = await service.Create(Order_ReceiptCreateDto); if (order == null) { return(BadRequest("Out of quantity in stock")); } return(order); } catch (Exception error) { return(Conflict(error.Message)); } }
public async Task <Order_Receipt> Create(Order_ReceiptCreateDto dto) { var delivery = await repository.context.DeliveryMethods.FirstOrDefaultAsync(x => x.Id == dto.DeliveryId); var cart = await shoppingCartService.GetCartByUserName(dto.AccountId); var items = cart.Items; foreach (var item in items) { var book = await repository.context.Books.FirstOrDefaultAsync(x => x.Id == item.BookId); if (book.QuantityInStock < item.Quantity) { return(null); } book.QuantityInStock = book.QuantityInStock - item.Quantity; await repository.context.SaveChangesAsync(); } var OrderItems = _mapper.Map <List <OrderItem> >(items); decimal total = 0; foreach (var item in items) { total = total + item.TotalPrice; } var entity = new Order_Receipt { FullName = dto.FullName, Phone = dto.Phone, Email = dto.Email, AccountId = dto.AccountId, CreatedAt = dto.CreatedAt, OrderItems = OrderItems, DeliveryMethod = delivery, Status = OrderStatus.Paid, TotalPrice = total + delivery.Price, }; cart.ClearItems(); repository.Add(entity); repository.context.SaveChanges(); return(entity); }