public async Task <TorrentsViewModel> GetTorrents(int pageIndex, int itemsPage, string searchText)
        {
            var filterSpecification          = new CatalogFilterSpecification(searchText);
            var filterPaginatedSpecification = new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, searchText);

            var torrentsOnPage = await _torrentRepository.ListAsync(filterPaginatedSpecification);

            var totalTorrents = await _torrentRepository.CountAsync(filterSpecification);

            var ci = new TorrentsViewModel
            {
                CatalogTorrents = torrentsOnPage.Select(x => new TorrentViewModel()
                {
                    Id          = x.Id,
                    Title       = x.Title,
                    Size        = x.Size,
                    RegistredAt = x.RegistredAt
                }),
                SearchText     = searchText,
                PaginationInfo = new PaginationInfoViewModel()
                {
                    ActualPage      = pageIndex,
                    TorrentsPerPage = torrentsOnPage.Count,
                    TotalTorrents   = totalTorrents,
                    TotalPages      = int.Parse(Math.Ceiling((decimal)totalTorrents / itemsPage).ToString())
                }
            };

            ci.PaginationInfo.Previous = (ci.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
            ci.PaginationInfo.Next     = (ci.PaginationInfo.ActualPage == ci.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            return(ci);
        }
        public async Task <GetCatalogItemsPaginatedResponse> Handle
        (
            GetCatalogItemsPaginatedRequest aGetCatalogItemsPaginatedRequest,
            CancellationToken aCancellationToken
        )
        {
            var catalogFilterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification
                (
                    skip: aGetCatalogItemsPaginatedRequest.PageSize * aGetCatalogItemsPaginatedRequest.PageIndex,
                    take: aGetCatalogItemsPaginatedRequest.PageSize,
                    brandId: aGetCatalogItemsPaginatedRequest.CatalogBrandId,
                    typeId: aGetCatalogItemsPaginatedRequest.CatalogTypeId
                );
            IReadOnlyList <CatalogItem> catalogItems = await CatalogItemRepository.ListAsync(catalogFilterPaginatedSpecification);

            var filterSpecification = new CatalogFilterSpecification(
                aGetCatalogItemsPaginatedRequest.CatalogBrandId,
                aGetCatalogItemsPaginatedRequest.CatalogTypeId);
            int totalItems = await CatalogItemRepository.CountAsync(filterSpecification);

            var response = new GetCatalogItemsPaginatedResponse(aGetCatalogItemsPaginatedRequest.CorrelationId)
            {
                CorrelationId = aGetCatalogItemsPaginatedRequest.CorrelationId,
                PageCount     = int.Parse(Math.Ceiling((decimal)totalItems / aGetCatalogItemsPaginatedRequest.PageSize).ToString())
            };

            response.CatalogItems.AddRange(catalogItems.Select(Mapper.Map <CatalogItemDto>));
            foreach (CatalogItemDto item in response.CatalogItems)
            {
                item.PictureUri = UriComposer.ComposePicUri(item.PictureUri);
            }

            return(response);
        }
Example #3
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification          = new CatalogFilterSpecification(brandId, typeId);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, brandId, typeId);

            // the implementation below using ForEach and Count. We need a List.
            var itemsOnPage = _itemRepository.List(filterPaginatedSpecification).ToList();
            var totalItems  = _itemRepository.Count(filterSpecification);

            // Initial implementation
            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });


            // Adding a reference to use an Azure Storage Blob

            /*
             * itemsOnPage.ForEach(x =>
             * {
             *  StorageCredentials credentials = new WindowsAzure.Storage.Auth.StorageCredentials("{YOUR_STORAGE_ACCOUNT_NAME}", "{YOUR_STORAGE_PRIMARY_KEY}");
             *  CloudStorageAccount storageAccount = new WindowsAzure.Storage.CloudStorageAccount(credentials, true);
             *  Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobClient = new WindowsAzure.Storage.Blob.CloudBlobClient(storageAccount.BlobStorageUri.PrimaryUri, credentials);
             *  Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blockblob = new WindowsAzure.Storage.Blob.CloudBlockBlob(new Uri(x.PictureUri));
             *  var blob = blockblob.OpenReadAsync();
             *  x.PictureUri = _uriComposer.ComposePicUri(blockblob.Uri.ToString());
             * });
             */

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #4
0
        public override async Task <ActionResult <ListPagedCatalogItemResponse> > HandleAsync([FromQuery] ListPagedCatalogItemRequest request, CancellationToken cancellationToken)
        {
            var response = new ListPagedCatalogItemResponse(request.CorrelationId());

            var filterSpec = new CatalogFilterSpecification(request.CatalogBrandId, request.CatalogTypeId);
            int totalItems = await _itemRepository.CountAsync(filterSpec, cancellationToken);

            var pagedSpec = new CatalogFilterPaginatedSpecification(
                skip: request.PageIndex * request.PageSize,
                take: request.PageSize,
                brandId: request.CatalogBrandId,
                typeId: request.CatalogTypeId);

            var items = await _itemRepository.ListAsync(pagedSpec, cancellationToken);

            response.CatalogItems.AddRange(items.Select(_mapper.Map <CatalogItemDto>));
            foreach (CatalogItemDto item in response.CatalogItems)
            {
                item.PictureUri = _uriComposer.ComposePicUri(item.PictureUri);
            }

            if (request.PageSize > 0)
            {
                response.PageCount = int.Parse(Math.Ceiling((decimal)totalItems / request.PageSize).ToString());
            }
            else
            {
                response.PageCount = totalItems > 0 ? 1 : 0;
            }

            return(Ok(response));
        }
        public async Task <CatalogIndexViewModel> GetCatalogItems(
            int pageIndex, int itemsPage,
            string searchText,
            int?brandId, int?typeId,
            bool convertPrice = true,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            _logger.LogInformation("GetCatalogItems called.");

            var pageItemsOffset              = itemsPage * pageIndex;
            var filterSpecification          = new CatalogFilterSpecification(searchText, brandId, typeId);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(
                    pageItemsOffset, itemsPage, searchText, brandId, typeId);

            // the implementation below using ForEach and Count. We need a List.
            var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

            // var itemsOnPage = await ListCatalogItems(
            // itemsPage * pageIndex, itemsPage, brandId, typeId);
            var totalItems = await _itemRepository.CountAsync(filterSpecification);

            // var totalItems = await CountCatalogItems(brandId, typeId);

            foreach (var itemOnPage in itemsOnPage)
            {
                itemOnPage.PictureUri = string.IsNullOrEmpty(itemOnPage.PictureUri)
                     ? _configuration.GetValue <string>("ImagePictureUri")
                     : _uriComposer.ComposePicUri(itemOnPage.PictureUri);
            }
            var CatalogItemsTask = Task.WhenAll(itemsOnPage.Select(
                                                    catalogItem => CreateCatalogItemViewModelAsync(catalogItem, convertPrice, cancellationToken)));

            cancellationToken.ThrowIfCancellationRequested();



            var vm = new CatalogIndexViewModel()
            {
                CatalogItems       = await CatalogItemsTask, // catalogItemsList,
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
        public void MatchesExpectedNumberOfItems(int?brandId, int?typeId, int expectedCount)
        {
            var spec   = new CatalogFilterSpecification(brandId, typeId);
            var result = GetTestItemCollection()
                         .AsQueryable()
                         .Where(spec.Criteria);

            Assert.Equal(expectedCount, result.Count());
        }
        public void MatchesExpectedNumberOfItems(int?illustrationId, int?typeId, int expectedCount)
        {
            var spec = new CatalogFilterSpecification(illustrationId, typeId, null);

            var result = GetTestItemCollection()
                         .AsQueryable()
                         .Where(spec.WhereExpressions.First().Compile());

            Assert.Equal(expectedCount, result.Count());
        }
Example #8
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId, string username, int recommendations)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification = new CatalogFilterSpecification(brandId, typeId);
            var root = _itemRepository.List(filterSpecification);

            var totalItems = root.Count();

            var itemsOnPage = root
                              .Skip(itemsPage * pageIndex)
                              .Take(itemsPage)
                              .ToList();

            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            if (pageIndex == 0 && !String.IsNullOrEmpty(username))
            {
                vm.RecommendedCatalogItems = (await GetRecommendations(username, recommendations)).ToArray();
            }
            else
            {
                vm.RecommendedCatalogItems = Enumerable.Empty <CatalogItemViewModel>();
            }

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #9
0
            public async Task <Result <List <CatalogItemViewModel> > > Handle(GetCatalogItemsQuery request, CancellationToken cancellationToken)
            {
                var filterSpecification          = new CatalogFilterSpecification(request.brandId, request.typeId);
                var filterPaginatedSpecification = new CatalogFilterPaginatedSpecification(request.itemsPage * request.pageIndex, request.itemsPage, request.brandId, request.typeId);

                // the implementation below using ForEach and Count. We need a List.
                var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

                var totalItems = await _itemRepository.CountAsync(filterSpecification);

                return(default);
Example #10
0
        public async Task <CatalogIndexViewModel> GetCategoryCatalogItems(int categoryId, int pageIndex, int?itemsPage)
        {
            //TODO: Move to repo

            //Get Category Name
            var category = await _db.Categories.FindAsync(categoryId);

            var filterSpecification = new CatalogFilterSpecification(null, null, categoryId);
            var root = await _itemRepository
                       .ListAsync(filterSpecification);

            var totalItems = root.Count();

            var iPage = itemsPage ?? totalItems;

            var allItems = root.ToList();

            var itemsOnPage = allItems
                              .Skip(iPage * pageIndex)
                              .Take(iPage)
                              .ToList();

            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });

            if (allItems?.Count > 0)
            {
                var vm = new CatalogIndexViewModel()
                {
                    CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                    {
                        CatalogItemId   = i.Id,
                        CatalogItemName = i.Name,
                        PictureUri      = i.PictureUri,
                        Price           = i.Price ?? i.CatalogType.Price,
                        ProductSku      = i.Sku,
                        CatalogTypeName = i.CatalogType?.Name
                    }),
                    PaginationInfo = new PaginationInfoViewModel()
                    {
                        ActualPage   = pageIndex,
                        ItemsPerPage = itemsOnPage.Count,
                        TotalItems   = totalItems,
                        TotalPages   = iPage != 0 ? int.Parse(Math.Ceiling(((decimal)totalItems / iPage)).ToString()) : 0
                    }
                };
                vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
                vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
                return(vm);
            }
            return(null);
        }
Example #11
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int?itemsPage, int?illustrationId, int?typeId, int?categoryId)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification = new CatalogFilterSpecification(illustrationId, typeId, categoryId);
            var root = await _itemRepository
                       .ListAsync(filterSpecification);

            var totalItems = root.Count();

            var iPage = itemsPage ?? totalItems;

            var itemsOnPage = root
                              .Skip(iPage * pageIndex)
                              .Take(iPage)
                              .OrderByDescending(x => x.IsFeatured)
                              .ThenBy(x => x.CatalogType.Code.StartsWith("QF") ? 0 : x.CatalogType.Code.StartsWith("SM") ? 1 : 2)
                              .ThenBy(x => x.Name)
                              .ToList();

            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    CatalogItemId   = i.Id,
                    CatalogItemName = i.Name,
                    PictureUri      = i.PictureUri,
                    Price           = i.Price ?? i.CatalogType.Price,
                    ProductSku      = i.Sku
                }),
                //Illustrations = await GetIllustrations(),
                Types = await GetTypes(),
                IllustrationFilterApplied = illustrationId ?? 0,
                TypesFilterApplied        = typeId ?? 0,
                PaginationInfo            = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = iPage != 0 ? int.Parse(Math.Ceiling(((decimal)totalItems / iPage)).ToString()) : 0
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #12
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId) // @issue@I02 // @issue@I05
        {
            _logger.LogInformation("GetCatalogItems called.");                                                           // @issue@I02

            var filterSpecification = new CatalogFilterSpecification(brandId, typeId);                                   // @issue@I02
            var root = _itemRepository.List(filterSpecification);                                                        // @issue@I02

            var totalItems = root.Count();                                                                               // @issue@I02

            var itemsOnPage = root                                                                                       // @issue@I02
                              .Skip(itemsPage * pageIndex)
                              .Take(itemsPage)
                              .ToList();

            /*
             * var itemsOnPage = root // @issue@I06
             *  .Skip(itemsPage * pageIndex) // @issue@I06
             *  .Take(itemsPage) // @issue@I06
             *  .ToList(); // @issue@I06
             */
            itemsOnPage.ForEach(x => // @issue@I02
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });

            var vm = new CatalogIndexViewModel() // @issue@I02
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : ""; // @issue@I02
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";                                // @issue@I02

            return(vm);                                                                                                           // @issue@I02
        }
Example #13
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification = new CatalogFilterSpecification(brandId, typeId);
            var catalogItems        = await _itemRepository.GetAsync(filterSpecification);

            if (catalogItems != null)
            {
                var totalItems = catalogItems.Count();

                var itemsOnPage = catalogItems
                                  .Skip(itemsPage * pageIndex)
                                  .Take(itemsPage)
                                  .ToList();

                itemsOnPage.ForEach(x =>
                {
                    x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
                });

                var viewModel = new CatalogIndexViewModel()
                {
                    CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                    {
                        Id         = i.Id,
                        Name       = i.Name,
                        PictureUri = i.PictureUri,
                        Price      = i.Price
                    }),
                    Brands             = await GetBrands(),
                    Types              = await GetTypes(),
                    BrandFilterApplied = brandId ?? 0,
                    TypesFilterApplied = typeId ?? 0,
                    PaginationInfo     = new PaginationInfoViewModel()
                    {
                        ActualPage   = pageIndex,
                        ItemsPerPage = itemsOnPage.Count,
                        TotalItems   = totalItems,
                        TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                    }
                };

                viewModel.PaginationInfo.Next     = (viewModel.PaginationInfo.ActualPage == viewModel.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
                viewModel.PaginationInfo.Previous = (viewModel.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

                return(viewModel);
            }

            return(null);
        }
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId, string searchText = null)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification          = new CatalogFilterSpecification(brandId, typeId, searchText);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, brandId, typeId, searchText);

            // the implementation below using ForEach and Count. We need a List.
            var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

            var totalItems = await _itemRepository.CountAsync(filterSpecification);

            foreach (var itemOnPage in itemsOnPage)
            {
                itemOnPage.PictureUri = _uriComposer.ComposePicUri(itemOnPage.PictureUri);
            }

            var brands = await _brandRepository.ListAllAsync();

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price,
                    Brand      = brands.FirstOrDefault(b => b.Id == i.CatalogBrandId)?.Brand
                }),
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #15
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
        {
            _logger.LogInformation("Get CatalogeItems Called..");

            var filterSpecification          = new CatalogFilterSpecification(brandId, typeId);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, brandId, typeId);

            var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

            var totalItems = await _itemRepository.CountAsync(filterSpecification);

            foreach (var itemOnPage in itemsOnPage)
            {
                itemOnPage.PictureUri = _uriComposer.ComposePicUri(itemOnPage.PictureUri);
            }

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),

                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
        public async Task <CatalogIndexViewModel> GetCatalogItems(CatalogPageFiltersViewModel catalogPageFiltersViewModel, bool useCache, bool convertPrice = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification          = new CatalogFilterSpecification(catalogPageFiltersViewModel.BrandFilter, catalogPageFiltersViewModel.TypesFilter, catalogPageFiltersViewModel.SearchTextFilter);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(catalogPageFiltersViewModel.ItemsPerPage * catalogPageFiltersViewModel.PageId, catalogPageFiltersViewModel.ItemsPerPage, catalogPageFiltersViewModel.SearchTextFilter, catalogPageFiltersViewModel.OrderBy, catalogPageFiltersViewModel.Order, catalogPageFiltersViewModel.BrandFilter, catalogPageFiltersViewModel.TypesFilter);

            // the implementation below using ForEach and Count. We need a List.
            var totalItems = await _itemRepository.CountAsync(filterSpecification);

            var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

            foreach (var itemOnPage in itemsOnPage)
            {
                itemOnPage.PictureUri = _uriComposer.ComposePicUri(itemOnPage.PictureUri);
            }

            var catalogItemsTask = await Task.WhenAll(itemsOnPage.Select(catalogItem => CreateCatalogItemViewModel(catalogItem, convertPrice, cancellationToken)));

            // em caso de algures haver um cancelamento o código para aqui e devolve um erro. Escusa de proceguir no processamento
            cancellationToken.ThrowIfCancellationRequested();

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = catalogItemsTask,
                Brands       = await GetBrands(cancellationToken),
                Types        = await GetTypes(cancellationToken),
                //BrandFilterApplied = catalogPageFiltersViewModel.BrandFilter ?? 0,
                //TypesFilterApplied = catalogPageFiltersViewModel.TypesFilter ?? 0,
                PaginationInfo = new PaginationInfoViewModel()
                {
                    ActualPage   = catalogPageFiltersViewModel.PageId,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = catalogPageFiltersViewModel.ItemsPerPage == 0 ? 1 :
                                   int.Parse(Math.Ceiling(((decimal)totalItems / catalogPageFiltersViewModel.ItemsPerPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
        public async Task <CatalogIndexViewModel> GetCatalogItems(CatalogFilterViewModel model)
        {
            CatalogFilterSpecification filterSpecification = new CatalogFilterSpecification(model.BrandFilterApplied, model.TypesFilterApplied, model.TextSearch);
            var root = _itemRepository.List(filterSpecification);

            var totalItems = root.Count();

            var itemsOnPage = root
                              .Skip(model.PaginationInfo.ItemsPerPage * model.PaginationInfo.ActualPage)
                              .Take(model.PaginationInfo.ItemsPerPage)
                              .ToList();

            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            });

            CatalogIndexViewModel vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),
                Brands = await GetBrands(),
                Types  = await GetTypes()
            };

            vm.CatalogFilter.BrandFilterApplied = model.BrandFilterApplied ?? 0;
            vm.CatalogFilter.TypesFilterApplied = model.TypesFilterApplied ?? 0;
            vm.CatalogFilter.PaginationInfo     = new PaginationInfoViewModel()
            {
                ActualPage   = model.PaginationInfo.ActualPage,
                ItemsPerPage = itemsOnPage.Count,
                TotalItems   = totalItems,
                TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / model.PaginationInfo.ItemsPerPage)).ToString())
            };
            vm.CatalogFilter.PaginationInfo.Next     = (vm.CatalogFilter.PaginationInfo.ActualPage == vm.CatalogFilter.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.CatalogFilter.PaginationInfo.Previous = (vm.CatalogFilter.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
            vm.CatalogFilter.TextSearch = model.TextSearch ?? string.Empty;

            return(vm);
        }
Example #18
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification          = new CatalogFilterSpecification(brandId, typeId);
            var filterPaginatedSpecification =
                new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, brandId, typeId);

            // the implementation below using ForEach and Count. We need a List.
            var itemsOnPage = _itemRepository.List(filterPaginatedSpecification).ToList();
            var totalItems  = _itemRepository.Count(filterSpecification);

            itemsOnPage.ForEach(x =>
            {
                x.PictureUri = "pic/" + x.PictureUri;
            });

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                {
                    Id         = i.Id,
                    Name       = i.Name,
                    PictureUri = i.PictureUri,
                    Price      = i.Price
                }),
                Brands             = await GetBrands(),
                Types              = await GetTypes(),
                BrandFilterApplied = brandId ?? 0,
                TypesFilterApplied = typeId ?? 0,
                PaginationInfo     = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #19
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
        { // pageIndex is current page
            _logger.LogInformation("GetCatalogItems called");

            var filterSpecification        = new CatalogFilterSpecification(brandId, typeId);                                            // this contains all catalogitems with matching brand&type ids
            var filterPaginatedSpecifition = new CatalogFilterPaginatedSpecification(itemsPage * pageIndex, itemsPage, brandId, typeId); // this contains all catalogItem per page
            var itemsPerPage = await _itemRepository.ListAsync(filterPaginatedSpecifition);

            var totalItems = await _itemRepository.CountAsync(filterSpecification);

            var vm = new CatalogIndexViewModel()
            {
                catalogItems = itemsPerPage.Select(i => new CatalogItemViewModel()
                {
                    id         = i.id,
                    name       = i.Name,
                    pictureUri = _uriComposer.ComposePictureUri(i.PictureUri),
                    price      = i.Price
                }).ToList(),
                //for List<SelectListItem> brands
                brands             = (List <SelectListItem>) await GetBrands(), // this is an explicit cast
                types              = (List <SelectListItem>) await GetTypes(),
                brandFilterApplied = brandId ?? 0,                              // if brandId not null pass it, else pass 0
                typeFilterApplied  = typeId ?? 0,

                paginationInfo = new PaginationInfoViewModel()
                {
                    totalItems   = totalItems,
                    itemsPerPage = itemsPerPage.Count,
                    actualPage   = pageIndex,
                    totalPages   = int.Parse(Math.Ceiling((decimal)totalItems / itemsPerPage.Count).ToString())
                                   // string next and previous are defined seperately below
                }
            };

            // "is-disabled" will be render into HTML that disables next/previous button
            vm.paginationInfo.next     = (vm.paginationInfo.actualPage == vm.paginationInfo.totalPages - 1)  ?  "is-disabled" : "";
            vm.paginationInfo.previous = (vm.paginationInfo.actualPage == 0) ? "is-disabled" : "";

            return(vm);
        }
Example #20
0
            private async Task <Model> GetCatalogItems(int pageIndex, int itemsPage, int?brandId, int?typeId)
            {
                string cacheKey                      = String.Format(_itemsKeyTemplate, pageIndex, itemsPage, brandId, typeId);
                var    filterSpecification           = new CatalogFilterSpecification(brandId, typeId);
                IEnumerable <Model.CatalogItem> root = await ListAsync(filterSpecification, cacheKey);

                var totalItems  = root.Count();
                var itemsOnPage = root
                                  .Skip(itemsPage * pageIndex)
                                  .Take(itemsPage)
                                  .ToList();

                itemsOnPage.ForEach(x =>
                {
                    x.ImageUrl = _urlComposer.ComposeImgUrl(x.ImageUrl);
                });
                var result = new Model()
                {
                    CatalogItems       = itemsOnPage,
                    Brands             = await GetBrands(),
                    Types              = await GetTypes(),
                    BrandFilterApplied = brandId ?? 0,
                    TypesFilterApplied = typeId ?? 0,
                    PaginationInfo     = new Model.PaginationInfoViewModel()
                    {
                        ActualPage   = pageIndex,
                        ItemsPerPage = itemsOnPage.Count,
                        TotalItems   = totalItems,
                        TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / itemsPage)).ToString())
                    }
                };

                foreach (var n in result.CatalogItems)
                {
                }
                result.PaginationInfo.Next     = (result.PaginationInfo.ActualPage == result.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
                result.PaginationInfo.Previous = (result.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
                return(result);
            }
Example #21
0
            public async Task <Result <ShopViewModel> > Handle(GetShopModelQuery request, CancellationToken cancellationToken)
            {
                var filterSpecification          = new CatalogFilterSpecification(request.brandId, request.typeId);
                var filterPaginatedSpecification = new CatalogFilterPaginatedSpecification(request.itemsPage * request.pageIndex, request.itemsPage, request.brandId, request.typeId);

                // the implementation below using ForEach and Count. We need a List.
                var itemsOnPage = await _itemRepository.ListAsync(filterPaginatedSpecification);

                var totalItems = await _itemRepository.CountAsync(filterSpecification);

                var vm = new ShopViewModel()
                {
                    CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                    {
                        Id         = i.Id,
                        Name       = i.Name,
                        PictureUri = _uriComposer.ComposePicUri(i.PictureUri),
                        Price      = i.Price
                    }),
                    Brands             = await GetBrands(),
                    Types              = await GetTypes(),
                    BrandFilterApplied = request.brandId ?? 0,
                    TypesFilterApplied = request.typeId ?? 0,
                    PaginationInfo     = new PaginationInfoViewModel()
                    {
                        ActualPage   = request.pageIndex,
                        ItemsPerPage = itemsOnPage.Count,
                        TotalItems   = totalItems,
                        TotalPages   = int.Parse(Math.Ceiling(((decimal)totalItems / request.itemsPage)).ToString())
                    }
                };

                vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
                vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

                return(Result <ShopViewModel> .Success(vm));
            }
Example #22
0
        public async Task <IActionResult> UpdateOtherPicturesAsync()
        {
            var spec     = new CatalogFilterSpecification(false);
            var products = await _catalogRepository.ListAsync(spec);

            foreach (var item in products)
            {
                foreach (var other in item.Pictures.Where(x => !x.IsMain).ToList())
                {
                    if (!string.IsNullOrEmpty(other.PictureHighUri))
                    {
                        Uri uri          = new Uri(other.PictureHighUri);
                        var fileName     = Path.GetFileName(uri.LocalPath);
                        var originalPath = Path.Combine(_backofficeSettings.WebProductsPictureFullPath, fileName);
                        var newFileName  = Utils.URLFriendly(Path.GetFileNameWithoutExtension(uri.LocalPath)) + Path.GetExtension(uri.LocalPath);
                        var newPath      = Path.Combine(_backofficeSettings.WebProductsPictureV2FullPath, newFileName);
                        using (Image image = Image.Load(originalPath))
                        {
                            var options = new ResizeOptions
                            {
                                Mode = ResizeMode.Crop,
                                Size = new Size(700, 700)
                            };

                            image.Mutate(x => x.Resize(options));

                            image.Save(newPath, new JpegEncoder {
                                Quality = 90
                            });                                                    // Automatic encoder selected based on extension.
                        }
                        other.UpdatePictureUri(_backofficeSettings.WebProductsPictureV2Uri + newFileName);
                    }
                }
                await _catalogRepository.UpdateAsync(item);
            }
            return(Ok());
        }
Example #23
0
        public async Task <IActionResult> UpdatePicturesAsync()
        {
            var spec     = new CatalogFilterSpecification(false);
            var products = await _catalogRepository.ListAsync(spec);

            //Add main Picture
            foreach (var item in products)
            {
                if (!string.IsNullOrEmpty(item.PictureUri) && !item.Pictures.Any(x => x.IsMain))
                {
                    item.AddPicture(new CatalogPicture(isActive: true, isMain: true, pictureUri: item.PictureUri, order: 0));
                    await _catalogRepository.UpdateAsync(item);
                }
            }
            //Set current Picture to PictureHighUri
            products = await _catalogRepository.ListAsync(spec);

            foreach (var product in products)
            {
                foreach (var picture in product.Pictures)
                {
                    if (!string.IsNullOrEmpty(picture.PictureUri) && string.IsNullOrEmpty(picture.PictureHighUri))
                    {
                        //Set pictureHighUri
                        picture.UpdatePictureUri(picture.PictureUri);
                        Uri uri      = new Uri(picture.PictureUri);
                        var name     = Utils.URLFriendly(Path.GetFileNameWithoutExtension(uri.LocalPath));
                        var fileName = name + Path.GetExtension(uri.LocalPath);
                        var fullPath = Path.Combine(_backofficeSettings.WebProductsPictureV2FullPath, fileName);
                        picture.UpdatePictureUri(_backofficeSettings.WebProductsPictureV2Uri + fileName);

                        //Get Image
                        var originalImage = Path.Combine(_backofficeSettings.WebProductsPictureFullPath, Path.GetFileName(uri.LocalPath));
                        using (Image image = Image.Load(originalImage))
                        {
                            image.Mutate(x => x
                                         .Resize(469, 469));

                            image.Save(fullPath); // Automatic encoder selected based on extension.
                        }
                    }
                }
                await _catalogRepository.UpdateAsync(product);
            }

            //Product Types
            var typesSpec = new CatalogTypeSpecification(true);
            var types     = await _catalogTypeRepository.ListAsync(typesSpec);

            foreach (var item in types)
            {
                //Main Picture
                if (!string.IsNullOrEmpty(item.PictureUri) && !item.PictureUri.Contains("v2"))
                {
                    Uri uri               = new Uri(item.PictureUri);
                    var fileName          = Path.GetFileName(uri.LocalPath);
                    var originalImagePath = Path.Combine(_backofficeSettings.WebProductTypesPictureFullPath, fileName);
                    var newImagePath      = Path.Combine(_backofficeSettings.WebProductTypesPictureV2FullPath, fileName);
                    using (Image image = Image.Load(originalImagePath))
                    {
                        image.Mutate(x => x
                                     .Resize(255, 116));

                        image.Save(newImagePath); // Automatic encoder selected based on extension.
                    }
                    item.UpdatePicture(_backofficeSettings.WebProductTypesPictureV2Uri + fileName);

                    if (item.PictureTextHelpers?.Count > 0)
                    {
                        foreach (var helper in item.PictureTextHelpers)
                        {
                            Uri uriHelper          = new Uri(helper.PictureUri);
                            var fileNameHelper     = Path.GetFileName(uriHelper.LocalPath);
                            var originalHelperPath = Path.Combine(_backofficeSettings.WebProductTypesPictureFullPath, fileNameHelper);
                            var newHelperPath      = Path.Combine(_backofficeSettings.WebProductTypesPictureV2FullPath, fileNameHelper);
                            using (Image image = Image.Load(originalHelperPath))
                            {
                                image.Mutate(x => x
                                             .Resize(112, 96));

                                image.Save(newHelperPath); // Automatic encoder selected based on extension.
                            }
                            helper.PictureUri = _backofficeSettings.WebProductTypesPictureV2Uri + fileNameHelper;
                            helper.Location   = newHelperPath;
                        }
                    }
                    await _catalogTypeRepository.UpdateAsync(item);
                }
            }

            return(Ok());
        }
        public async Task ExecuteAsync()
        {
            try
            {
                using var scope = _serviceProvider.CreateScope();
                var invoiceRepository =
                    scope.ServiceProvider
                    .GetService <IAsyncRepository <InvoiceConfig> >();

                var catalogRepository =
                    scope.ServiceProvider
                    .GetService <IAsyncRepository <CatalogItem> >();

                var basketRepository =
                    scope.ServiceProvider
                    .GetService <IAsyncRepository <Basket> >();

                var orderService =
                    scope.ServiceProvider
                    .GetService <IOrderService>();

                var invoiceService =
                    scope.ServiceProvider
                    .GetService <IInvoiceService>();

                var emailSender =
                    scope.ServiceProvider
                    .GetService <IEmailSender>();

                var invoiceConfigs = await invoiceRepository.ListAllAsync();

                if (invoiceConfigs.Count == 0)
                {
                    _logger.LogWarning("No Invoice Configs found!");
                    return;
                }

                var dayConfig = invoiceConfigs.SingleOrDefault(x => x.Week == DateTime.Now.DayOfWeek && x.IsActive);
                if (dayConfig == null)
                {
                    _logger.LogWarning("Day {week} is not ative", DateTime.Now.DayOfWeek);
                    return;
                }

                var maxTotal = dayConfig.NrInvoices * dayConfig.MaxValue;
                //Get total products
                var spec    = new CatalogFilterSpecification(true);
                var catalog = await catalogRepository.ListAsync(spec);

                List <Order> orders = new List <Order>();
                //Check if already send today
                var workerOrders = await orderService.GetOrdersAsync(WORKER_USER);

                var ordersOfToday = workerOrders.Where(x => x.OrderDate.Date == DateTime.Now.Date).ToList();
                if (ordersOfToday.Count > 0)
                {
                    _logger.LogWarning("There already orders for today, ignoring...");
                    return;
                }
                for (int i = 0; i < dayConfig.NrInvoices; i++)
                {
                    await DeleteWorkerBasket(basketRepository);

                    var basket = new Basket()
                    {
                        BuyerId = WORKER_USER, CreatedDate = DateTime.Now
                    };
                    await basketRepository.AddAsync(basket);

                    decimal amountAvailable = dayConfig.MaxValue;
                    while (basket.Total() < dayConfig.MaxValue)
                    {
                        //Get available Products

                        var availableProducts = catalog.Where(x =>
                                                              (x.Price.HasValue && x.Price.Value <= amountAvailable) ||
                                                              (!x.Price.HasValue && x.CatalogType.Price <= amountAvailable))
                                                .ToList();
                        if (availableProducts.Count == 0)
                        {
                            _logger.LogDebug("No more products to add to basket");
                            break;
                        }
                        _logger.LogDebug("{count} available products", availableProducts.Count);

                        //Pick one product
                        var r         = _rnd.Next(availableProducts.Count);
                        var product   = availableProducts[r];
                        var priceUnit = product.Price ?? product.CatalogType.Price;
                        _logger.LogDebug("Pick product {name} for {price}", product.Name, priceUnit);
                        //Add to basket
                        basket.AddItem(product.Id, priceUnit, addToExistingItem: true);
                        amountAvailable -= priceUnit;
                        _logger.LogDebug("Available amount: {amount}", amountAvailable);
                    }

                    //Save basket
                    await basketRepository.UpdateAsync(basket);

                    //Total
                    _logger.LogInformation("Created Basket for Invoice {nr} with total: {total}", i + 1, basket.Total());

                    //Create Order
                    try
                    {
                        var address  = new Address(string.Empty, "Mercado de Loulé - Banca nº 44, Praça da Republica", "Loulé", "Portugal", "8100-270");
                        var resOrder = await orderService.CreateOrderAsync(basket.Id, string.Empty, null, null, null, false, 0, null, true, PaymentType.CASH);

                        orders.Add(resOrder);
                        _logger.LogInformation("Successuful creating order {num} with total {total}", resOrder.Id, resOrder.Total());
                    }
                    catch (RegisterInvoiceException ex)
                    {
                        _logger.LogError(ex, "Erro ao gerar fatura na sage");
                    }
                    //Delete Basket
                    await basketRepository.DeleteAsync(basket);
                }
                //Send Emails
                if (orders.Count > 0)
                {
                    //Send Email to client (from: [email protected])
                    var body = "Olá, foram geradas as faturas em anexo para este dia! <br>" +
                               "Podes consultar as faturas no backoffice do sabor com tradição: <br>" +
                               "http://backoffice.saborcomtradicao.com/sales <br>" +
                               "Ou no portal da sage: <br>" +
                               "https://app.pt.sageone.com/facturacao <br>" +
                               "<br><strong>Muito obrigado e até amanhã!</strong><br>" +
                               "João Gonçalves<br>" +
                               "<img src='https://vendas.saborcomtradicao.com//images/logo-sabor.png' alt='Sabor Com Tradição'/>";

                    List <(string, byte[])> files = new List <(string, byte[])>();
                    foreach (var order in orders)
                    {
                        var invoiceBytes = await invoiceService.GetPDFInvoiceAsync(SageApplicationType.SALESWEB, order.SalesInvoiceId.Value);

                        if (invoiceBytes != null)
                        {
                            files.Add(($"FaturaSaborComTradicao#{order.Id}.pdf", invoiceBytes));
                        }
                        else
                        {
                            _logger.LogError("Erro: O registo de venda foi efectuado com sucesso mas não foi possível obter a fatura. Email não enviado!");
                        }
                    }
                    try
                    {
                        await emailSender.SendEmailAsync(
                            _settings.FromOrderEmail,
                            _settings.CCEmails,
                            $"Sabor com Tradição - Faturação do dia {DateTime.Now.ToString("yyyy-MM-dd")}",
                            body,
                            null,
                            null,
                            files);
                    }
                    catch (SendEmailException ex)
                    {
                        _logger.LogError(ex, "Erro ao enviar email");
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Something got wrong in worker: ");
                try
                {
                    using var scope = _serviceProvider.CreateScope();
                    var emailSender =
                        scope.ServiceProvider
                        .GetService <IEmailSender>();

                    await emailSender.SendEmailAsync(
                        _settings.FromInfoEmail,
                        _settings.CCEmails,
                        "Erro no Sales Worker",
                        ex.ToString());
                }
                catch (Exception ex2)
                {
                    _logger.LogError(ex2, "Error sending email");
                }
            }
        }
Example #25
0
        public async Task <CategoryViewModel> GetCategoryCatalogItems(string categorySlug, int pageIndex, int?itemsPage, string onlyAvailable = null)
        {
            Category category = await GetCategoryFromUrl(categorySlug);

            if (category == null)
            {
                return(null);
            }

            var filterSpecification = new CatalogFilterSpecification(null, null, category.Id, showOnlyAvailable: onlyAvailable == "true");
            var root = await _itemRepository
                       .ListAsync(filterSpecification);

            var totalItems = root.Count();

            var iPage = itemsPage ?? totalItems;

            var allItems = root
                           .OrderByDescending(x => x.Id)
                           .ToList();

            //Get Catalog Types of Category
            var types = new List <CatalogType>();

            foreach (var item in allItems)
            {
                if (item.CatalogType.CatalogItems
                    .Where(x => x.Categories.Any(c => c.CategoryId == category.Id))
                    .ToList().Count() > 0)
                {
                    if (!types.Any(x => x.Id == item.CatalogTypeId))
                    {
                        types.Add(item.CatalogType);
                    }
                }
            }

            var itemsOnPage = allItems
                              .Skip(iPage * pageIndex)
                              .Take(iPage)
                              .ToList();

            if (allItems?.Count > 0)
            {
                var vm = new CatalogIndexViewModel()
                {
                    NewCatalogItems = allItems
                                      .Where(x => x.IsNew)
                                      .Take(12)
                                      .Select(i => new CatalogItemViewModel()
                    {
                        CatalogItemId       = i.Id,
                        CatalogItemName     = i.Name,
                        PictureUri          = i.PictureUri,
                        PictureHighUri      = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                        Price               = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                        PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                        ProductSlug         = i.Slug,
                        IsUnavailable       = i.IsUnavailable
                    }),
                    FeaturedCatalogItems = allItems
                                           .Where(x => x.IsFeatured)
                                           .Take(12)
                                           .Select(i => new CatalogItemViewModel()
                    {
                        CatalogItemId       = i.Id,
                        CatalogItemName     = i.Name,
                        PictureUri          = i.PictureUri,
                        PictureHighUri      = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                        Price               = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                        PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                        ProductSlug         = i.Slug,
                        IsUnavailable       = i.IsUnavailable
                    }),
                    CatalogTypes = types.OrderBy(x => x.Name).Select(x => new CatalogTypeViewModel()
                    {
                        Id          = x.Id,
                        Code        = x.Code,
                        Name        = x.Name,
                        PictureUri  = x.PictureUri,
                        CatNameUri  = category.Slug,
                        TypeNameUri = x.Slug
                    })
                                   .ToList(),
                    CatalogItems = itemsOnPage.Select(i => new CatalogItemViewModel()
                    {
                        CatalogItemId       = i.Id,
                        CatalogItemName     = i.Name,
                        PictureUri          = i.PictureUri,
                        PictureHighUri      = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                        Price               = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                        PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                        ProductSlug         = i.Slug,
                        IsUnavailable       = i.IsUnavailable
                    }),
                    PaginationInfo = new PaginationInfoViewModel()
                    {
                        ActualPage   = pageIndex,
                        ItemsPerPage = itemsOnPage.Count,
                        TotalItems   = totalItems,
                        TotalPages   = iPage != 0 ? int.Parse(Math.Ceiling(((decimal)totalItems / iPage)).ToString()) : 0
                    }
                };
                vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
                vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";
                return(new CategoryViewModel
                {
                    CatalogModel = vm,
                    CategoryName = category.Name,
                    CategoryUrlName = categorySlug,
                    MetaDescription = category.MetaDescription,
                    Title = string.IsNullOrEmpty(category.Title) ? category.Name : category.Title,
                    DescriptionSection = new DescriptionViewModel
                    {
                        H1Text = category.H1Text,
                        Description = category.Description,
                        Question = $"Queres um {GetSingularyName(category.Name)} único e especial?"
                    }
                });
            }
            return(null);
        }
Example #26
0
        public async Task <CatalogIndexViewModel> GetCatalogItems(int pageIndex, int?itemsPage, int?illustrationId, int?typeId, int?categoryId, string onlyAvailable = null)
        {
            _logger.LogInformation("GetCatalogItems called.");

            var filterSpecification = new CatalogFilterSpecification(illustrationId, typeId, categoryId, showOnlyAvailable: onlyAvailable == "true");
            var root = await _itemRepository
                       .ListAsync(filterSpecification);

            var totalItems = root.Count();

            var iPage = itemsPage ?? totalItems;

            var itemsOnPage = root
                              .OrderByDescending(x => x.Id)
                              .Skip(iPage * pageIndex)
                              .Take(iPage)
                              .ToList();

            //itemsOnPage.ForEach(x =>
            //{
            //    x.PictureUri = _uriComposer.ComposePicUri(x.PictureUri);
            //});

            var vm = new CatalogIndexViewModel()
            {
                CatalogItems = itemsOnPage
                               .Select(i => new CatalogItemViewModel()
                {
                    CatalogItemId       = i.Id,
                    CatalogItemName     = i.Name,
                    PictureUri          = i.PictureUri,
                    PictureHighUri      = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                    Price               = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                    PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                    ProductSlug         = i.Slug,
                    IsUnavailable       = i.IsUnavailable
                }),
                NewCatalogItems = new List <CatalogItemViewModel>(),
                // NewCatalogItems = itemsOnPage
                //     .Where(x => x.IsNew)
                //     .Take(12)
                //     .Select(i => new CatalogItemViewModel()
                //     {
                //         CatalogItemId = i.Id,
                //         CatalogItemName = i.Name,
                //         PictureUri = i.PictureUri,
                //         PictureHighUri = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                //         Price = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                //         PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                //         ProductSlug = i.Slug,
                //         IsUnavailable = i.IsUnavailable
                //     }),
                FeaturedCatalogItems = itemsOnPage
                                       .Where(x => x.IsFeatured)
                                       .Take(24)
                                       .Select(i => new CatalogItemViewModel()
                {
                    CatalogItemId       = i.Id,
                    CatalogItemName     = i.Name,
                    PictureUri          = i.PictureUri,
                    PictureHighUri      = i.Pictures?.SingleOrDefault(x => x.IsMain)?.PictureHighUri,
                    Price               = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) - i.Discount.Value : (i.Price ?? i.CatalogType.Price),
                    PriceBeforeDiscount = i.Discount.HasValue ? (i.Price ?? i.CatalogType.Price) : default(decimal?),
                    ProductSlug         = i.Slug,
                    IsUnavailable       = i.IsUnavailable
                }),
                Illustrations             = await GetIllustrations(),
                Types                     = await GetTypes(),
                IllustrationFilterApplied = illustrationId ?? 0,
                TypesFilterApplied        = typeId ?? 0,
                PaginationInfo            = new PaginationInfoViewModel()
                {
                    ActualPage   = pageIndex,
                    ItemsPerPage = itemsOnPage.Count,
                    TotalItems   = totalItems,
                    TotalPages   = iPage != 0 ? int.Parse(Math.Ceiling(((decimal)totalItems / iPage)).ToString()) : 0
                }
            };

            vm.PaginationInfo.Next     = (vm.PaginationInfo.ActualPage == vm.PaginationInfo.TotalPages - 1) ? "is-disabled" : "";
            vm.PaginationInfo.Previous = (vm.PaginationInfo.ActualPage == 0) ? "is-disabled" : "";

            return(vm);
        }