public async Task <IActionResult> Create(OrderCreateInputModel input)
        {
            if (!this.ModelState.IsValid)
            {
                input = this.ordersService.LoadOrderCreateInputModel(input.Id);
                return(this.View(input));
            }

            // var priceIn = this.financeService.GetAmount(input.OrderFromCurrencyId, input.OrderFromPriceNetIn);
            // var priceOut = this.financeService.GetAmount(input.CurrencyOutId, input.PriceNetOut);
            // var margin = priceIn - priceOut;
            // var fromCurrencyId = this.currencies.AllAsNoTracking().FirstOrDefault(c => c.Name == CurrencyCodes.EUR.ToString()).Id;

            //// if (priceIn < this.financeService.GetAmount(fromCurrencyId, GlobalConstants.SmallOrderMaxAmount) &&
            ////    margin < this.financeService.GetAmount(fromCurrencyId, GlobalConstants.SmallOrderMinMargin))
            //// {
            ////    this.ModelState.AddModelError(string.Empty, "The order margin for order under 500€ cannot be less than 25€.");
            ////    input = this.ordersService.LoadOrderCreateInputModel(input.Id);
            ////    return this.View(input);
            //// }
            // var minMarginPer = priceIn * GlobalConstants.MinOrderMargin;

            // if (margin < minMarginPer)
            // {
            //    this.ModelState.AddModelError(string.Empty, "The order margin cannot be less than 5%.");
            //    input = this.ordersService.LoadOrderCreateInputModel(input.Id);
            //    return this.View(input);
            // }
            await this.ordersService.CreateAsync(input);

            this.notyfService.Success(this.localizer["Order carrier found."]);
            return(this.Redirect(@$ "/Orders/GenerateApplication/{input.Id}"));
        }
        public async Task CreateUproccessedOrder_ThrowsException_WhenShoppingCartIsEmptyOrNull()
        {
            MapperInitializer.InitializeMapper();
            var context                   = ApplicationDbContextInMemoryFactory.InitializeContext();
            var orderRepository           = new EfDeletableEntityRepository <Order>(context);
            var userTestSeeder            = new UserTestSeeder();
            var shoppingCartProductSeeder = new ShoppingCartProductSeeder();

            //seed user
            await userTestSeeder.SeedUsersWithAddressesAsync(context);

            var userWithoutProducts = context.Users.First(x => x.UserName == "UserWithoutAddresses");

            var orderCreateInputModel = new OrderCreateInputModel()
            {
            };

            var orderService = this.GetOrderService(orderRepository, context);

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await orderService.CreateUproccessedOrder(orderCreateInputModel, null);
            });

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await orderService.CreateUproccessedOrder(orderCreateInputModel, userWithoutProducts.ShoppingCart.Id);
            });
        }
        private async Task OrderSubmitted(OrderCreateInputModel model)
        {
            var bus = WebApiApplication.Bus;

            model.CartId = Guid.Parse(model.UserId.Replace("Default", "").Replace("StorefrontAU", ""));
            await bus.Publish <IOrderSubmitted>(model);
        }
Beispiel #4
0
        public async Task <OrderCreateViewModel> CreateAsync(OrderCreateInputModel orderFromView, string username, ModelStateDictionary modelState)
        {
            if (!modelState.IsValid)
            {
                var errorModel = await this.customersService.GetByIdAsync <OrderCreateViewModel>(orderFromView.CustomerId);

                errorModel.IsExpress             = orderFromView.IsExpress;
                errorModel.HasFlavor             = orderFromView.HasFlavor;
                errorModel.ItemQuantitySetByUser = orderFromView.ItemQuantitySetByUser;
                return(errorModel);
            }

            var hasAnyCustomerWithId = await this.customersService.IsCustomerExistAsync(orderFromView.CustomerId);

            // If customer with Id NOT exists return existing view model
            if (!hasAnyCustomerWithId)
            {
                throw new ArgumentNullException(nameof(orderFromView.CustomerId), string.Format(OrderConstants.NullReferenceCustomerId, orderFromView.CustomerId));
            }

            var orderToDb = orderFromView.To <Order>();

            orderToDb.StatusId = await this.orderStatusService.GetIdByNameAsync(OrderConstants.StatusPickUpArrangeDayWaiting);

            orderToDb.CreatorId = await this.employeesService.GetIdByUserNameAsync(username);

            await this.orderRepository.AddAsync(orderToDb);

            await this.orderRepository.SaveChangesAsync();

            return(orderToDb.To <OrderCreateViewModel>());
        }
        public IActionResult Create(OrderCreateInputModel orderCreateInputModel)
        {
            string userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            OrderServiceModel orderServiceModel = AutoMapper.Mapper.Map <OrderServiceModel>(orderCreateInputModel);

            this.orderService.Create(orderServiceModel, userId);

            return(Redirect("/Order/Details"));
        }
        public async Task <IHttpActionResult> OrderCreated([FromBody] OrderCreateInputModel model)
        {
            if (!ModelState.IsValid)
            {
                return(InternalServerError(new Exception("Model is not valid")));
            }

            await OrderSubmitted(model);

            return(Ok());
        }
Beispiel #7
0
        public async Task <IActionResult> Create(OrderCreateInputModel orederCreate)
        {
            var userName = this.User.Identity.Name;
            var result   = await this.ordersService.CreateAsync(orederCreate, userName, this.ModelState);

            if (!this.ModelState.IsValid)
            {
                return(this.View(result));
            }

            return(this.Redirect($"/{GlobalConstants.AreaAdministrationName}/{GlobalConstants.ContollerCustomersName}"));
        }
Beispiel #8
0
        public async Task <IActionResult> Create(int id)
        {
            var user = await this.userManager.GetUserAsync(this.User);

            var products = this.productsService.GetAll <ProductDropDownViewModel>(user.Id).ToList();


            var viewModel = new OrderCreateInputModel
            {
                CustomerId = id,
                Products   = products,
            };

            return(View(viewModel));
        }
Beispiel #9
0
        public async Task <string> CreateAsync(OrderCreateInputModel input)
        {
            var order = this.orders.All().FirstOrDefault(o => o.Id == input.Id);

            order.DueDaysTo = input.DueDaysTo;
            input.OrderTos.Select(ot => ot.CarrierOrderCompanyId)
            .Distinct()
            .ToList()
            .ForEach(id =>
            {
                order.CarrierOrders.Add(new CarrierOrder {
                    CompanyId = id, OrderTos = new List <OrderTo>()
                });
            });

            foreach (var orderToInput in input.OrderTos)
            {
                var vehicle = this.vehicles.All().FirstOrDefault(v => v.Id == orderToInput.VehicleId);
                if (!string.IsNullOrWhiteSpace(orderToInput.VehicleTrailerId))
                {
                    vehicle.TrailerId = orderToInput.VehicleTrailerId;
                    await this.vehicles.SaveChangesAsync();
                }

                var orderTo = order.OrderTos.FirstOrDefault(o => o.Id == orderToInput.Id);
                orderTo.PriceNetOut   = orderToInput.PriceNetOut;
                orderTo.CurrencyOutId = orderToInput.CurrencyOutId;
                orderTo.ContactId     = orderToInput.ContactId;
                orderTo.VehicleId     = orderToInput.VehicleId;
                orderTo.TypeId        = null;

                orderTo.AdminId = order.AdminId;
                orderTo.Drivers.Add(new DriverOrder {
                    OrderId = orderTo.Id, DriverId = orderToInput.DriverId,
                });
                var carrierOrder = order.CarrierOrders.FirstOrDefault(co => co.CompanyId == orderToInput.CarrierOrderCompanyId);
                carrierOrder.OrderTos.Add(orderTo);
                await this.carrierOrders.SaveChangesAsync();

                carrierOrder.AdminId = order.AdminId;
            }

            await this.orders.SaveChangesAsync();

            await this.UpdateOrderStatus(order.Id, OrderStatusNames.Ready.ToString());

            return(order.Id);
        }
Beispiel #10
0
        public async Task <IActionResult> CreateOrder(OrderCreateInputModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.RedirectToAction(
                           nameof(this.CreateOrder),
                           new { id = model.ProductId }));
            }

            string userId  = this.userManager.GetUserId(this.User);
            string orderId = await this.orderService.CreateAsync(model.ProductId, userId, model.Quantity);

            await this.shoppingCartService.AddOrderAsync(userId, orderId);

            return(this.RedirectToHome());
        }
Beispiel #11
0
        public async Task <Uri> CreateUriForPayment(OrderCreateInputModel inputModel)
        {
            var options = paypalOptions.CurrentValue;
            PayPalEnvironment environment = CreateEnvironment();
            var client = new PayPalHttpClient(environment);

            var payment = new OrderRequest()
            {
                CheckoutPaymentIntent = "CAPTURE",
                PurchaseUnits         = new List <PurchaseUnitRequest>()
                {
                    new PurchaseUnitRequest()
                    {
                        CustomId            = inputModel.OrderId.ToString(),
                        Description         = inputModel.Description,
                        AmountWithBreakdown = new AmountWithBreakdown()
                        {
                            CurrencyCode = inputModel.Price.Currency.ToString(),
                            Value        = inputModel.Price.Amount.ToString(CultureInfo.InvariantCulture)
                        }
                    }
                },
                ApplicationContext = CreateApplicationContext()
            };

            //https://developer.paypal.com/docs/api/orders/v2/#orders_create
            var request = new OrdersCreateRequest();

            request.Prefer("return=representation");
            request.RequestBody(payment);

            try
            {
                var response = await client.Execute(request);

                var statusCode = response.StatusCode;
                var result     = response.Result <Order>();
                return(new Uri(result.Links.Single(l => l.Rel == "approve").Href));
            }
            catch (HttpException httpException)
            {
                var statusCode = httpException.StatusCode;
                var debugId    = httpException.Headers.GetValues("PayPal-Debug-Id").FirstOrDefault();
                logger.LogError($"Il tentativo di reindirizzare l'utente alla pagina di pagamento è fallito con status code {statusCode} e debugId {debugId}");
                throw new PaymentException();
            }
        }
Beispiel #12
0
        public async Task CreateUproccessedOrder(OrderCreateInputModel orderCreateInputModel, string shoppingCartId)
        {
            var shoppingCartProducts = await this.shoppingCartProductsService.GetAllProductsAsync <ShoppingCartProductInputModel>(shoppingCartId);

            if (shoppingCartProducts == null || shoppingCartProducts.Count() == 0)
            {
                throw new ArgumentNullException("ShoppingCartId was null or empty");
            }


            decimal totalPrice    = 0m;
            decimal deliveryPrice = 0m;

            var order = orderCreateInputModel.To <Order>();

            await this.orderRepository.AddAsync(order);


            foreach (var product in shoppingCartProducts)
            {
                order.OrderProducts.Add(new OrderProduct()
                {
                    OrderId   = order.Id,
                    ProductId = product.ProductId,
                    Quantity  = product.Quantity
                });
            }

            totalPrice = shoppingCartProducts.Sum(x => x.Quantity * x.ProductPrice);

            if (orderCreateInputModel.PromoCodeId != null)
            {
                totalPrice = await this.promoCodeService.DeductPercentageFromPrice(totalPrice, orderCreateInputModel.PromoCodeId);
            }

            deliveryPrice = totalPrice >= 20m ? 0m : 3.5m;

            order.OrderStatus   = OrderStatus.UnProccessed;
            order.DeliveryPrice = deliveryPrice;
            order.TotalPrice    = totalPrice + deliveryPrice;
            order.OrderDate     = DateTime.UtcNow;

            await this.shoppingCartProductsService.DeleteAll(shoppingCartId);

            await this.orderRepository.SaveChangesAsync();
        }
        public IActionResult Index()
        {
            ViewData["Title"] = "Paga l'ordine";
            //Mostriamo alcuni dati fittizi nell'interfaccia per consentire la modifica dell'id dell'ordine e dell'importo
            //In un'applicazione reale, questi valori arrivano dal database e per nessun motivo dovrebbero essere modificati dall'utente
            var inputModel = new OrderCreateInputModel
            {
                OrderId     = 123456,
                Description = "Ordine merce",
                Price       = new Money
                {
                    Amount   = 11.00m,
                    Currency = Currency.EUR
                }
            };

            return(View(inputModel));
        }
Beispiel #14
0
        public async Task <IActionResult> Create(OrderCreateInputModel inputModel)
        {
            if (!ModelState.IsValid)
            {
                return(this.View(inputModel));
            }

            var user = await this.userManager.GetUserAsync(HttpContext.User);

            var result = await this.orderService.Create(user, inputModel.Phone, inputModel.ShippingAddress);

            if (!result)
            {
                //to do
                return(this.Redirect("/"));
            }

            return(this.RedirectToAction(nameof(SuccessfulOrder)));
        }
        public async Task CreateUnproccessedOrder_RemovesProductsFromShoppingCart_ProperlyCreatesAnOrderWithTheProducts()
        {
            MapperInitializer.InitializeMapper();
            var context                   = ApplicationDbContextInMemoryFactory.InitializeContext();
            var orderRepository           = new EfDeletableEntityRepository <Order>(context);
            var userTestSeeder            = new UserTestSeeder();
            var shoppingCartProductSeeder = new ShoppingCartProductSeeder();
            var productsTestSeeder        = new ProductsTestSeeder();

            //seed products
            await productsTestSeeder.SeedProducts(context);

            //seed users
            await userTestSeeder.SeedUsersWithAddressesAsync(context);

            var userWithProducts = context.Users.First(x => x.UserName == "UserWithoutAddresses");

            //seed products in shoppingCart for user
            await shoppingCartProductSeeder.SeedProductsToUser(context, userWithProducts);

            var orderCreateInputModel = new OrderCreateInputModel()
            {
                UserId = userWithProducts.Id,
            };

            var orderService = this.GetOrderService(orderRepository, context);

            await orderService.CreateUproccessedOrder(orderCreateInputModel, userWithProducts.ShoppingCart.Id);

            var actualShoppingCartCount = userWithProducts.ShoppingCart.ShoppingCartProducts.Count();
            var actualOrderCount        = context.Orders.Count();
            var order = context.Orders.FirstOrDefault();

            var deliveryPrice = userWithProducts.ShoppingCart.ShoppingCartProducts.Sum(x => x.Quantity * x.Product.Price) >= 20m ? 0m : 3.5m;
            var totalPrice    = userWithProducts.ShoppingCart.ShoppingCartProducts.Sum(x => x.Quantity * x.Product.Price) + deliveryPrice;

            Assert.Equal(OrderStatus.UnProccessed, order.OrderStatus);
            Assert.Equal(deliveryPrice, order.DeliveryPrice);
            Assert.Equal(totalPrice, order.TotalPrice);
            Assert.Equal(0, actualShoppingCartCount);
            Assert.Equal(1, actualOrderCount);
        }
        public IActionResult Create(OrderCreateInputModel orderCreateInputModel)
        {
            string username = this.User.FindFirst(ClaimTypes.Name).Value;

            if (!this.ModelState.IsValid)
            {
                return(RedirectToAction("Create"));
            }


            var isCreated = this.orderService.CreateOrder(username, orderCreateInputModel.SupplierId, orderCreateInputModel.DeliveryType, orderCreateInputModel.AddressId);

            if (!isCreated)
            {
                this.TempData["error"] = WebConstants.ErrorOrderMessage;
                return(this.RedirectToAction("Create"));
            }

            return(this.RedirectToAction("Successfully"));
        }
Beispiel #17
0
        public async Task <IActionResult> Create(OrderCreateInputModel input)
        {
            var user = await this.userManager.GetUserAsync(this.User);

            var products = this.productsService.GetAll <ProductDropDownViewModel>(user.Id).ToList();
            var product  = this.productsService.GetById <ProductViewModel>(input.ProductId);

            if (product.Quantity < input.Quantity)
            {
                ModelState.AddModelError("", $"You cannot add {input.Quantity} because in your storage has only {product.Quantity}");
            }

            if (!ModelState.IsValid)
            {
                input.Products = products;

                return(this.View(input));
            }


            await this.ordersService.CreateOrder(input.CustomerId, input.ProductId, input.Quantity);

            return(this.RedirectToAction("Index", "Customers"));
        }
        public async Task <IActionResult> Index(OrderCreateInputModel inputModel, [FromServices] IPaymentService paymentService)
        {
            Uri url = await paymentService.CreateUriForPayment(inputModel);

            return(Redirect(url.ToString()));
        }