Пример #1
0
        public async Task <IActionResult> Edit(int id, int size, decimal price)
        {
            var execRes = new ExecutionResult();

            if (id == 0 || size == 0 || price == 0)
            {
                execRes.AddError("Invalid size or price was given. Please try again.").PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppi = await _context.PizzaPriceInfo.SingleOrDefaultAsync(p => p.Id == id);

            ppi.Size  = size;
            ppi.Price = price;

            _context.PizzaPriceInfo.Update(ppi);
            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess("Price information was successfully updated.");
            }
            else
            {
                execRes.AddError("Database error occured. Price information could not be added.");
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #2
0
        public async Task <ActionResult> Create(string description)
        {
            var execRes = new ExecutionResult();

            if (string.IsNullOrWhiteSpace(description))
            {
                execRes.AddError("Invalid description was given. Please try again.").PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppc = new PizzaPriceCategory {
                Description = description
            };
            await _context.PizzaPriceCategories.AddAsync(ppc);

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess("Price category was successfully added.");
            }
            else
            {
                execRes.AddError("Database error occured. Price category could not be added.");
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #3
0
        public async Task <IActionResult> Add(int id, int size, decimal price)
        {
            var execRes = new ExecutionResult();

            if (id == 0 || size == 0 || price == 0)
            {
                execRes.AddError("Invalid size or price was given. Please try again.").PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppi = new PizzaPriceInfo
            {
                PriceCategoryId = id,
                Price           = price,
                Size            = size
            };

            await _context.PizzaPriceInfo.AddAsync(ppi);

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess("Price information was successfully added.");
            }
            else
            {
                execRes.AddError("Database error occured. Price information could not be added.");
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #4
0
        public async Task <ActionResult> Delete(int?id)
        {
            var execRes = new ExecutionResult();

            if (id == null)
            {
                execRes.AddError("Invalid id was provided. Please try again.").PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppc = await _context.PizzaPriceCategories.SingleAsync(p => p.Id == id);

            _context.PizzaPriceCategories.Remove(ppc);
            try
            {
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddSuccess("Price category was sucessfully removed.");
                }
                else
                {
                    execRes.AddError("Invalid request.");
                }
            }
            catch (DbUpdateException)
            {
                execRes.AddError("Price category is still in use by some pizzas. Make sure to unlink all pizzas before proceeding.");
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #5
0
        public async Task <IActionResult> Remove(int?id)
        {
            var execRes = new ExecutionResult();

            if (id == null)
            {
                execRes.AddError("Invalid id was provided. Please try again.").PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppi = await _context.PizzaPriceInfo.SingleAsync(p => p.Id == id);

            _context.PizzaPriceInfo.Remove(ppi);

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess("Price information was sucessfully removed.");
            }
            else
            {
                execRes.AddError("Invalid request.");
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #6
0
        public async Task <IActionResult> Remove(Guid id)
        {
            var execRes = new ExecutionResult();

            var order = _context.Orders
                        .Where(o => o.Client.Id == User.GetId())
                        .Single(o => o.Id == id);

            if (order != null)
            {
                _context.Orders.Remove(order);
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddSuccess(_localizer["Pizza was successfuly removed from the cart."]);
                }

                else
                {
                    execRes.AddError(_localizer["Pizza was not able to be removed from the cart. Please try again."]);
                }
            }
            else
            {
                execRes.AddError(_localizer["Requested pizza was not found. Please try again."]);
            }

            execRes.PushTo(TempData);
            return(RedirectToAction("Index"));
        }
Пример #7
0
        public async Task ShouldSerializeErrorExtensionsAccordingToOptions()
        {
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            options.Converters.Add(new ExecutionResultJsonConverter(new TestErrorInfoProvider()));

            var executionResult = new ExecutionResult();

            executionResult.AddError(new ExecutionError("An error occurred."));

            var    writer = new DocumentWriter(options);
            string json   = await writer.WriteToStringAsync(executionResult);

            json.ShouldBeCrossPlatJson(@"{
                ""errors"": [{
                    ""message"":""An error occurred."",
                    ""extensions"": {
                        ""violations"": {
                            ""message"":""An error occurred on field Email."",
                            ""field"":""Email""
                        }
                    }
                }]
            }");
        }
Пример #8
0
        public async Task <IActionResult> Create(string id)
        {
            var requestCulture = HttpContext.Features.Get <IRequestCultureFeature>();
            var cultCode       = requestCulture.RequestCulture.UICulture.Name;
            var exRes          = new ExecutionResult();

            if (string.IsNullOrEmpty(id))
            {
                return(RedirectToAction(nameof(Index)));
            }

            var pizza = await _context.Pizzas
                        .SingleOrDefaultAsync(m => m.NameEn == id);

            if (pizza == null)
            {
                exRes.AddError(_localizer["Requested pizza could not be found."]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var prices = _context.PizzaPriceInfo.Where(info => info.PriceCategoryId == pizza.PriceCategoryId);
            var vm     = new OrderCreateViewModel
            {
                ImagePath   = pizza.ImagePath,
                Name        = cultCode == "lt-LT" ? pizza.NameLt : pizza.NameEn,
                Prices      = prices,
                Description = cultCode == "lt-LT" ? pizza.DescriptionLt : pizza.DescriptionEn
            };

            vm.MinPrice = vm.Prices.DefaultIfEmpty(new PizzaPriceInfo()).Min(p => p.Price);
            return(View(vm));
        }
Пример #9
0
        public async Task <IActionResult> Redeem([Bind("Id")] RedeemViewModel model)
        {
            var execRes = new ExecutionResult();

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

            var code = _context.PrepaidCodes.SingleOrDefault(c => c.Id == Guid.Parse(model.Id));

            if (code == null)
            {
                execRes.AddError(_localizer["Provided code doesn't exist."]).PushTo(TempData);
                return(View());
            }
            if (code.RedemptionDate != null)
            {
                execRes.AddError(_localizer["Provided code has already been used."]).PushTo(TempData);
                return(View());
            }

            var user = _context.Users.Single(u => u.Id == User.GetId());

            code.Redeemer       = user ?? throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            code.RedemptionDate = DateTime.Now;

            user.Coins += code.Amount;

            _cache.Remove(user.UserName);

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddInfo(
                    _localizer["Code has been succesfully redeemed. Added {0} to the acccount balance. New balance: {1}!", code.Amount, user.Coins]);
            }
            else
            {
                execRes.AddError(_localizer["Failed to use the code. Try again later."]);
            }

            execRes.PushTo(TempData);
            return(View());
        }
Пример #10
0
        public async Task <IActionResult> Edit(string id, int qty)
        {
            var execRes = new ExecutionResult();
            var order   = _context.Orders.Single(o => o.Id.Equals(Guid.Parse(id)));

            if (order == null || order.ClientId != User.GetId())
            {
                execRes.AddError(_localizer["Pizza you were trying to edit was not found. Please try again."]).PushTo(TempData);
                return(RedirectToAction("Index"));
            }

            if (qty < 1)
            {
                execRes.AddError(_localizer["Quantity must be a positive whole number"]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var oq = order.Quantity;

            if (qty == oq)
            {
                return(RedirectToAction(nameof(Index)));
            }

            order.Quantity = qty;

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess(_localizer["Pizza amount was successfully changed from {0} to {1}.", oq, qty]);
            }
            else
            {
                execRes.AddError(_localizer["Order could not be processed. Please try again."]);
            }

            execRes.PushTo(TempData);
            return(RedirectToAction("Index"));
        }
Пример #11
0
        public async Task <IActionResult> DeleteConfirmed(string id)
        {
            var pizza = await _context.Pizzas.SingleOrDefaultAsync(m => m.NameLt == id);

            _context.Pizzas.Remove(pizza);

            var execRes = new ExecutionResult();

            try
            {
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddSuccess("Pizza deleted successfully.");
                }
                else
                {
                    execRes.AddError("Database error. Pizza was not deleted.");
                }
            }
            catch (DbUpdateException)
            {
                _context.Entry(pizza).State = EntityState.Unchanged;
                pizza.IsDepricated          = true;
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddInfo("Pizza could not be fully deleted. Changed to depricated.");
                }
                else
                {
                    execRes.AddError("Database error. Pizza was not deleted.");
                }
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Пример #12
0
        /// <summary>
        /// Traitement de la commande.
        /// </summary>
        /// <typeparam name="QueryT">Type de la commande.</typeparam>
        /// <typeparam name="ResultT">Type du résultat.</typeparam>
        /// <param name="query">Commande.</param>
        /// <param name="resultAccessor"></param>
        /// <returns>Résultat d'exécution de la commande.</returns>
        private async Task <IWrittableResult <ResultT> > ProcessInternal <QueryT, ResultT>(QueryT query, Func <QueryT, ResultT> resultAccessor)
            where QueryT : IQuery
        {
            try
            {
                // Initialisation du résultat.
                IWrittableResult <ResultT> result = new ExecutionResult <ResultT>();

                // Contrôles des paramètres et du contexte.
                IChecker contextChecker    = new ContextChecker(result);
                IChecker parametersChecker = new ParametersChecker(result);
                query.CheckContext(applicationContext, contextChecker);
                query.CheckParameters(parametersChecker);

                // Contrôle de la possiblité d'exécuter la commande. Si non, on indique que l'exécution a échoué.
                if (result.ValidContext && result.ValidParameters)
                {
                    try
                    {
                        // Exécution de la commande.
                        await query.ExecuteAsync(executionContext, applicationContext);

                        result.SetSucces(true);
                    }
                    catch (Exception error)
                    {
                        result.AddError(error);
                        result.SetSucces(false);
                    }

                    // Si la commande a reussi, affectation du résultat.
                    if (result.Success && query is IQuery <ResultT> )
                    {
                        result.SetResult(resultAccessor(query));
                    }
                }
                else
                {
                    result.SetSucces(false);
                }

                return(result);
            }
            catch (Exception error)
            {
                throw error;
            }
        }
Пример #13
0
        public async Task <IActionResult> Continue(ConfirmCheckoutViewModel model)
        {
            var execRes = new ExecutionResult();

            var clientId = User.GetId();
            var user     = _context.Users.Single(u => u.Id == clientId);

            if (!ModelState.IsValid)
            {
                var requestCulture = HttpContext.Features.Get <IRequestCultureFeature>();
                var cultCode       = requestCulture.RequestCulture.UICulture.Name;
                model.CheckoutList = GetCheckoutOrders(clientId, cultCode);
                model.Price        = model.CheckoutList.Sum(o => o.Price * o.Quantity);

                return(View(model));
            }

            var orders = await _context.Orders.Include(o => o.Pizza)
                         .Where(o => o.Client.Id == clientId)
                         .Where(o => o.Status == OrderStatus.Unpaid)
                         .Where(o => o.PlacementDate > DateTime.Now.AddDays(-7)) // Each item is only valid for 7 days
                         .ToArrayAsync();

            var price = orders.Sum(o => o.Price * o.Quantity);

            if (price > user.Coins)
            {
                // insufficient PizzaCoins
                execRes.AddError(_localizer["Insufficient amount of coins in the balance."]).PushTo(TempData);
                return(RedirectToAction("Index"));
            }

            // looks good, go ahead

            foreach (var checkoutEntry in orders)
            {
                var order = _context.Orders.Single(o => o.Id == checkoutEntry.Id);
                order.Status          = OrderStatus.Queued;
                order.IsPaid          = true;
                order.DeliveryAddress = model.ConfirmAddress;
                order.DeliveryComment = model.Comment;
                order.PaymentDate     = DateTime.Now;
                order.PhoneNumber     = model.PhoneNumber;
            }

            user.Coins -= price;

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess(_localizer["Pizza was ordered successfully."]);
            }
            else
            {
                execRes.AddError(_localizer["Order could not be processed. Please try again."]).PushTo(TempData);
                return(RedirectToAction("Index"));
            }

            if (user.EmailSendUpdates)
            {
                await SendEmail(user, orders.ToArray());

                execRes.AddInfo(_localizer["Email was sent to {0}", user.Email]);
            }

            _cache.Remove(user.UserName);

            execRes.PushTo(TempData);
            return(RedirectToAction("Index", "Order"));
        }
Пример #14
0
        public async Task <IActionResult> Create(string id, OrderCreateViewModel model)
        {
            var execRes = new ExecutionResult();

            var pizza = _context.Pizzas.SingleOrDefault(i => i.NameEn == id);

            if (pizza == null)
            {
                execRes.AddError(_localizer["Requested pizza was not found. Please try again."]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            if (!ModelState.IsValid)
            {
                model.Prices   = _context.PizzaPriceInfo.Where(info => info.PriceCategoryId == pizza.PriceCategoryId);
                model.MinPrice = model.Prices.Min(p => p.Price);
                return(View(model));
            }

            if (pizza.IsDepricated)
            {
                execRes.AddError(_localizer["Pizza no longer exists. Please try another pizza."]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppi = _context.PizzaPriceInfo.SingleOrDefault(g => g.Id == model.SizeId);

            if (ppi == null || pizza.PriceCategoryId != ppi.PriceCategoryId)
            {
                execRes.AddError(_localizer["Unexpected size was selected. Please try again."]).PushTo(TempData);
                return(RedirectToAction(nameof(Create), new { Id = id }));
            }

            var userId = User.GetId();

            if (string.IsNullOrEmpty(userId))
            {
                execRes.AddError(_localizer["You are logged out. Please log in to add the order."]).PushTo(TempData);
                return(RedirectToAction(nameof(Create), new { Id = id }));
            }

            // Check if there is an order in the basket already
            var order = await _context.Orders.SingleOrDefaultAsync(o => !o.IsPaid && o.PizzaId == pizza.Id && o.ClientId == userId && o.Size == ppi.Size);

            if (order != null)
            {
                order.Price         = ppi.Price;
                order.Quantity     += model.Quantity;
                order.PlacementDate = DateTime.Now;
                // Adds a new line to the comment with the new comment.
                order.CookingComment = string.IsNullOrEmpty(order.CookingComment)
                    ? model.Comment : string.IsNullOrEmpty(model.Comment)
                        ? order.CookingComment : $"{order.CookingComment}\n-----\n{model.Comment}";
            }
            else
            {
                order = new Order
                {
                    Id             = Guid.NewGuid(),
                    Pizza          = pizza,
                    ClientId       = userId,
                    CookingComment = model.Comment,
                    Quantity       = model.Quantity,
                    Price          = ppi.Price,
                    Size           = ppi.Size,
                    PlacementDate  = DateTime.Now
                };
                _context.Add(order);
            }

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddInfo(_localizer["Pizza was succesfully added to the cart."]);
            }
            else
            {
                execRes.AddError(_localizer["Pizza could not be added to the cart. Please try again."]);
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }