コード例 #1
0
        // End Testing ---------------------------------------------------------------------------------------------------------------

        private void InitializeFields()
        {
            var fileMock = new Mock <IFormFile>();
            var content  = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            this.file = fileMock.Object;

            this.orderInputModel = new OrderInputModel
            {
                UserId      = "some userId",
                ServiceId   = 1,
                Description = "Lorem Ipsum is simply dummy text ",
                Documents   = new List <IFormFile>()
                {
                    this.file
                },
            };
        }
コード例 #2
0
        public async Task <ActionResult> DoOrder()
        {
            // sipariş formu açılısında kullanıcı oturum açmış ise bu durumda şuan oturum açan müşteri bilgilerini getir.
            if (User.Identity.IsAuthenticated)
            {
                var authenticatedUser = await _userManager.FindByNameAsync(User.Identity.Name);

                var customer = _custormerRepo.Find(authenticatedUser.Id);

                var model = new OrderInputModel();
                model.CustomerDetail = new CustomerDetailModel
                {
                    FullName    = customer.FullName,
                    ShipAddress = customer.DefaultShippingAddress,
                    CustomerId  = customer.Id,
                    PhoneNumber = customer.PhoneNumber
                };


                return(View(model));
            }


            return(View());
        }
コード例 #3
0
        public async Task <IActionResult> Update(Guid businessId, string orderId, DateTime date,
                                                 [FromBody] OrderInputModel inputModel)
        {
            if (inputModel == null ||
                businessId != inputModel.BusinessId ||
                orderId != inputModel.OrderId ||
                date != inputModel.Date)
            {
                return(BadRequest());
            }

            if (!await orderService.OrderExists(date, businessId, orderId))
            {
                return(NotFound());
            }

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

            var model = ToDomainModel(inputModel);
            await orderService.UpdateOrder(model);

            return(NoContent());
        }
コード例 #4
0
        public IHttpResponse Order(OrderInputModel orderInput)
        {
            if (orderInput.Barcode.Length != 12)
            {
                return(this.Error("Barcode shoud be 12 digits long!"));
            }

            if (orderInput.Quantity < 1)
            {
                return(this.Error("Quantity shoud be possitive number!"));
            }

            int productId = productsService.GetProductId(orderInput.Barcode);

            if (productId == 0)
            {
                return(this.Error("Not existing product barcode!"));
            }

            Guid cashierId = this.GetUserId();

            ordersService.Create(productId, orderInput.Quantity, cashierId);

            return(this.Redirect("/"));
        }
コード例 #5
0
        public ActionResult DoOrder(OrderInputModel model)
        {
            // 1 sipariş düzgün bir şekilde oluşur ise bu bilgileri database gönderip siparişe çevireceğiz ve
            // daha sonrasında kullanıcıya bir mesaj verip sms email filan göndereceğiz.

            // Kredi kartı işlem enum
            // Başarılı 200
            // red 300
            // Limit Yertersiz 500 gibi
            // eğer Başarılı ise Sipariş oluşturma işlemini yapıp kullanıcıya sipariş kodunu dönelim.


            // 2 kredi kartı doğrulmasını yalancıktan yapalım eğer limit yeterli ise ve red verilmediyse sipariş oluşsun ve kullanıcıya ViewBag ile sipariş kodunu göster


            if (ModelState.IsValid)
            {
                var cart = _cartService.GetCart();
                _orderService.DoOrder(cart, model);

                ViewBag.OrderCode   = _orderService.orderCode;
                ViewBag.OrderStatus = _orderService.Status;

                return(View());
            }


            ViewBag.OrderCode   = string.Empty;
            ViewBag.OrderStatus = string.Empty;



            return(View());
        }
コード例 #6
0
        private async Task CreateOrder(string serviceType, OrderInputModel model)
        {
            if (serviceType == "mobile")
            {
                model.MobileServiceInfo = await this.orderService
                                          .CreateAsync <MobileServiceInfoViewModel, OrderViewModel>(
                    new OrderViewModel
                {
                    UserId      = this.User.GetId(),
                    DocumentUrl = await this.uploadService.UploadImageAsync(model.Image),
                },
                    model.MobileServiceInfo);

                await this.orderService.FinishOrderAsync <MobileServiceInfoViewModel>(model.MobileServiceInfo);
            }
            else
            {
                model.FixedServiceInfo = await this.orderService
                                         .CreateAsync <FixedServiceInfiViewModel, OrderViewModel>(
                    new OrderViewModel
                {
                    UserId      = this.User.GetId(),
                    DocumentUrl = await this.uploadService.UploadImageAsync(model.Image),
                },
                    model.FixedServiceInfo);

                await this.tasksService.CreateAsync(model.FixedServiceInfo.OrderId, model.InstalationSlotId);

                await this.context.Clients.All.ReceiveTasksUpdate();
            }
        }
コード例 #7
0
        public async Task <IActionResult> Create(string customerId, string serviceType)
        {
            if (!await this.customerService.ExistAsync(customerId))
            {
                return(this.NotFound());
            }

            var model = new OrderInputModel
            {
                ServiceType = serviceType,
            };

            model.Services = await this.serviceService.GetServiceNamesByTypeAsync <ServiceViewModel>(serviceType);

            if (serviceType == "mobile")
            {
                model.Numbers = await this.numberService.GetFreeNumbersAsync <ServiceNumberViewModel>(serviceType, null);

                model.MobileServiceInfo = new MobileServiceInfoViewModel
                {
                    ICC        = await this.serviceInfoService.GetICCAsync(),
                    CustomerId = customerId,
                };

                return(this.View("Mobile", model));
            }

            model.FixedServiceInfo = new FixedServiceInfiViewModel
            {
                CustomerId = customerId,
            };

            return(this.View("Fixed", model));
        }
コード例 #8
0
        public IActionResult Checkout()
        {
            if (!this.shoppingBagService.AnyProducts(this.User.Identity.Name))
            {
                this.TempData["error"] = ERROR_MESSAGE;
                return(RedirectToAction("Index", "Home"));
            }

            var order   = this.orderService.CreateOrder(this.User.Identity.Name);
            var address = this.adressesService.GetAllAddressByUser(this.User.Identity.Name);

            var viewModel = this.mapper.Map <IList <AddressInputModel> >(address);

            var user     = this.userService.GetUserByUsername(this.User.Identity.Name);
            var fullName = $"{user.FirstName} {user.LastName}";


            var createOrderViewModel = new OrderInputModel
            {
                Addresses   = viewModel.ToList(),
                FullName    = fullName,
                PhoneNumber = user.PhoneNumber
            };

            return(this.View(createOrderViewModel));
        }
コード例 #9
0
        public OrderDto CreateNewOrder(string email, OrderInputModel order)
        {
            var user = _dbContext.Users.FirstOrDefault(u => u.Email == email)
                       ?? throw new ResourceNotFoundException($"User with email {email} not found");

            var address = _dbContext.Addresses.FirstOrDefault(a => a.Id == order.AddressId)
                          ?? throw new ResourceNotFoundException($"Address with Id {order.AddressId} not found");

            var paymentCard = _dbContext.PaymentCards.FirstOrDefault(p => p.Id == order.PaymentCardId)
                              ?? throw new ResourceNotFoundException($"Payment card with Id {order.PaymentCardId} not found");

            var cart = _dbContext.ShoppingCarts.FirstOrDefault(c => c.User.Email == email)
                       ?? throw new ResourceNotFoundException($"No cart for  with {email} was found");

            var cartItems = _dbContext.ShoppingCartItems.Where(ci => ci.ShoppingCartId == cart.Id).ToList();

            if (cartItems.Count == 0)
            {
                throw new ResourceNotFoundException($"Cart is empty");
            }

            var newOrder = CreateOrder(user, address, paymentCard);

            PopulateItemsToOrder(newOrder, cartItems);
            var orderDto = _mapper.Map <OrderDto>(newOrder);

            orderDto.CreditCard = paymentCard.CardNumber;
            return(orderDto);
        }
コード例 #10
0
ファイル: OrderRepository.cs プロジェクト: sjofno17/cryptocop
        public OrderDto CreateNewOrder(string email, OrderInputModel order)
        {
            // Retrieve information for the user with the email passed in
            var user = _dbContext.Users.FirstOrDefault(u => u.Email == email);

            if (user == null)
            {
                throw new Exception("User not found");
            }

            // Retrieve information for the address with the address id passed in
            var address = _dbContext.Addresses.FirstOrDefault(a => a.Id == order.AddressId);
            // Retrieve information for the payment card with the payment card id passed in
            var card         = _dbContext.PaymentCards.FirstOrDefault(c => c.Id == order.PaymentCardId);
            var cardNumber   = card.CardNumber;
            var shoppingCart = _dbContext.ShoppingCarts.FirstOrDefault(s => s.UserId == user.Id);
            var fullName     = user.FullName;

            float totalPrice = 0;

            for (int i = 0; i < shoppingCart.ShoppingCartItems.Count(); i++)
            {
                totalPrice += shoppingCart.ShoppingCartItems[i].UnitPrice * shoppingCart.ShoppingCartItems[i].Quantity;
            }

            // Create a new order where the credit card number has been masked, e.g. ************5555
            var entity = new OrderEntity
            {
                Email            = user.Email,
                FullName         = fullName,
                StreetName       = address.StreetName,
                HouseNumber      = address.HouseNumber,
                ZipCode          = address.ZipCode,
                Country          = address.Country,
                City             = address.City,
                CardHolderName   = card.CardHolderName,
                MaskedCreditCard = PaymentCardHelper.MaskPaymentCard(card.CardNumber),
                OrderDate        = DateTime.Now,
                TotalPrice       = totalPrice
            };

            _dbContext.Orders.Add(entity);
            _dbContext.SaveChanges();

            // Return the order but here the credit card number should not be masked
            return(new OrderDto
            {
                Id = entity.Id,
                FullName = entity.FullName,
                Email = entity.Email,
                StreetName = entity.StreetName,
                HouseNumber = entity.HouseNumber,
                ZipCode = entity.ZipCode,
                Country = entity.Country,
                CardholderName = entity.CardHolderName,
                CreditCard = cardNumber,
                OrderDate = entity.OrderDate.ToString("dd.MM.yyyy"),
                TotalPrice = entity.TotalPrice
            });
        }
コード例 #11
0
        public IActionResult All(OrderInputModel model, int start)
        {
            if (ModelState.IsValid)
            {
                this.ordersService.AddOrder(model.TicketsCount, this.User, model.EventName);

                return(this.Redirect("/"));
            }
            else
            {
                var totalEventsCount =
                    this.eventsService
                    .AllEventsCount();

                var events =
                    this.eventsService
                    .EventsOnOnePage(start);

                var viewModel = new EventsOnPageViewModel
                {
                    Events           = events,
                    Start            = start,
                    TotalEventsCount = totalEventsCount
                };

                return(this.View(viewModel));
            }
        }
コード例 #12
0
        public async Task <IActionResult> Post([FromBody] OrderInputModel orderInputmodel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                foreach (var item in orderInputmodel.Items)
                {
                    var product = await _productService.GetByIdAsync(item.ProductId);

                    product.AvailableProduct -= item.NoOfProduct;

                    if (!await CheckProductAvailablityAsync(item))
                    {
                        return(NotFound(product));
                    }

                    await _productService.UpdateAsync(product);
                }

                var result = await _orderService.AddAsync(orderInputmodel.Map(orderInputmodel));

                return(Ok(result.OrderNumber));
            }
            catch (Exception ex)
            {
                _loggerManager.LogError(ex.StackTrace + ex.Message);
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
コード例 #13
0
ファイル: OrderService.cs プロジェクト: dadisteinn/Cryptocop
        public void CreateNewOrder(string email, OrderInputModel order)
        {
            var dto = _orderRepository.CreateNewOrder(email, order);

            _shoppingCartRepository.DeleteCart(email);
            _queueService.PublishMessage(_routingKey, dto);
        }
コード例 #14
0
        public IActionResult Checkout(OrderInputModel OrderModel)
        {
            var Order = new Order();

            var cart = OrderService.GetCart(this.HttpContext);

            TryUpdateModelAsync(Order);

            try
            {
                // fill out the order with the data from the user
                Order.Username   = User.Identity.Name;
                Order.OrderDate  = DateTime.Now;
                Order.FullName   = OrderModel.FullName;
                Order.Address    = OrderModel.Address;
                Order.City       = OrderModel.City;
                Order.PostalCode = OrderModel.PostalCode;
                Order.Country    = OrderModel.Country;
                Order.Email      = OrderModel.Email;
                Order.Total      = _orderS.GetTotal();

                //Add and save order
                _checkoutS.Add(Order);
                //returns the OrderId, we use that generate the complete page
                int OrderId = cart.CreateOrder(Order);
                //Checkout Complete!
                return(RedirectToAction("Complete", new { id = OrderId }));
            }
            catch
            {
                //invalid, redisplay with errors
                return(View(Order));
            }
        }
コード例 #15
0
        public async Task <ActionResult <Order> > Post(
            [FromServices] DataContext context,
            [FromBody] OrderInputModel model)
        {
            if (ModelState.IsValid)
            {
                List <Product> products = new List <Product>();

                foreach (int id in model.ProductsId)
                {
                    var productRegistered = await context.Products.Where(x => x.Id == id)
                                            .AsNoTracking()
                                            .SingleOrDefaultAsync();

                    if (productRegistered == null)
                    {
                        return(BadRequest());
                    }

                    products.Add(productRegistered);
                }

                Order order = new Order(model.Title, model.Description, products);

                context.Orders.Add(order);
                await context.SaveChangesAsync();

                return(Ok(model));
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
コード例 #16
0
        public OrderDto CreateNewOrder(string email, OrderInputModel order)
        {
            var newOrder = _orderRepository.CreateNewOrder(email, order);

            _shoppingCartRepository.DeleteCart(email);
            _queueService.PublishMessage("create-order", newOrder);
            return(newOrder);
        }
コード例 #17
0
        public IActionResult Order(string coachId)
        {
            var inputModel = new OrderInputModel {
                CoachId = coachId
            };

            return(this.View(inputModel));
        }
コード例 #18
0
        public UpdateOrderCommand BuildUpdateOrderCommand(string id, OrderInputModel model)
        {
            var command = _mapper.Map <UpdateOrderCommand>(model);

            command.OrderId = id;

            return(command);
        }
コード例 #19
0
        public IActionResult AddToWishlist(OrderInputModel input)
        {
            input.ExpirationTime = DateTime.Now.AddDays(90);
            input.UserId         = User.FindFirst(ClaimTypes.Name).Value;

            orderService.AddToWishlist(input);
            return(Ok());
        }
コード例 #20
0
 private void CreateSale(OrderInputModel orderInputModel)
 => manager.PublishSale(new SaleMessage
 {
     SaleDate = DateTime.Now,
     Customer = orderInputModel.Customer,
     Price    = orderInputModel.Price,
     Product  = orderInputModel.Product,
     Quantity = orderInputModel.Quantity
 });
コード例 #21
0
        public IActionResult Post([FromBody] OrderInputModel inputModel)
        {
            var paymentMethod = _paymentMethodService.GetById(inputModel.PaymentMethodId);
            var payment       = _mapper.Map <CreditCard>(inputModel.CreditCard) ?? BankSlip.Create() as Payment;
            var address       = _addressService.GetById(inputModel.AddressId);

            _orderService.ProcessOrder(User.Identity.Name, paymentMethod, payment, address, inputModel.CouponCode);

            return(Ok());
        }
コード例 #22
0
        protected void DeepEqualForOrder(OrderInputModel inputModel, OrderOutputModel expOutputModel)
        {
            Assert.NotNull(expOutputModel.Date);
            Assert.NotNull(expOutputModel.WarehouseName);
            Assert.NotNull(expOutputModel.OrderDetailsOutput);
            var model       = mapper.Map <Order>(inputModel);
            var outputModel = mapper.Map <OrderOutputModel>(model);

            Assert.IsTrue(outputModel.Equals(expOutputModel));
        }
コード例 #23
0
        public IActionResult AddToCart(OrderInputModel input)
        {
            input.ExpirationTime = DateTime.Now.AddDays(30);
            input.UserId         = User.FindFirst(ClaimTypes.Name).Value;

            Console.WriteLine("\n**ADDING TO CART");

            orderService.AddToCart(input);
            return(Ok());
        }
コード例 #24
0
        public async Task <ActionResult <IdField> > Update(string id, [FromBody] OrderInputModel data)
        {
            var command = _commandBuilder.BuildUpdateOrderCommand(id, data);

            var orderId = await _commandDispatcher.ExecuteAsync(command).ConfigureAwait(false);

            return(new IdField {
                Id = orderId
            });
        }
コード例 #25
0
        public string OrderConsole(int id, OrderInputModel input)
        {
            input.GetRequestFromReST();

            StockBO stock = new StockBO(new Herds(HerdBO.GetXmlEntries()), id, input.Request.order.milk, input.Request.order.skins);

            Response.ContentType = "application/json";
            Response.StatusCode  = (int)stock.data[0];
            return((string)stock.data[1]);
        }
コード例 #26
0
        public string OrderConsole(int id, OrderInputModel input)
        {
            input.GetRequestFromReST();

            StockBO stock = new StockBO(new Herds(HerdBO.GetXmlEntries()), id, input.Request.order.milk, input.Request.order.skins);

            Response.ContentType = "application/json";
            Response.StatusCode = (int)stock.data[0];
            return (string)stock.data[1];
        }
コード例 #27
0
        public async Task <ActionResult <IdField> > Create([FromBody] OrderInputModel data)
        {
            var command = _commandBuilder.BuildAddOrderCommand(data);

            var orderId = await _commandDispatcher.ExecuteAsync(command).ConfigureAwait(false);

            return(StatusCode(StatusCodes.Status201Created, new IdField {
                Id = orderId
            }));
        }
コード例 #28
0
        public Order UpdateOrder(OrderInputModel model)
        {
            var order = GetOrderById(model.OrderId);

            order.Address    = model.Address;
            order.ItemOrders = ConvertToItemOrder(model.Items);
            order.PromoCode  = model.PromoCode;
            _db.SaveChanges();
            return(order);
        }
コード例 #29
0
        public ActionResult PostOrder(long id, [FromBody] OrderInputModel input)
        {
            try
            {
                using (_dal)
                {
                    var claim = User.Claims.Where(x => x.Type == ClaimTypes.Sid).FirstOrDefault();
                    if (claim == null)
                    {
                        return(Unauthorized());
                    }
                    var idPlayer = long.Parse(claim.Value);

                    // On récupère la feuille d'ordres ciblée
                    var ordersSheet = (from s in _dal.OrdersSheets
                                       where s.PlayerId == idPlayer && s.Id == id
                                       select s).FirstOrDefault();
                    if (ordersSheet == null)
                    {
                        return(NotFound());
                    }

                    if (ordersSheet.Status != OrdersSheetStatus.Writing)
                    {
                        return(StatusCode((int)HttpStatusCode.PreconditionFailed, "Statut incorrect de la feuille d'ordres"));
                    }

                    var ordersCount = (from o in _dal.Orders
                                       where o.OrdersSheetId == ordersSheet.Id
                                       select 1).Count();
                    if (ordersCount >= ordersSheet.MaxOrdersCount)
                    {
                        return(BadRequest("Nombre d'ordres max atteint"));
                    }

                    var order = new Order()
                    {
                        ActionTypeId  = input.ActionTypeId,
                        OrdersSheetId = ordersSheet.Id,
                        Parameters    = input.Parameters,
                        Rank          = input.Rank,
                        Status        = OrderStatus.None
                    };

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

                    return(Ok(order));
                }
            }
            catch (Exception)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
コード例 #30
0
        // POST api/<controller>
        public OrderModel Post(OrderInputModel model)
        {
            try {
                _orderHelper = new OrderHelper();

                return(_orderHelper.CreateOrder(model));
            }
            catch (Exception ex) {
                return(null);
            }
        }
コード例 #31
0
ファイル: OrderController.cs プロジェクト: sjofno17/cryptocop
        public IActionResult AddOrder([FromBody] OrderInputModel order)
        {
            // Adds a new order associated with the authenticated user, see Models section for reference
            if (!ModelState.IsValid)
            {
                return(BadRequest("Order is not properly constructed!"));
            }

            _orderService.CreateNewOrder(User.Identity.Name, order);
            return(StatusCode(201, order));
        }