Ejemplo n.º 1
0
 public IActionResult Post([FromBody] NewOrderDto newOrderDto, int idClient)
 {
     try
     {
         return(Ok(_dbService.AddOrder(newOrderDto, idClient)));
     }
     catch (Exception e)
     {
         return(BadRequest("Exception: " + e.Message + "\n" + e.StackTrace));
     }
 }
        public async Task <ContentResult> CreateOrder(NewOrderDto order)
        {
            ReturnMessage rm = new ReturnMessage(1, "Success");

            try
            {
                var customer = _mapper.Map <Customer>(order.Customer);
                var address  = _mapper.Map <Address>(order.Address);
                var payment  = _mapper.Map <Payment>(order.Payment);


                var customerAdded = _unitOfWork.Customers._Add(customer);
                var addressAdded  = _unitOfWork.Address._Add(address);
                var paymentAdded  = _unitOfWork.Payments._Add(payment);

                var orderAdded = _unitOfWork.Orders._Add(new Order()
                {
                    Message      = order.Message,
                    Status       = "Pending",
                    Customer     = customerAdded,
                    OrderAddress = addressAdded,
                    Payment      = paymentAdded,
                    CreatedAt    = DateTime.Now,
                    UpdatedAt    = DateTime.Now,
                    OrderAt      = order.OrderTime
                });

                foreach (var item in order.Product)
                {
                    _unitOfWork.OrderDetails.Add(new OrderDetail()
                    {
                        Quantity  = item.Quantity,
                        Message   = item.Message,
                        Order     = orderAdded,
                        ProductId = item.ProductId,
                        SizeId    = item.SizeId
                    });
                }

                _unitOfWork.Complete();

                return(this.Content(rm.returnMessage(null),
                                    "application/json"));
            }
            catch (Exception ex)
            {
                return(this.Content(JsonConvert.SerializeObject(new
                {
                    // 0 is Exception
                    msgCode = 0,
                    msg = ex.Message
                }), "application/json"));
            }
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] NewOrderDto newOrderDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _orderId++;

            var pickupPosition = await GetByAddress(newOrderDto.PickUp);

            if (pickupPosition == null)
            {
                return(BadRequest($"address = \"{newOrderDto.PickUp}\"  not found"));
            }

            var dropoffPosition = await GetByAddress(newOrderDto.DropOff);

            if (dropoffPosition == null)
            {
                return(BadRequest($"address = \"{newOrderDto.DropOff}\" address not found"));
            }

            var newOrder = new Order
            {
                Id     = _orderId.ToString(),
                Status = OrderStatus.unassigned,
                Pickup = new GLocation
                {
                    Address  = newOrderDto.PickUp,
                    Position = pickupPosition,
                },
                Dropoff = new GLocation
                {
                    Address  = newOrderDto.DropOff,
                    Position = dropoffPosition,
                }
            };

            Orders.Add(newOrder);

            BrowserSocket.SendToAllAsync(new OrdersSocketMessage
            {
                Payload = Orders
            });

            MobileSocket.SendToAllMobileSockets(new OrderAvailablePayload
            {
                Payload = newOrder
            });

            return(Ok(newOrder));
        }
Ejemplo n.º 4
0
        public void Add(NewOrderDto order)
        {
            var dbOrder = new Order()
            {
                CreatedDate = order.CreatedDate.ToUniversalTime(),
                Total       = order.Total,
                UserId      = -1,
            };

            dbOrder.OrderItems = GetOrderItems(order.Items, dbOrder);

            _orderRepository.Create(dbOrder);
        }
Ejemplo n.º 5
0
        private async Task <Order> SaveNewOrderAsync(NewOrderDto newOrderDto)
        {
            var newOrderModel = _mapper.Map <Order>(newOrderDto);

            newOrderModel.CreatedAt = newOrderModel.LastUpdatedAt = DateTime.Now;
            newOrderModel.Status    = OrderStatus.New;

            foreach (var orderItem in newOrderModel.Items)
            {
                orderItem.Status = OrderItemStatus.New;
            }

            return(await _orderUoW.OrdersRepository.CreateAsync(newOrderModel));
        }
Ejemplo n.º 6
0
 public static void ValidateNewOrderDto(NewOrderDto newOrderDto)
 {
     newOrderDto.OrderLines.ForEach(item =>
     {
         if (string.IsNullOrEmpty(item.ComputerId))
         {
             throw new Exception("Computer id cannot be null or empty");
         }
         if (item.Quantity < 0)
         {
             throw new Exception("Computer quantity cannot be negative");
         }
     });
 }
Ejemplo n.º 7
0
        public ActionResult <OrderDto> Create([FromBody] NewOrderDto data)
        {
            try
            {
                var order    = _mapper.Map <NewOrderDto, Order>(data);
                var newOrder = _service.CreateOrder(order);

                var result = _mapper.Map <Order, OrderDto>(newOrder);
                return(CreatedAtAction(nameof(Get), new { id = newOrder.Id }, result));
            }
            catch (ArgumentException)
            {
                return(BadRequest());
            }
        }
        public IActionResult AddOrder(NewOrderDto newOrderDto, int idClient)
        {
            if (newOrderDto.Wyroby.Count() == 0)
            {
                return(new BadRequestObjectResult("Order should contains at least 1 product"));
            }

            Client client = _context.Clients.Find(idClient);

            if (client == null)
            {
                return(new NotFoundObjectResult("Client with selected id doesn't exist"));
            }

            Order order = new Order
            {
                IdClient       = idClient,
                IdEmployee     = idClient % 2,
                AcceptanceDate = newOrderDto.DataPrzyjecia,
                Comments       = newOrderDto.Uwagi
            };

            _context.Orders.Add(order);
            _context.SaveChanges();

            foreach (NewOrderItemDto newOrderItemDto in newOrderDto.Wyroby)
            {
                ConfectioneryProduct confectioneryProduct = _context.ConfectioneryProducts
                                                            .Where(p => p.Name == newOrderItemDto.Wyrob)
                                                            .FirstOrDefault();
                if (confectioneryProduct == null)
                {
                    return(new NotFoundObjectResult("Product with selected name doesn't exist"));
                }
                OrderItem orderItem = new OrderItem
                {
                    IdOrder = _context.Orders.Max(o => o.IdOrder),
                    IdConfectioneryProduct = confectioneryProduct.IdConfectioneryProduct,
                    Quantity = int.Parse(newOrderItemDto.Ilosc),
                    Comments = newOrderItemDto.Uwagi
                };
                _context.OrderItems.Add(orderItem);
            }
            _context.SaveChanges();


            return(new OkObjectResult("Ok"));
        }
        public void Raise_an_error_when_creating_new_order_with_non_existing_computer()
        {
            NewOrderDto newOrderDto = new NewOrderDto
            {
                OrderLines = new List <NewOrderLineDto> {
                    new NewOrderLineDto {
                        ComputerId = "Unknown", Quantity = 1
                    }
                },
            };

            Exception exception = Assert.Throws <Exception>(() => ordersController.CreateNewOrder(newOrderDto));

            Assert.IsNotNull(exception);
            Assert.AreEqual("Computer not found. Id: Unknown", exception.Message);
        }
        public void Raise_an_error_when_creating_new_order_with_negative_quantity()
        {
            ComputersController computersController = new ComputersController();
            ComputerInfoDto     computerInfoDto     = computersController.FindComputerByName("MacBook Pro 15");
            NewOrderDto         newOrderDto         = new NewOrderDto
            {
                OrderLines = new List <NewOrderLineDto> {
                    new NewOrderLineDto {
                        ComputerId = computerInfoDto.Id, Quantity = -1
                    }
                }
            };

            Exception exception = Assert.Throws <Exception>(() => ordersController.CreateNewOrder(newOrderDto));

            Assert.IsNotNull(exception);
            Assert.AreEqual("Computer quantity cannot be negative", exception.Message);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> CheckOut([FromBody] NewOrderDto newOrderDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var correlationToken = CorrelationTokenManager.GenerateToken();

            // Note: Sending querystring parameters in the post.
            var response = await client.PostAsync <NewOrderDto>(ServiceEnum.Basket,
                                                                $"api/Basket/CheckOut/?correlationToken={correlationToken}", newOrderDto);

            if (response == null)
            {
                return(BadRequest($"Shopping Basket with Id {newOrderDto.BasketId} could not be found"));
            }

            return(Accepted("Order Being Created"));
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> OrderForm(List <string> listbox)
        {
            NewOrderDto newOrderDTO           = new NewOrderDto();
            ICollection <OrderedPartDto> list = new List <OrderedPartDto>();
            int        id    = 0;
            List <int> ids   = new List <int>();
            var        parts = await partRepo.Select();

            foreach (var item in listbox)
            {
                id = 0;
                foreach (var part in parts)
                {
                    if (part.Name == item)
                    {
                        id = part.Id;
                        break;
                    }
                }
                ids.Add(id);
            }


            foreach (var _id in ids)
            {
                OrderedPartDto newOrder = new OrderedPartDto()
                {
                    PartId = _id,
                    Price  = 30
                };
                list.Add(newOrder);
            }
            newOrderDTO.PartList = list;
            newOrderDTO.AuthorId = HttpContext.Session.GetComplex <User>("User").Id;
            newOrderDTO.Date     = DateTime.Now;
            await orderRepo.AddOrder(newOrderDTO);

            var orders = await orderRepo.Select();

            return(View("OrdersPage", orders));
        }
Ejemplo n.º 13
0
        public ActionResult NewOrder(NewOrderDto newOrder, ICreateService service)
        {
            if (!ModelState.IsValid)
            {
                //model errors so return immediately
                service.ResetDto(newOrder);
                return(View(newOrder));
            }

            var response = service.Create(newOrder);

            if (response.IsValid)
            {
                //no success message as in a process
                return(RedirectToAction("EditLineItems", new { salesOrderId = newOrder.SalesOrderID }));
            }

            //else errors, so copy the errors over to the ModelState and return to view
            response.CopyErrorsToModelState(ModelState, newOrder);
            return(View(newOrder));
        }
        public NewOrderIdDto CreateNewOrder(NewOrderDto newOrderDto)
        {
            User user = AuthenticationService.AuthenticateUser(_username, _password);

            ValidationService.ValidateNewOrderDto(newOrderDto);
            Order order = new Order()
            {
                Guid       = Guid.NewGuid().ToString(),
                Date       = DateTime.Now,
                OrderLines = newOrderDto.OrderLines.Select(TransformationService.NewOrderLineDtoToOrderLine).ToList(),
                User       = user
            };

            Entities entities = DatabaseContext.GetEntities();

            entities.Orders.Add(order);
            entities.Save();
            return(new NewOrderIdDto
            {
                Id = order.Guid
            });
        }
Ejemplo n.º 15
0
        public void CreateOrder_CreatedDate_Should_BeStoredInUtcFormat()
        {
            // Arrange
            var dateToTest = DateTime.Now;
            var inputDto   = new NewOrderDto()
            {
                CreatedDate = dateToTest
            };
            var mockOrderRepository = new Mock <IOrderRepository>();

            var result = default(Order);

            mockOrderRepository.Setup(r => r.Create(It.IsAny <Order>()))
            .Callback <Order>(o => result = o);

            // Act
            var orderService = new OrderService(mockOrderRepository.Object);

            orderService.Add(inputDto);

            // Assert
            mockOrderRepository.Verify(orderRepo => orderRepo.Create(It.IsAny <Order>()), Times.Once);
            Assert.AreEqual(result.CreatedDate, dateToTest.ToUniversalTime());
        }
Ejemplo n.º 16
0
        public async Task <ActionResult <string> > CreateOrder(NewOrderDto newOrder)
        {
            var requestId = await _ordersService.Create(newOrder);

            return(Accepted(requestId));
        }
        public ActionResult NewOrder(NewOrderDto newOrder, ICreateService service)
        {
            if (!ModelState.IsValid)
            {
                //model errors so return immediately
                service.ResetDto(newOrder);
                return View(newOrder);
            }

            var response = service.Create(newOrder);
            if (response.IsValid)
            {
                //no success message as in a process
                return RedirectToAction("EditLineItems", new { salesOrderId = newOrder.SalesOrderID});
            }

            //else errors, so copy the errors over to the ModelState and return to view
            response.CopyErrorsToModelState(ModelState, newOrder);
            return View(newOrder);
        }
Ejemplo n.º 18
0
 public Task <ApiResponse <OrderDto> > AddOrderAsync(NewOrderDto dto)
 {
     return(PostAsync <NewOrderDto, ApiResponse <OrderDto> >(_clientOptions.MakeOrderUrl, dto));
 }
Ejemplo n.º 19
0
 public async Task <Guid> Create(NewOrderDto newOrder)
 {
     return(await Mediator.Send(new CreateOrderCommand { NewOrder = newOrder }));
 }
Ejemplo n.º 20
0
 public Task AddOrder(NewOrderDto order)
 {
     order.PersonId = GetPersonId();
     return(_ordersService.AddOrder(order, HttpContext.RequestAborted));
 }
Ejemplo n.º 21
0
        public async Task <IActionResult> MakeOrderAsync([FromBody] NewOrderDto order)
        {
            var result = await _billingService.MakeOrderAsync(order);

            return(ApiResult(result));
        }
 public CreateOrderCommand(NewOrderDto order)
 {
     Order = order;
 }