Beispiel #1
0
        public async Task <IActionResult> Post([FromBody] API.Order order)
        {
            try
            {
                var user = _userServ.GetUser();
                if (user == null)
                {
                    return(Unauthorized("User is not authentificated."));
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var cartLines = await _cartLineRepo.FindByAsync(c => c.UserId == user.Id);

                //if (cartLines.Count == 0)
                //    return BadRequest("Cart is empty.");

                order.OrderTime = DateTime.Now;
                order.UserId    = user.Id;
                order.Amount    = cartLines.Sum(c => c.Price * c.Quantity);

                //маппировка, сохранение, получение ID новой записи
                var newOrderId = await _orderRepo.SaveAsync(_mapper.Map <BL.Order>(order));

                foreach (var item in cartLines)
                {
                    var orderLine = new BL.OrderLine
                    {
                        Quantity  = item.Quantity,
                        Price     = item.Price,
                        ProductId = item.ProductId,
                        OrderId   = newOrderId
                    };

                    await _orderLineRepo.SaveAsync(orderLine);  //сохранение новой записи строки заказа

                    await _cartLineRepo.DeleteAsync(item.Id);   //удаление строки корзины на основании которой создана строка заказа
                }

                return(Ok(order));
            }
            catch (Exception ex)
            {
                return(BadRequest($"{ex.Message}"));
            }
        }
Beispiel #2
0
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                BL.CartLine cartLine = await _cartLineRepo.GetByIdAsync(id);

                if (cartLine != null)
                {
                    await _cartLineRepo.DeleteAsync(id);

                    return(Ok(cartLine));
                }

                return(BadRequest("Item not found."));
            }
            catch (Exception ex)
            {
                return(BadRequest($"{ex.Message}"));
            }
        }