Example #1
0
        public void AddOrder(OrderViewModel o, OrderDetailsViewModel d)
        {
            var order   = _mapper.Map <Order>(o);
            var details = _mapper.Map <OrderDetails>(d);

            _ordersRepo.AddOrder(order, details);
        }
        public async Task <IActionResult> SubmitRequest([FromBody] OrderForCreation order)
        {
            if (order?.Equipments == null || !order.Equipments.Any(e => e.Days > 0))
            {
                return(BadRequest());
            }

            var rentals = _rentalService.CreateRentals(order);

            var newOrder = new Entities.Order()
            {
                Rentals = rentals.ToList()
            };

            await _ordersRepository.AddOrder(newOrder);

            if (!await _ordersRepository.SaveAsync())
            {
                var err = new Exception("Adding new order failed on save.");
                Log.Error(err, err.Message);
                throw err;
            }

            return(CreatedAtRoute("GetOrder", new { orderId = newOrder.OrderId }, newOrder.OrderId));
        }
Example #3
0
        //這裡實作的程式碼請叫用對應的 Repository ,並將資料轉換為讓可讓 (前端/Presentation/View) 所使用

        /// <summary>
        /// 新增一筆訂單資料.
        /// </summary>
        /// <param name="orders"></param>
        /// <returns></returns>
        public int AddOrder(OrderViewModel orders)
        {
            Orders order = new Orders()
            {
                CustomerID     = orders.CustomerID,
                EmployeeID     = orders.EmployeeID,
                OrderID        = orders.OrderID,
                Freight        = orders.Freight,
                OrderDate      = orders.OrderDate,
                RequiredDate   = orders.RequiredDate,
                ShipAddress    = orders.ShipAddress,
                ShipCity       = orders.ShipCity,
                ShipCountry    = orders.ShipCountry,
                ShipName       = orders.ShipName,
                ShippedDate    = orders.ShippedDate,
                ShipPostalCode = orders.ShipPostalCode,
                ShipRegion     = orders.ShipRegion,
                ShipVia        = orders.ShipVia,
                ORDER_DETAILS  = (from query in orders.ORDER_DETAILS
                                  select new Order_details()
                {
                    ProductID = query.ProductID,
                    Quantity = query.Quantity,
                    OrderID = query.OrderID,
                    Discount = query.Discount,
                    UnitPrice = query.UnitPrice
                }).ToList()
            };

            return(_Orders.AddOrder(order));
        }
Example #4
0
        public async Task <IActionResult> CreateOrder(
            [FromBody] Models.OrdersForCreation orderToCreate)
        {
            if (orderToCreate == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var orderEntity = _mapper.Map <Orders>(orderToCreate);

            _ordersRepository.AddOrder(orderEntity);

            await _ordersRepository.SaveChanges();

            await _ordersRepository.GetOrder(orderEntity.OrderId);

            return(Ok(CreatedAtRoute("GetOrder",
                                     new { orderId = orderEntity.OrderId },
                                     _mapper.Map <Models.Orders>(orderEntity))));
        }
Example #5
0
        public async Task <IActionResult> CreateOrder(Order order)
        {
            try
            {
                order.Lines = GetCart().Selections.Select(s => new OrderLine
                {
                    ProductId = s.ProductId,
                    Quantity  = s.Quantity,
                    //Product = productRepository.Products.FirstOrDefault(p => p.Id == s.ProductId)
                    Product = s.Product
                }).Where(p => p.ProductId != 0).ToArray();

                IEnumerable <OrderLine> ordersForMessage = GetCart().Selections.Select(s => new OrderLine
                {
                    ProductId = s.ProductId,
                    Quantity  = s.Quantity,
                    //Product = productRepository.Products.FirstOrDefault(p => p.Id == s.ProductId)
                    Product = s.Product
                }).Where(p => p.ProductId != 0).ToArray();

                ordersRepository.AddOrder(order);

                SaveCart(new Cart());
                await SendMessage(order, ordersForMessage);

                return(RedirectToAction("Completed"));
            }
            catch (Exception ex)
            {
                return(View("NotCompleted", ex.Message.ToString()));
            }
        }
        public void handle(ICommand obj)
        {
            switch (obj)
            {
            case CreateOrder co: {
                var order = new Orders(((CreateOrder)obj).OrderID,
                                       new OrderDateType(((CreateOrder)obj).OrderDate),
                                       ((CreateOrder)obj).lineItems
                                       );

                _repo.AddOrder(order);

                IEnumerable <IEvents> allevents = order.GetEvents();
                foreach (var e in allevents)
                {
                    switch (e)
                    {
                    case OrderEvents.OrderPlaced op: {
                        _publisher.PublishEvent(e);
                        break;
                    }
                    }
                }
                break;
            }
            }
        }
Example #7
0
        void IOrderHelper.AddOrder(OrderModel model)
        {
            var adress = model.Client.Name + " " + model.Client.Surname
                         + ";" + model.Client.Street + ";" + model.Client.PostalCode
                         + ";" + model.Client.City;

            var order = new orders
            {
                Id_Client        = model.Client.Id,
                Id_Delivery      = model.selectedDeliveryId,
                Id_Status        = 1,
                ToPay            = model.cart.ComputeTotalValue(),
                AdressToDelivery = adress,
                InsertTime       = DateTime.Now,
            };

            //dodanie nowego zamówienia => przejscie do wypełnienia szczegółów zamówienia
            var orderId = _ordersRepository.AddOrder(order);

            var orderDetails = new List <order_details>();
            var arrayToList  = model.cart.Lines.ToList();

            for (int i = 0; i < arrayToList.Count - 1; i++)
            {
                orderDetails.Add(new order_details
                {
                    Id_Order = orderId,
                    Id_Item  = arrayToList[i].Item.Id,
                    Quantity = arrayToList[i].Quantity
                });
            }

            _ordersRepository.AddOrderDetails(orderDetails);
        }
Example #8
0
        public void AddOrder(OrderViewModel o, string email)
        {
            Order or = new Order();

            or.OrderDate = System.DateTime.Now;
            or.Email     = email;
            _ordersRepo.AddOrder(or);
        }
Example #9
0
        public Guid AddOrder(OrderViewModel order)
        {
            _ordersRepository.AddOrder(_mapper.Map <Order>(order));
            var orders = GetOrders().OrderByDescending(x => x.DatePlaced);
            var list   = orders.ToList();

            return(list.ElementAt(0).Id);
        }
Example #10
0
        public ViewResult ProcessCheckout(Orders order)
        {
            order.Time = DateTime.Now;
            order.Cart = GetCart();

            oRepository.AddOrder(order);

            return(View(order));
        }
Example #11
0
 public IActionResult CreateOrder(Order order)
 {
     order.Lines = GetCart().Selections.Select(s => new OrderLine {
         ProductId = s.ProductId,
         Quantity  = s.Quantity
     }).ToArray();
     ordersRepository.AddOrder(order);
     SaveCart(new Cart());
     return(RedirectToAction(nameof(Completed)));
 }
        public void CheckOut(string email)
        {
            // get a list of products that have been added to the cart for
            // the given email (from db)
            var carts = _cartsRepo.GetCarts().Where(x => x.Email == email);

            // loop within the list of products to check qty from the stock
            // if you find a product with qty > stock - throw new Exeption("Not enough stock") OR!!!!
            // if you find a product with qty > stock - feturn false
            foreach (var cart in carts)
            {
                var product = _productsRepo.GetProduct(cart.Product.Id);

                if (cart.Qty > product.Stock)
                {
                    throw new Exception("Out Of Stock!");
                }
            }

            // 3. create an order
            Guid  orderId = Guid.NewGuid();
            Order o       = new Order();

            o.Id         = orderId;
            o.DatePlaced = DateTime.Now;
            o.UserEmail  = email;

            // Call the AddOrder from inside the IOrdersRepository (3)
            _ordersRepo.AddOrder(o);


            // 4. loop with the list of products and create an OrderDetail for each of the products
            // start loop
            List <OrderDetail> details = new List <OrderDetail>();

            foreach (var cart in carts)
            {
                var product = _productsRepo.GetProduct(cart.Product.Id);

                OrderDetail detail = new OrderDetail();

                detail.OrderFK   = orderId;
                detail.ProductFK = cart.Product.Id;
                detail.Quantity  = cart.Qty;
                detail.Price     = Math.Round(cart.Product.Price * cart.Qty, 2);

                details.Add(detail);

                // deduct qty from stock
                product.Stock -= cart.Qty;
                // end loop
            }
            _ordersRepo.AddOrderDetails(details);
            _cartsRepo.EmptyCart(carts);
        }
Example #13
0
        static void GetNewOrderInput(IOrdersRepository order)
        {
            Random rnd        = new Random();
            int    customerId = rnd.Next(1200000);
            var    _order     = new Orders(customerId);

            order.AddOrder(_order);
            CustomerId = _order.CustomerId;
            var _orderId = order.GetOrderId(CustomerId);

            OrderId = _orderId.OrderId;
        }
Example #14
0
 public IActionResult AddUpdateOrder(Order order)
 {
     order.Lines = order.Lines.Where(l => l.OrderLineId != default(Guid) || (l.OrderLineId == default(Guid) && l.Quantity > 0)).ToArray();
     if (order.OrderId == default(Guid))
     {
         ordersRepository.AddOrder(order);
     }
     else
     {
         ordersRepository.UpdateOrder(order);
     }
     return(RedirectToAction("Index"));
 }
Example #15
0
        public bool AddOrder(List <Guid> shoppingCartItems, string email)
        {
            //makes a new Order
            Order order = new Order();

            order.UserEmail  = email;
            order.DatePlaced = DateTime.Now;

            Guid orderId = _ordersRepository.AddOrder(order);

            //Makes a list with unique Guids from shoppinCartItems list
            List <Guid> filteredShoppingCartItems = new List <Guid>();

            foreach (var item in shoppingCartItems)
            {
                if (!filteredShoppingCartItems.Any(x => x == item))
                {
                    filteredShoppingCartItems.Add(item);
                }
            }
            List <OrderDetails> listOfOrderDetails = new List <OrderDetails>();

            //Fills the OrderDetailsList with OrderDetails
            foreach (var item in filteredShoppingCartItems)
            {
                int    quantity  = shoppingCartItems.Count(x => x == item);
                Guid   ProductFk = item;
                Guid   OrderFk   = orderId;
                double price     = _productsRepository.GetProduct(item).Price *quantity;

                OrderDetails orderDetails = new OrderDetails();
                orderDetails.Quantity  = quantity;
                orderDetails.ProductFK = ProductFk;
                orderDetails.OrderFK   = OrderFk;
                orderDetails.Price     = price;

                listOfOrderDetails.Add(orderDetails);
            }
            //Checks for stock before adding OrderDetails
            if (CheckStock(listOfOrderDetails))
            {
                _orderDetailsRepository.AddOrderDetailsList(listOfOrderDetails);
                return(true);
            }
            else
            {
                //Removes the previously created Order that doesnt have OrderDetails, because of the failed stock check
                _ordersRepository.RemoveOrder(order);
                return(false);
            }
        }
Example #16
0
        public IActionResult AddOrUpdateOrder(Order order)
        {
            order.Lines = order.Lines.Where(l => l.Id > 0 || (l.Id == 0 && l.Quantity > 0)).ToArray();

            if (order.Id == 0)
            {
                ordersRepository.AddOrder(order);
            }
            else
            {
                ordersRepository.UpdateOrder(order);
            }
            return(RedirectToAction(nameof(Index)));
        }
Example #17
0
 public IActionResult AddOrUpdateOrder(Order order)
 {
     order.Lines = order.Lines
                   .Where(l => l.Id > 0 || (l.Id == 0 && l.Quantity > 0)).ToArray(); //lines (exactly - id) already was save in the order
     if (order.Id == 0)
     {
         orderRepository.AddOrder(order);
     }
     else
     {
         orderRepository.UpdateOrder(order);
     }
     return(RedirectToAction(nameof(IndexOrder)));
 }
 public IActionResult AddOrUpdateOrder(Order order)
 {
     // Store only exising lines and lines with quantity > 0
     order.Lines = order.Lines.Where(l => l.Id > 0 || (l.Id == 0 && l.Quantity > 0)).ToList();
     if (order.Id == 0)
     {
         _ordersRepository.AddOrder(order);
     }
     else
     {
         _ordersRepository.UpdateOrder(order);
     }
     return(RedirectToAction(nameof(Index)));
 }
Example #19
0
 public ViewResult ProcessCheckout(Order order)
 {
     if (ModelState.IsValid)
     {
         order.Time = DateTime.Now;
         order.Cart = GetCart();
         oRepository.AddOrder(order);
         return(View(order));
     }
     else
     {
         return(View("Checkout"));
     }
 }
Example #20
0
        public ActionResult AddOrder(OrderCreateDto order)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var orderModel = mapper.Map <Order>(new Order {
                Dimension = order.Dimension, DropOff = order.DropOff, Pickup = order.Pickup, Status = Status.Status1
            });

            ordersRepository.AddOrder(orderModel);
            ordersRepository.SaveChanges();

            return(Ok(orderModel));
        }
Example #21
0
        public async Task <ActionResult <Order> > CreateOrder(
            [FromBody] OrderForCreation orderForCreation)
        {
            // model validation
            if (orderForCreation == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                // return 422 - Unprocessable Entity when validation fails
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            // map model to entity
            var orderEntity = _mapper.Map <Core.Entities.Order>(orderForCreation);

            // get product details
            foreach (var orderItem in orderEntity.Items)
            {
                var productDetail = await _productService.GetProductDetailAsync(orderItem.ProductId);

                if (productDetail == null)
                {
                    // return not found if no details were found
                    return(NotFound());
                }
                orderItem.Name  = productDetail.name;
                orderItem.Price = productDetail.price;
            }

            // add the entity to the repository
            _ordersRepository.AddOrder(orderEntity);

            // save the changes
            await _ordersRepository.SaveChangesAsync();

            // Fetch the order from the data store to include items
            await _ordersRepository.GetOrderAsync(orderEntity.Id);

            // return CreatedAtRoute to include location in header
            return(CreatedAtRoute("GetOrder",
                                  new { id = orderEntity.Id },
                                  _mapper.Map <Order>(orderEntity)));
        }
        public IActionResult PostOrder([FromBody] OrderEntityModel model)
        {
            try
            {
                var newOrder = _mapper.Map <OrderEntityModel, Order>(model);
                CheckDataValidation(newOrder);
                if (!ModelState.IsValid)
                {
                    _logger.LogDebug($"bad request from post order made by : {ModelState} ");
                    return(BadRequest(ModelState));
                }

                var client = _clientsRepo
                             .GetClientById(model.ClientId);

                if (client == null)
                {
                    ModelState.AddModelError("Errors", "Client is not in Data Base");
                    return(BadRequest(ModelState));
                }

                string firsName = client.FirstName.ToUpper();
                string lastName = client.LastName.ToUpper();

                newOrder.OrderNumber =
                    $"{firsName[0]}{lastName.Substring(0, 3)}-{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}";

                newOrder.Client = _clientsRepo
                                  .GetAllClients()
                                  .FirstOrDefault(c => c.Id == model.ClientId);
                _repo.AddOrder(newOrder);
                if (_repo.SaveAll())
                {
                    return(Created($"/api/orders/{newOrder.Id}", _mapper.Map <Order, OrderEntityModel>(newOrder)));
                }
            }
            catch (Exception e)
            {
                _logger.LogError($"Failed to post order: {e}");
            }
            return(BadRequest(("Failed to save new order")));
        }
Example #23
0
        public OrderDto AddOrder(OrderDto orderDto, int userId)
        {
            if (orderDto == null)
            {
                return(null);
            }
            var user = _usersService.GetUserById(userId);

            orderDto.AddingUser    = user;
            orderDto.ExecutingUser = null;
            orderDto.IsDone        = false;
            orderDto.IsPaid        = false;
            orderDto.Content       = null;

            orderDto.Value = CountValue(orderDto);
            var order      = _mapper.Map <Order>(orderDto);
            var addedOrder = _ordersRepository.AddOrder(order);

            return(_mapper.Map <OrderDto>(addedOrder));
        }
        public IActionResult LendGame(ClientViewModel clientData)
        {
            string firstName = clientData.FirstName;
            string lastName  = clientData.LastName;
            string password  = clientData.Password;
            string gameName  = clientData.Game;

            if (_ordersRepository.AddOrder(firstName, lastName, password, gameName))
            {
                ViewBag.ClientName  = firstName + " " + lastName;
                ViewBag.ClientGame  = gameName;
                ViewBag.ClientOrder = "Wypożyczyłeś grę. Dziękujemy.";
            }
            else
            {
                ViewBag.ClientName  = "-";
                ViewBag.ClientGame  = "-";
                ViewBag.ClientOrder = "Niestety nie udało się, sprawdź czy wpisujesz dobre dane!";
            }
            return(View("LentGame"));
        }
Example #25
0
        public void Should_insert_new_order_and_select_it_by_id()
        {
            //Arrange
            var order = new Order()
            {
                CustomerId = "ALFKI",
                EmployeeId = 1,
                ShipVia    = 1,
                ShipName   = "test"
            };

            //Act
            _repo.AddOrder(order);
            var selectedOrder = _repo.GetOrderWithDetailsById((int)_repo.GetLastOrderId());

            //Assert
            Assert.IsTrue(selectedOrder.ShipName == order.ShipName &&
                          order.CustomerId == selectedOrder.CustomerId &&
                          order.EmployeeId == selectedOrder.EmployeeId &&
                          order.ShipVia == selectedOrder.ShipVia);
        }
Example #26
0
        public ActionResult FinalizeOrder(OrderModel orderdetails)                                                                                   //Finalizowanie zamówienia.
        {
            cart = (Cart)Session["cart"];                                                                                                            //Przypisanie koszyka użytkownika.
            bool AnyValueIsNull = orderdetails.DeliveryDetails.GetType().GetProperties().All(p => p.GetValue(orderdetails.DeliveryDetails) != null); //Sprawdza czy wszystkie dane adresowe zostały uzupełnione.

            if (cart.Products.Count() != 0 && AnyValueIsNull == false)                                                                               //Jeżeli koszyk nie jest pusty i wszystkie dane adresowe zostały uzupełnione.
            {
                int id      = ordersRepository.Orders.Select(x => x.Delivery_ID).DefaultIfEmpty().Max() + 1;                                         //ID nowego zamówienia.
                int user_id = (int)Session["ID_User"];                                                                                               //Przypisanie ID użytkownika.
                ordersRepository.AddOrder(user_id, cart.ComputeTotalValue());                                                                        //Dodanie nowego zamówienia.
                foreach (var item in cart.Products)                                                                                                  //Dla każdego produktu w koszyku.
                {
                    orderDetails = new OrderDetails                                                                                                  //Nowy szczegół zamówienia.
                    {
                        Order_ID   = id,
                        Product_ID = item.ProductID,
                        User_ID    = user_id,
                        Quantity   = item.Quantity,
                        Category   = item.Category
                    };
                    productRepository.SellProduct(orderDetails);              //Usuwanie przedmiotu z magazynu.
                    orderDetailsRepository.AddOrderDetail(orderDetails);      //Dodanie nowego szczegółu zamówienia.
                }
                deliveryRepository.AddDelivery(orderdetails.DeliveryDetails); //Dodanie danych adresowych zamówienia.
                Session["cart"] = new Cart();                                 //Wyczyszczenie koszyka.
                return(View("Success"));                                      //Wygenerowanie widoku potwierdzającego złożenie zamówienia.
            }
            else if (AnyValueIsNull == true)                                  //Jeżeli nie wszystkie wartości zostały uzupełnione.
            {
                orderdetails.Cart = cart;                                     //Przypisanie wartości do modelu
                return(View(orderdetails));                                   //Wygenerowanie widoku z przekazaniem modelu.
            }
            else
            {
                return(RedirectToAction("Index", "Home"));   //W każdym innym przypadku.
            }
        }
        public async Task <IActionResult> PostOrder([FromBody] OrderChangeDto orderDto)
        {
            try
            {
                var user = await _userManager.GetUserAsync(User);

                var email = user?.Email;

                if (email != null)
                {
                    var order = _mapper.Map <Order>(orderDto);
                    order.Email = email;

                    await _repository.AddOrder(order);

                    await _repository.Save();

                    return(CreatedAtAction("GetOrder",
                                           new { id = order.Id },
                                           _mapper.Map <OrderDto>(order)));
                }

                return(Unauthorized());
            }
            catch (DbUpdateException e)
            {
                ModelState.AddModelError("database", e.InnerException != null
                    ? e.InnerException.Message
                    : e.Message);
                return(ValidationProblem());
            }
            catch (Exception e)
            {
                return(_helpers.ErrorResponse(e));
            }
        }
Example #28
0
        /*
         * Approach - storing items in cart table in db
         * a) user must be logged in
         * b) in the checkout method you need to fetch list of cart items from db
         *
         */


        public void Checkout(string email)
        {
            //https://stackoverflow.com/a/2180920 Thread fix
            //1. Get a list of products that have been added to the cart for the given email (from the db)
            IList <CartViewModel> cartEntries = _cartsRepo.GetCartEntries(email).ProjectTo <CartViewModel>(_mapper.ConfigurationProvider).ToList <CartViewModel>();

            //2. loop within the list of products to check qty from the stock
            //Stock not showing up on the intellisense so I can't test with it
            foreach (var cart in cartEntries)
            {
                if (cart.Product.Stock < cart.Quantity)
                {
                    throw new Exception("Not enough stock for product " + cart.Product.Name);
                }
                //if you find a product with qty > stock - throw new exception not enough stock
            }

            //3. Create order
            Guid  orderId  = Guid.NewGuid();
            Order newOrder = new Order();

            newOrder.Id         = orderId;
            newOrder.DatePlaced = DateTime.Now;
            newOrder.UserEmail  = email;
            //Contineu setting up other properties

            //Might need to comment to test
            _orderRepo.AddOrder(newOrder);
            //3.1. Call the Addorder from inside the IOrdersRepository (this can be merged with step 3)

            //4. loop with the list of products and create an OrderDetail Instance for each of the products
            //Start of loop
            foreach (var cart in cartEntries)
            {
                //4.1
                //deduct qty from stock
                _productsRepo.EditProductQuantity(_mapper.Map <Product>(cart.Product), cart.Quantity);

                //Create a new OrderDetail
                OrderDetail newOrderDetail = new OrderDetail();
                newOrderDetail.OrderFK   = orderId;
                newOrderDetail.ProductFK = cart.Product.Id;
                newOrderDetail.Price     = (cart.Product.Price);
                newOrderDetail.Quantity  = (cart.Quantity);

                //4.2 Loop Call the add orderDetail from inside the IOrderDetailsRepository (this can be merged with step 4)
                //Might need to comment for testing
                _orderRepo.AddOrderDetail(newOrderDetail);
                //end of loop
            }

            //cartEntries = null;
            //IList<Cart> cartEntriesToDelete = _cartsRepo.GetCartEntries(email).ToList<Cart>();
            //Remove Cart Entries
            foreach (var cart in cartEntries)
            {
                Cart cartToDelete = _mapper.Map <Cart>(cart);
                _cartsRepo.DeleteFromCart(cartToDelete);
            }
            //throw new NotImplementedException();
        }
Example #29
0
        public void AddOrder(OrderViewModel o)
        {
            var newOrder = _mapper.Map <OrderViewModel, Order>(o);

            _repo.AddOrder(newOrder);
        }
Example #30
0
        public void AddOrder(OrderViewModel order)
        {
            var myOrder = _mapper.Map <Order>(order);

            _ordersRepo.AddOrder(myOrder);
        }