public async Task GetByIdAsync_WithExistentId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ShoppingListService GetByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var shoppingListRepository = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService    = new ShoppingListService(shoppingListRepository);
            var existentId             = shoppingListRepository.All().First().Id;

            // Act
            var actualResult = await shoppingListService.GetByIdAsync(existentId);

            var expectedResult = (await shoppingListRepository
                                  .All()
                                  .SingleOrDefaultAsync(x => x.Id == existentId))
                                 .To <ShoppingListServiceModel>();

            // Assert
            Assert.True(actualResult.Id == expectedResult.Id, errorMessagePrefix + " " + "Id is not returned properly.");
            Assert.True(actualResult.Ingredients == expectedResult.Ingredients, errorMessagePrefix + " " + "Ingredients are not returned properly.");
            Assert.True(actualResult.RecipeId == expectedResult.RecipeId, errorMessagePrefix + " " + "RecipeId is not returned properly.");
        }
Exemplo n.º 2
0
        // GET: User/Lists
        public ActionResult Lists()
        {
            if (Session["UserId"] != null)
            {
                ViewBag.Message = TempData["SuccessMessage"];
                ViewBag.Error   = TempData["ErrorMessage"];

                //TODO: Logic to show all lists of a user
                int userId = int.Parse(Session["UserId"].ToString());

                ShoppingListService listService = new ShoppingListService();
                var listOfLists = listService.GetListsByUserId(userId).OrderByDescending(x => x.TimeStamp).ToList();

                if (listOfLists.Count() == 0)
                {
                    ViewBag.Message = "You don't have any lists yet. Start creating your lists now!";
                }

                ListsVM lists = new ListsVM
                {
                    AllUserLists = listOfLists
                };

                return(View(lists));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }
        public async Task EditAsync_WithCorrectData_ShouldSuccessfullyEdit()
        {
            var errorMessagePrefix = "ShoppingListService EditAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var shoppingListRepository   = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService      = new ShoppingListService(shoppingListRepository);
            var shoppingListServiceModel = shoppingListRepository
                                           .All()
                                           .First()
                                           .To <ShoppingListServiceModel>();
            var shoppingListId = shoppingListServiceModel.Id;
            var newValue       = "New Ingredients";

            shoppingListServiceModel.Ingredients = newValue;

            // Act
            await shoppingListService.EditAsync(shoppingListId, shoppingListServiceModel);

            var actualResult  = shoppingListRepository.All().First();
            var expectedValue = newValue;

            // Assert
            Assert.True(actualResult.Ingredients == expectedValue, errorMessagePrefix + " " + "Ingredients are not returned properly.");
        }
Exemplo n.º 4
0
        public ActionResult CreateList(FormCollection collection)
        {
            try
            {
                var name = collection["listname"];

                if (name == null || name == "")
                {
                    throw new Exception("Name cannot be null.");
                }

                var sessionUserId = Session["UserId"];
                int userid        = int.Parse(sessionUserId.ToString());

                ShoppingListDto list = new ShoppingListDto
                {
                    Name             = name,
                    Path             = "somerandomPath",
                    ListAccessTypeId = 1, //Default owner when creating
                    UserId           = userid,
                    ChosenSortingId  = null
                };

                ShoppingListService listService = new ShoppingListService();
                listService.Create(list);

                TempData["SuccessMessage"] = "You successfully created a new shopping list!";
                return(RedirectToAction("Lists"));
            }
            catch (Exception)
            {
                TempData["ErrorMessage"] = "Something went wrong. Make sure to have entered a valid list name. Try again!";
                return(RedirectToAction("Lists"));
            }
        }
        public async void ItemClicked(SelectableShoppingListItem item, bool skipSleep = false)
        {
            SelectedItem = item;
            if (!item.Item.IsChecked)
            {
                ModalMeasurementType = item.Item.Measurement.MeasurementType;
                ModalRequiredAmount  = item.Item.Measurement.UnitQuantityTypeVolume * item.Item.Amount;
                var options = await ShoppingListService.GetMeasurementsForProduct(item.Item.ProductId);

                MeasurementOptions = options.Select(m => new SelectableMeasurement(m)).ToList();
                SelectModal.MeasurementsOptions = options.Select(m => new SelectableMeasurement(m)).ToList();
                SelectedItemId = item.Item.Id;
                SelectModal.Show();
                return;
            }
            SelectedItem.Item.IsChecked = !SelectedItem.Item.IsChecked;
            await ShoppingListService.UpdateCheckedForItem(SelectedItem.Item.Id, SelectedItem.Item.IsChecked);

            if (true)
            {
                StateHasChanged();
                await Task.Run(() => System.Threading.Thread.Sleep(80));
            }
            await Refresh();
        }
        public void TestGetIncludeListItems()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListGetId, true, false)).Returns(
                new ShoppingList
            {
                Id        = shoppingListGetId, Title = "Test list to get", CreatorId = userIds[0], CreatedDate = DateTime.Now,
                ListItems = new List <ListItem>()
                {
                    new ListItem {
                        Description = "Test list item 1", ShoppingListId = shoppingListGetId, CreatorId = userIds[0], CreatedDate = DateTime.Now
                    },
                    new ListItem {
                        Description = "Test list item 2", ShoppingListId = shoppingListGetId, CreatorId = userIds[0], CreatedDate = DateTime.Now
                    }
                }
            }
                );
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListGetId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListGetId, userIds[0], includeListItems: true);

            Assert.AreEqual(2, shoppingList.ListItems.Count());
        }
Exemplo n.º 7
0
        public ActionResult RenameList(FormCollection collection)
        {
            try
            {
                var newName = collection["ListName"];
                int listId  = int.Parse(collection["ShoppingList_Id"]);

                ShoppingListService listService = new ShoppingListService();
                var dbList = listService.Get(listId);

                if (newName == dbList.Name)
                {
                    throw new Exception("The name of the list is unchanged.");
                }

                ShoppingListDto list = new ShoppingListDto
                {
                    Id   = listId,
                    Name = newName
                };

                listService.Update(list);

                TempData["SuccessMessage"] = "The list's name was successfully updated!";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
            catch
            {
                TempData["ErrorMessage"] = "Updating the list's name wasn't successful.";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
Exemplo n.º 8
0
        public ActionResult DeleteList(FormCollection collection)
        {
            try
            {
                int listId = int.Parse(collection["ShoppingList_Id"].ToString());

                ShoppingListService listService     = new ShoppingListService();
                LanguageService     languageService = new LanguageService();
                var langId = languageService.GetByCode(Session["LanguageCode"].ToString()).Id;

                //TO DO: delete all related entries (ShoppingListEntry)
                ProductService productService = new ProductService();
                var            listEntries    = productService.GetEntriesAsProducts(listId, langId);

                foreach (ProductDto product in listEntries)
                {
                    DeleteItem(product.Id, listId);
                }

                //delete ListSorting
                UserListSortingService listSortingService = new UserListSortingService();
                listSortingService.Delete((int)listService.Get(listId).ChosenSortingId);

                //delete list itself & all links in LinkUserToList
                listService.Delete(listId);

                TempData["SuccessMessage"] = "The list was successfully deleted.";
                return(RedirectToAction("Lists"));
            }
            catch
            {
                TempData["ErrorMessage"] = "Deleting the list wasn't successful. Try again.";
                return(RedirectToAction("Lists"));
            }
        }
Exemplo n.º 9
0
 public ActionResult ShareList(FormCollection collection)
 {
     try
     {
         var             emailAddress    = collection["EmailAddress"];
         var             type            = int.Parse(collection["Type"]);
         var             listId          = int.Parse(collection["ShoppingList_Id"]);
         UserService     userService     = new UserService();
         var             userId          = userService.GetIdByEmail(emailAddress);
         ShoppingListDto shoppingListDto = new ShoppingListDto
         {
             UserId           = userId,
             Id               = listId,
             ListAccessTypeId = type
         };
         ShoppingListService listService = new ShoppingListService();
         listService.CreateLink(shoppingListDto);
         TempData["SuccessMessage"] = "You successfully shared your list!";
         return(RedirectToAction("SingleList", new { @id = listId }));
     }
     catch
     {
         var listId = int.Parse(collection["ShoppingList_Id"]);
         TempData["ErrorMessage"] = "An error occured and your list hasn't been shared.";
         return(RedirectToAction("SingleList", new { @id = listId }));
     }
 }
Exemplo n.º 10
0
        public void Initialize()
        {
            myShoopingListAdapter = Substitute.For <IShoppingListDataAdapter>();
            myProductAdapter      = Substitute.For <IProductDataAdapter>();
            myRecipeAdapter       = Substitute.For <IRecipeDataAdapter>();

            myService = new ShoppingListService(myShoopingListAdapter, myProductAdapter, myRecipeAdapter);
        }
        public async Task Refresh()
        {
            var items = await ShoppingListService.GetShoppingListToShopItems();

            ListItems          = items.Select(i => new SelectableShoppingListItem(i)).ToList();
            UnCheckedListItems = ListItems.Where(li => !li.Item.IsChecked).ToList();
            CheckedListItems   = ListItems.Where(li => li.Item.IsChecked).ToList();
            StateHasChanged();
        }
Exemplo n.º 12
0
        // GET: ShoppingList
        public ActionResult Index()
        {
            IndexViewModel vm = new IndexViewModel
            {
                Customers = ShoppingListService.GetCustomerSelectViewModel()
            };

            return(View(vm));
        }
 private async void HandleAddToCart(BaseMeasurement measurement)
 {
     await ShoppingListService.AddToShoppingList(Guid.Empty, new PunterHomeDomain.ApiModels.AddProductToShoppingListRequest
     {
         MeasurementAmount = Convert.ToInt32(measurement.UnitQuantityTypeVolume),
         MeasurementType   = measurement.MeasurementType,
         ProductId         = ProductId,
         Reason            = Enums.EShoppingListReason.Manual
     });
 }
Exemplo n.º 14
0
        // GET: ShoppingList
        public ActionResult Index()
        {
            ShoppingListService service = new ShoppingListService();

            IndexViewModel vm = new IndexViewModel
            {
                Customers = service.GetItems()
            };

            return(View(vm));
        }
        public void TestGetEntityNotFound()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListNotExistingId, false, false)).Returns <ShoppingList>(null);
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListNotExistingId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListNotExistingId, userIds[0]); // Should throw EntityNotFoundException.
        }
        public async void ModalOnConfirm()
        {
            SelectModal.Hide();

            // do some
            ShoppingListService.AddMeasurementsToShoppingItem(SelectModal.MeasurementsOptions, SelectedItemId);

            SelectedItem.Item.IsChecked = !SelectedItem.Item.IsChecked;
            await ShoppingListService.UpdateCheckedForItem(SelectedItem.Item.Id, SelectedItem.Item.IsChecked);

            if (true)
            {
                StateHasChanged();
                await Task.Run(() => System.Threading.Thread.Sleep(80));
            }
            await Refresh();
        }
        public async Task GetByIdAsync_WithNonExistentId_ShouldThrowArgumentNullException()
        {
            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();
            var shoppingListRepository = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService    = new ShoppingListService(shoppingListRepository);
            var nonExistentId          = Guid.NewGuid().ToString();

            // Act

            // Assert
            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await shoppingListService.GetByIdAsync(nonExistentId);
            });
        }
Exemplo n.º 18
0
        // GET: List/Item/Delete/5
        public ActionResult DeleteItem(int id, int listId)  //id = productId
        {
            //try
            //{
            //1. If UserProduct -> Delete
            ProductService productService = new ProductService();
            var            prodType       = productService.GetProductTypeId(id);

            if (prodType == 4)     //one-time UserProduct
            {
                var userProdId = productService.GetUserProductId(id);
                productService.DeleteUserProduct(userProdId);
            }

            //2. Update Sorting without this item
            LanguageService        languageService    = new LanguageService();
            var                    listEntries        = productService.GetEntriesAsProducts(listId, languageService.GetByCode(Session["LanguageCode"].ToString()).Id);
            UserListSortingService listSortingService = new UserListSortingService();
            ShoppingListService    listService        = new ShoppingListService();
            var                    sortingId          = listService.Get(listId, int.Parse(Session["UserId"].ToString())).ChosenSortingId;
            UserListSortingDto     sorting            = new UserListSortingDto();

            if (sortingId != null)
            {
                sorting.Id = (int)sortingId;
            }
            sorting.ShoppingList_Id = listId;

            ShoppingListEntryService shoppingListEntryService = new ShoppingListEntryService();
            var entryId = shoppingListEntryService.GetEntryId(id, listId);

            listSortingService.SaveSorting(sorting, listEntries, entryId);

            //3. Delete ShoppingListEntry (if default or reusable only this)
            shoppingListEntryService.Delete(entryId);

            TempData["SuccessMessage"] = "Successfully deleted the entry.";
            return(RedirectToAction("SingleList", new { @id = listId }));
            //}
            //catch
            //{
            //    TempData["ErrorMessage"] = "There was an error while trying to delete this entry.";
            //    return Redirect(Request.UrlReferrer.ToString());
            //}
        }
        public void TestGetWithoutIncludes()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListGetId, false, false)).Returns(
                new ShoppingList
            {
                Id = shoppingListGetId, Title = "Test list to get", CreatorId = userIds[0], CreatedDate = DateTime.Now
            }
                );
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListGetId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListGetId, userIds[0]);

            Assert.IsNull(shoppingList.ListItems);
        }
        public async Task DeleteByIdAsync_WithExistentId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ShoppingListService DeleteByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var shoppingListRepository = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService    = new ShoppingListService(shoppingListRepository);
            var existentId             = shoppingListRepository.All().First().Id;

            // Act
            var result = await shoppingListService.DeleteByIdAsync(existentId);

            // Assert
            Assert.True(result, errorMessagePrefix + " " + "Returns false.");
        }
        public void TestCreateShouldAssignNextUniqueTitle()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.FindByPartialTitleMatch("Shopping List #", userIds[0])).Returns(
                new List <ShoppingList>()
            {
                new ShoppingList {
                    Id = 1231, Title = "Shopping List #Z", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1231, Title = "Shopping List #A", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1231, Title = "Shopping List #3", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1232, Title = "Shopping List #2", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1233, Title = "Shopping List #1", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1233, Title = "Shopping List #0", CreatorId = userIds[0], CreatedDate = DateTime.Now
                },
                new ShoppingList {
                    Id = 1233, Title = "Shopping List #10", CreatorId = userIds[0], CreatedDate = DateTime.Now
                }
            }
                );
            mockShoppingListRepository.Setup(slr => slr.Create(It.IsAny <ShoppingList>()));
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            var mockShoppingListPermissionRepository = new Mock <IShoppingListPermissionRepository>();

            container.StartMocking <IShoppingListPermissionRepository>(() => mockShoppingListPermissionRepository.Object);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Create(userIds[0]);

            Assert.AreEqual("Shopping List #11", shoppingList.Title);
        }
        public async Task GetIdByRecipeIdAsync_WithExistentRecipeId_ShouldReturnCorrectResult()
        {
            var errorMessagePrefix = "ShoppingListService GetIdByRecipeIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var shoppingListRepository = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService    = new ShoppingListService(shoppingListRepository);
            var recipeId = context.Recipes.First().Id;

            // Act
            var actualResult = await shoppingListService.GetIdByRecipeIdAsync(recipeId);

            var expectedResult = shoppingListRepository.All().First().Id;

            // Assert
            Assert.True(expectedResult == actualResult, errorMessagePrefix + " " + "Id is not returned properly.");
        }
        public async Task DeleteByIdAsync_WithExistentId_ShouldSuccessfullyDelete()
        {
            var errorMessagePrefix = "ShoppingListService DeleteByIdAsync() method does not work properly.";

            // Arrange
            MapperInitializer.InitializeMapper();
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            await this.SeedDataAsync(context);

            var shoppingListRepository = new EfDeletableEntityRepository <ShoppingList>(context);
            var shoppingListService    = new ShoppingListService(shoppingListRepository);
            var existentId             = shoppingListRepository.All().First().Id;

            // Act
            var shoppingListsCount = shoppingListRepository.All().Count();
            await shoppingListService.DeleteByIdAsync(existentId);

            var actualResult   = shoppingListRepository.All().Count();
            var expectedResult = shoppingListsCount - 1;

            // Assert
            Assert.True(actualResult == expectedResult, errorMessagePrefix + " " + "ShoppingLists count is not reduced.");
        }
Exemplo n.º 24
0
 public ShoppingListController()
 {
     _repo = new ShoppingListService();
 }
Exemplo n.º 25
0
        public static async Task SignalRInitAsync(IConfiguration configuration,
                                                  User data,
                                                  Action <User> SetData,
                                                  Action <ListAggregator> SetListAggregatorChoosed,
                                                  Action <List> SetListChoosed,

                                                  AuthenticationStateProvider authenticationStateProvider, UserService userService,
                                                  NavigationManager navigationManager, Action StateHasChanged,
                                                  ShoppingListService shoppingListService,
                                                  ILocalStorageService localStorage

                                                  )
        {
            //_hubConnection = new HubConnectionBuilder().WithUrl("https://94.251.148.92:5013/chatHub", (opts) =>
            //{
            //_hubConnection = new HubConnectionBuilder().WithUrl("https://192.168.8.222:91/chatHub", (opts) =>
            //{
            HubConnection _hubConnection = new HubConnectionBuilder().WithUrl(configuration.GetSection("AppSettings")["SignlRAddress"], (opts) =>
            {
                opts.HttpMessageHandlerFactory = (message) =>
                {
                    if (message is HttpClientHandler clientHandler)
                    {
                        // bypass SSL certificate
                        clientHandler.ServerCertificateCustomValidationCallback +=
                            (sender, certificate, chain, sslPolicyErrors) => { return(true); }
                    }
                    ;
                    return(message);
                };
            }).WithAutomaticReconnect().Build();


            _hubConnection.On("DataAreChanged_" + data.UserId, async() =>
            {
                try
                {
                    var identity = await authenticationStateProvider.GetAuthenticationStateAsync();

                    var nameUser = identity.User.Identity.Name;

                    data = await userService.GetUserDataTreeObjectsgAsync(nameUser);

                    SetData(data);
                }

                catch (Exception ex)
                {
                    ((ShoppingListWebApi.Data.CustomAuthenticationStateProvider)authenticationStateProvider).MarkUserAsLoggedOut();

                    navigationManager.NavigateTo("/login");

                    return;
                }

                (var listAggregatorChoosed, var listChoosed) = await LoadSaveOrderHelper.LoadChoosedList(data, localStorage);

                SetListAggregatorChoosed(listAggregatorChoosed);
                SetListChoosed(listChoosed);

                await LoadSaveOrderHelper.LoadListAggregatorsOrder(localStorage, data, authenticationStateProvider);

                StateHasChanged();

                return;
            });
 public ShoppingListServiceTests()
     : base()
 {
     Service = new ShoppingListService(DbContext);
 }
Exemplo n.º 27
0
 protected void WithItems(params ShoppingListItem[] items)
 {
     ShoppingList = MockRepository.GenerateStub <IShoppingList>();
     ShoppingList.Stub(x => x.GetEnumerator()).Return(items.ToList().GetEnumerator());
     ShoppingListService.Stub(x => x.GetShoppingList()).Return(ShoppingList);
 }
Exemplo n.º 28
0
        public ActionResult EditItem(FormCollection collection)
        {
            try
            {
                var name       = collection["Name"];
                var reusable   = collection["UserProduct"];
                var price      = decimal.Parse(collection["Price"]);
                var listId     = int.Parse(collection["ListId"]);
                var qty        = uint.Parse(collection["Quantity"]);
                var unitTypeId = int.Parse(collection["UnitTypesListId"]);
                int catId      = 0;
                int userCatId  = 0;
                if (collection["CategoryListId"] != "")
                {
                    catId = int.Parse(collection["CategoryListId"]);
                }
                var userCat    = collection["UserCategory"];
                var currencyId = int.Parse(collection["CurrencyListId"]);
                var prodTypeId = int.Parse(collection["ProductTypeId"]);
                var prodId     = int.Parse(collection["ProductId"]);

                /* UPDATING ShoppingListEntry */

                ShoppingListEntryService entryService = new ShoppingListEntryService();
                ShoppingListEntryDto     entry        = new ShoppingListEntryDto
                {
                    Id              = entryService.GetEntryId(prodId, listId),
                    Quantity        = (int)qty,
                    ProductTypeId   = prodTypeId,
                    ShoppingList_Id = listId,
                    Product_Id      = prodId,
                    State_Id        = 2 //Default is unchecked
                };

                entryService.Update(entry); //updates ShoppingListEntry

                /* CREATE NEW UserCatgory */
                if (userCat != "")
                {
                    LanguageService languageService = new LanguageService();

                    CategoryDto category = new CategoryDto
                    {
                        Name       = userCat,
                        LanguageId = languageService.GetByCode(Session["LanguageCode"].ToString()).Id,
                        UserId     = int.Parse(Session["UserId"].ToString())
                    };

                    CategoryService categoryService = new CategoryService();
                    userCatId = categoryService.Create(category);
                }

                ProductService productService = new ProductService();
                if (prodTypeId == 4 || prodTypeId == 3)
                {
                    if (reusable == "false")
                    {
                        prodTypeId = 4;   //4 = UserListProduct = non reusable
                    }
                    else
                    {
                        prodTypeId = 3;
                    }

                    /* UPDATING UserProduct */

                    UserProductDto userProduct = new UserProductDto
                    {
                        Id        = productService.GetUserProductId(prodId),
                        ProductId = prodId,
                        Name      = name
                    };
                    if (userCat != "")
                    {
                        userProduct.Category_Id = userCatId;
                    }
                    else
                    {
                        userProduct.Category_Id = catId;
                    }
                    userProduct.User_Id     = int.Parse(Session["UserId"].ToString());
                    userProduct.Unit_Id     = unitTypeId;
                    userProduct.Price       = price;
                    userProduct.Currency_Id = currencyId;

                    productService.Update(userProduct);
                }
                else if (prodTypeId == 1) //if default Product
                {
                    if (catId != 0)
                    {
                        //create LinkDefaultProductToCategory entry
                    }
                    else if (userCatId != 0)
                    {
                        //create LinkDefaultProductToCategory entry
                    }
                }

                /* UPDATING Product -> for new Timestamp*/
                ProductDto productDto = new ProductDto
                {
                    Id            = prodId,
                    ProductTypeId = prodTypeId
                };
                productService.Update(productDto);

                /* UPDATING ShoppingList -> for new Timestamp: */
                ShoppingListDto shoppingList = new ShoppingListDto
                {
                    Id = listId
                };
                ShoppingListService listService = new ShoppingListService();
                listService.Update(shoppingList);

                TempData["SuccessMessage"] = "Successfully edited this item";
                return(RedirectToAction("SingleList", new { @id = listId }));
            }
            catch
            {
                TempData["ErrorMessage"] = "There was an error while editing the item";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
Exemplo n.º 29
0
        public ActionResult CreateItem(FormCollection collection)
        {
            try
            {
                var name            = collection["Name"];
                var reusable        = collection["UserProduct"];
                var price           = decimal.Parse(collection["Price"]);
                var listId          = int.Parse(collection["ShoppingList_Id"]);
                var qty             = int.Parse(collection["quantity"]);
                var unitTypeId      = int.Parse(collection["UnitTypesListId"]); //TODO: create lists in view and get id (like for countries/languages)
                var catId           = int.Parse(collection["CategoryListId"]);
                var userCat         = collection["UserCategory"];
                int userCatId       = 0;
                var currencyId      = int.Parse(collection["CurrencyListId"]);
                int prodType        = 0;
                var prodId          = 0;
                var chosenProductId = collection["ChosenProductId"]; //gets defaultProductId from dropdown

                if (name != "" && chosenProductId != "")             //Name filled in and defaultProduct chosen
                {
                    throw new Exception("You can either create a new item or choose from the default products, but not both!");
                }

                LanguageService languageService = new LanguageService();
                if (userCat != "")
                {
                    CategoryDto category = new CategoryDto
                    {
                        Name       = userCat,
                        LanguageId = languageService.GetByCode(Session["LanguageCode"].ToString()).Id,
                        UserId     = int.Parse(Session["UserId"].ToString())
                    };

                    CategoryService categoryService = new CategoryService();
                    userCatId = categoryService.Create(category);
                }

                ShoppingListEntryService entryService   = new ShoppingListEntryService();
                ProductService           productService = new ProductService();

                if (name != "") //IF UserProduct -> create Product - ShoppingListEntry - UserProduct
                {
                    if (reusable == "false")
                    {
                        prodType = 4;   //4 = UserListProduct = non reusable
                    }
                    else
                    {
                        prodType = 3;   //reusable UserProduct
                    }

                    //create a new Product
                    ProductDto productDto = new ProductDto
                    {
                        ProductTypeId = prodType
                    };
                    prodId = productService.Create(productDto);

                    //create new UserProduct
                    UserProductDto userProduct = new UserProductDto
                    {
                        ProductId = prodId,
                        Name      = name
                    };
                    if (userCat != "")
                    {
                        userProduct.Category_Id = userCatId;
                    }
                    else
                    {
                        userProduct.Category_Id = catId;
                    }
                    userProduct.User_Id     = int.Parse(Session["UserId"].ToString());
                    userProduct.Unit_Id     = unitTypeId;
                    userProduct.Price       = price;
                    userProduct.Currency_Id = currencyId;

                    entryService.Create(userProduct);
                }
                else if (chosenProductId != "")   //IF DefaultProduct -> create ShoppingListEntry & LinkDefaultProductToUser
                {
                    //check if chosen defaultProduct or reusable UserProduct
                    prodId   = int.Parse(chosenProductId);
                    prodType = productService.GetProductTypeId(prodId);

                    if (prodType == 1)    //if DefaultProduct: create Link entry
                    {
                        DefaultProductDto defaultProductDto = new DefaultProductDto
                        {
                            Id = productService.GetDefaultProductId(prodId)
                        };
                        productService.CreateLink(defaultProductDto, int.Parse(Session["UserId"].ToString()));
                    }

                    //if reusable UserProduct: only create ShoppingListEntry
                }

                //create Entry if not existent right now!
                var existentEntries = entryService.GetEntriesByListId(listId);
                foreach (ShoppingListEntryDto shoppingListEntry in existentEntries)
                {
                    if (shoppingListEntry.Product_Id == prodId)
                    {
                        throw new Exception("You can't add the same product to your list twice.");
                    }
                }

                ShoppingListEntryDto entry = new ShoppingListEntryDto
                {
                    Quantity        = qty,
                    Product_Id      = prodId,
                    ShoppingList_Id = listId,
                    State_Id        = 2 //Default is unchecked
                };
                entryService.Create(entry);

                //Update ShoppingList to update Timestamp:
                ShoppingListDto shoppingList = new ShoppingListDto
                {
                    Id = listId
                };
                ShoppingListService listService = new ShoppingListService();
                listService.Update(shoppingList);

                // Update Sorting
                var listEntries = productService.GetEntriesAsProducts(listId, languageService.GetByCode(Session["LanguageCode"].ToString()).Id);
                UserListSortingService listSortingService = new UserListSortingService();
                var sortingId = listService.Get(listId, int.Parse(Session["UserId"].ToString())).ChosenSortingId;
                UserListSortingDto sorting = new UserListSortingDto();
                if (sortingId != null)
                {
                    sorting.Id = (int)sortingId;
                }
                sorting.ShoppingList_Id = listId;
                listSortingService.SaveSorting(sorting, listEntries);

                TempData["SuccessMessage"] = "Successfully created a new item";
                return(RedirectToAction("SingleList", new { @id = listId }));
            }
            catch
            {
                TempData["ErrorMessage"] = "There was an error while creating a new item. Be aware that you can only create a new item or choose from the dropdown list of default products and your own reusable items, but you can't do both.";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
Exemplo n.º 30
0
        // GET: User/SingleList
        public ActionResult SingleList(int?id, int?templateId, int?sortingId)
        {
            if (Session["UserId"] != null && id != null)
            {
                ViewBag.Message = TempData["SuccessMessage"];
                ViewBag.Error   = TempData["ErrorMessage"];

                ShoppingListService listService = new ShoppingListService();
                var userLists     = listService.GetListsByUserId(int.Parse(Session["UserId"].ToString()));
                var requestedList = listService.Get((int)id);

                //checking whether the list the user tries to access is his or if he has access rights
                foreach (ShoppingListDto x in userLists)
                {
                    if (x.Id == requestedList.Id)
                    {
                        SingleListVM list = new SingleListVM
                        {
                            ShoppingList_Id = requestedList.Id
                        };

                        var listObj = listService.Get(list.ShoppingList_Id, int.Parse(Session["UserId"].ToString()));

                        list.ListName         = listObj.Name;
                        list.ListAccessTypeId = listObj.ListAccessTypeId;

                        LanguageService languageService = new LanguageService();
                        var             langId          = languageService.GetByCode(Session["LanguageCode"].ToString()).Id;

                        ProductService productService = new ProductService();
                        list.ListEntries = productService.GetEntriesAsProducts(list.ShoppingList_Id, langId);

                        if (list.ListEntries.Count() == 0)
                        {
                            ViewBag.Message = "You don't have any entries yet. Start creating your entries now!";
                        }

                        TemplateSortingService templateService    = new TemplateSortingService();
                        UserListSortingService listSortingService = new UserListSortingService();
                        UserListSortingDto     sorting            = new UserListSortingDto();
                        if (listObj.ChosenSortingId != null)
                        {
                            sorting.Id = (int)listObj.ChosenSortingId;
                        }
                        sorting.ShoppingList_Id = list.ShoppingList_Id;

                        if (listObj.ChosenSortingId != null)
                        {
                            list.ListEntries = listSortingService.ApplyUserSorting((int)listObj.ChosenSortingId, list.ListEntries);
                        }

                        if (templateId != null)
                        {
                            list.ListEntries = templateService.SortByTemplate((int)templateId, list.ListEntries);
                            listSortingService.SaveSorting(sorting, list.ListEntries);
                            ViewBag.Message = "Your list has been sorted according to the template. This sorting has been saved permanently for you.";
                        }
                        else if (sortingId != null)
                        {
                            switch ((int)sortingId)
                            {
                            case 1:     // A - Z
                            {
                                list.ListEntries = list.ListEntries.OrderBy(z => z.Name).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 2:     // Z - A
                            {
                                list.ListEntries = list.ListEntries.OrderByDescending(z => z.Name).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 3:     // lowest price
                            {
                                list.ListEntries = list.ListEntries.OrderBy(z => z.Price).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 4:     // highest price
                            {
                                list.ListEntries = list.ListEntries.OrderByDescending(z => z.Price).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            default: break;
                            }
                        }

                        list.ChosenProductId    = 0; //By default no defaultProduct should be selected
                        list.ChooseProductsList = (from item in productService.GetDefaultAndReusableProductsByLanguage(langId)
                                                   select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.ProductId.ToString()
                        }).ToList();

                        UnitTypeService unitTypeService = new UnitTypeService();
                        list.UnitTypesListId = 8; //default value: pc.
                        list.UnitTypesList   = (from item in unitTypeService.GetUnitTypesByLanguage(langId)
                                                select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.Id.ToString()
                        }).ToList();

                        CurrencyService currencyService = new CurrencyService();
                        list.CurrencyListId = 5; //default DKK
                        list.CurrencyList   = (from item in currencyService.GetAll()
                                               select new SelectListItem()
                        {
                            Text = item.Code,
                            Value = item.Id.ToString()
                        }).ToList();

                        CategoryService categoryService = new CategoryService();
                        list.CategoryListId = 20; //default category: others
                        list.CategoryList   = (from item in categoryService.GetAllCategories(langId, int.Parse(Session["UserId"].ToString()))
                                               select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.Id.ToString()
                        }).ToList();

                        list.ChosenTemplateId = 0;
                        list.Templates        = (from item in templateService.GetTemplates()
                                                 select new SelectListItem()
                        {
                            Text = item.TemplateName,
                            Value = item.Id.ToString()
                        }).ToList();

                        return(View(list));
                    }
                }

                TempData["ErrorMessage"] = "The list you tried to access isn't yours!!";
                return(RedirectToAction("Lists", "List"));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }