Example #1
0
        public async Task <IEnumerable <OrderModel> > GetOrdersByUserId(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable <OrderModel> userOrders = await dataContext.Orders.Where(o => o.UserId == userId).
                                                      OrderByDescending(o => o.DateCreated).
                                                      Include(o => o.OrderStatus).
                                                      Select(o => new OrderModel()
                {
                    Id = o.Id,
                    DeliveryMerchant   = o.DeliveryMerchant,
                    DeliveryPrice      = o.DeliveryPrice,
                    HasComission       = o.HasCommission,
                    CommissionPercents = o.CommissionPercents,
                    ShippingPrice      = o.ShippingPrice,
                    ItemsPrice         = o.ItemsPrice,
                    TotalPrice         = o.TotalPrice,
                    Status             = o.OrderStatus.Name,
                    DateCreated        = o.DateCreated
                }).
                                                      ToArrayAsync();

                return(userOrders);
            }
        }
Example #2
0
 public async Task <bool> IsEmailSubscribed(string email)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         return(await dataContext.EmailSubscriptions.AnyAsync(s => s.Email == email));
     }
 }
        public IEnumerable<CategoryModel> GetCategoriesTree()
        {
            List<CategoryModel> categoriesTree = new List<CategoryModel>();

            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                CategoriesConverter converter = new CategoriesConverter();
                List<CategoryModel> allCategories = dataContext.Categories.OrderBy(c => c.OrderIndex).
                    ToList().
                    Select(c => converter.ToModel(c)).
                    ToList();
                Dictionary<int, CategoryModel> categoriesDictionary = allCategories.ToDictionary(c => c.Id);

                foreach (CategoryModel categoryModel in allCategories)
                {
                    if (categoryModel.ParentCategoryId == null)
                    {
                        categoriesTree.Add(categoryModel);
                    }
                    else
                    {
                        int parentCategoryId = categoryModel.ParentCategoryId.Value;
                        CategoryModel parentCategory = categoriesDictionary[parentCategoryId];
                        parentCategory.ChildCategories.Add(categoryModel);
                    }
                }
            }

            return categoriesTree;
        }
        public async Task<IEnumerable<OrderModel>> GetOrdersByUserId(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable<OrderModel> userOrders = await dataContext.Orders.Where(o => o.UserId == userId).
                    OrderByDescending(o => o.DateCreated).
                    Include(o => o.OrderStatus).
                    Select(o => new OrderModel()
                    {
                        Id = o.Id,
                        DeliveryMerchant = o.DeliveryMerchant,
                        DeliveryPrice = o.DeliveryPrice,
                        HasComission = o.HasCommission,
                        CommissionPercents = o.CommissionPercents,
                        ShippingPrice = o.ShippingPrice,
                        ItemsPrice = o.ItemsPrice,
                        TotalPrice = o.TotalPrice,
                        Status = o.OrderStatus.Name,
                        DateCreated = o.DateCreated
                    }).
                    ToArrayAsync();

                return userOrders;
            }
        }
 public async Task<bool> IsEmailSubscribed(string email)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         return await dataContext.EmailSubscriptions.AnyAsync(s => s.Email == email);
     }
 }
Example #6
0
 public async Task <Order> GetFullOrderData(int orderId)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         return(await dataContext.Orders.Include(o => o.OrderDetails).Include(o => o.OrderDetails.Select(od => od.Article)).FirstOrDefaultAsync(o => o.Id == orderId));
     }
 }
        public async Task<IEnumerable<OrderItemModel>> GetOrderItems(int orderId, Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable<OrderItemModel> orderedItems = await dataContext.OrderDetails.
                    Include(od => od.Article).
                    Include(od => od.Size).
                    Include(od => od.Color).
                    Where(od => od.OrderId == orderId && od.Order.UserId == userId).
                    Select(od => new OrderItemModel()
                    {
                        ArticleTitle = od.Article.Title,
                        ArticleUrlName = od.Article.UrlName,
                        ThumbnailUrl = od.Article.ThumbnailUrl,
                        Size = od.Size.Name,
                        Color = od.ColorId == null ? null : od.Color.Title,
                        Quantity = od.Quantity,
                        ItemPrice = od.ItemPrice,
                    }).
                    OrderBy(oi => oi.ArticleTitle).
                    ToArrayAsync();

                return orderedItems;
            }
        }
        public IEnumerable <CategoryModel> GetCategoriesTree()
        {
            List <CategoryModel> categoriesTree = new List <CategoryModel>();

            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                CategoriesConverter  converter     = new CategoriesConverter();
                List <CategoryModel> allCategories = dataContext.Categories.OrderBy(c => c.OrderIndex).
                                                     ToList().
                                                     Select(c => converter.ToModel(c)).
                                                     ToList();
                Dictionary <int, CategoryModel> categoriesDictionary = allCategories.ToDictionary(c => c.Id);

                foreach (CategoryModel categoryModel in allCategories)
                {
                    if (categoryModel.ParentCategoryId == null)
                    {
                        categoriesTree.Add(categoryModel);
                    }
                    else
                    {
                        int           parentCategoryId = categoryModel.ParentCategoryId.Value;
                        CategoryModel parentCategory   = categoriesDictionary[parentCategoryId];
                        parentCategory.ChildCategories.Add(categoryModel);
                    }
                }
            }

            return(categoriesTree);
        }
 public async Task <bool> ArticleExists(int articleId)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         return(await dataContext.Articles.AnyAsync(a => a.Id == articleId));
     }
 }
Example #10
0
        public async Task <IEnumerable <OrderItemModel> > GetOrderItems(int orderId, Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable <OrderItemModel> orderedItems = await dataContext.OrderDetails.
                                                            Include(od => od.Article).
                                                            Include(od => od.Size).
                                                            Include(od => od.Color).
                                                            Where(od => od.OrderId == orderId && od.Order.UserId == userId).
                                                            Select(od => new OrderItemModel()
                {
                    ArticleTitle   = od.Article.Title,
                    ArticleUrlName = od.Article.UrlName,
                    ThumbnailUrl   = od.Article.ThumbnailUrl,
                    Size           = od.Size.Name,
                    Color          = od.ColorId == null ? null : od.Color.Title,
                    Quantity       = od.Quantity,
                    ItemPrice      = od.ItemPrice,
                }).
                                                            OrderBy(oi => oi.ArticleTitle).
                                                            ToArrayAsync();

                return(orderedItems);
            }
        }
 public async Task<IEnumerable<PaymentMethodModel>> GetAllPaymentMethods()
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         PaymentMethod[] paymentMethods = await dataContext.PaymentMethods.OrderBy(d => d.OrderIndex).ThenBy(d => d.Id).ToArrayAsync();
         return paymentMethods.Select(d => this.CreatePaymentMethodModel(d)).ToArray();
     }
 }
        public async Task <bool> HasArticleWithPrice(int articleId, decimal price)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                bool articleExists = await dataContext.Articles.AnyAsync(a => a.Id == articleId && (a.Price == price || a.OriginalPrice == price));

                return(articleExists);
            }
        }
        public async Task<PaymentMethodModel> GetPaymentMethodById(int paymentMethodId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                PaymentMethod foundPaymentMethod = await dataContext.PaymentMethods.FindAsync(paymentMethodId);

                return this.CreatePaymentMethodModel(foundPaymentMethod);
            }
        }
        public async Task<DeliveryMethodModel> GetDeliveryMethodById(int deliveryMethodId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                DeliveryMethod foundDeliveryMethod = await dataContext.DeliveryMethods.FindAsync(deliveryMethodId);

                return this.CreateDeliveryMethodModel(foundDeliveryMethod);
            }
        }
Example #15
0
        public async Task <PaymentMethodModel> GetPaymentMethodById(int paymentMethodId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                PaymentMethod foundPaymentMethod = await dataContext.PaymentMethods.FindAsync(paymentMethodId);

                return(this.CreatePaymentMethodModel(foundPaymentMethod));
            }
        }
        public async Task <DeliveryMethodModel> GetDeliveryMethodById(int deliveryMethodId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                DeliveryMethod foundDeliveryMethod = await dataContext.DeliveryMethods.FindAsync(deliveryMethodId);

                return(this.CreateDeliveryMethodModel(foundDeliveryMethod));
            }
        }
Example #17
0
        public ActionResult ReIndex()
        {
            using (PoshBoutiqueData db = new PoshBoutiqueData())
            {
                ArticlesIndexStore.Current.UpsertItems(db.Articles.ToList());
            }

            return(this.RedirectToAction("Index"));
        }
Example #18
0
        public async Task <IEnumerable <PaymentMethodModel> > GetAllPaymentMethods()
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                PaymentMethod[] paymentMethods = await dataContext.PaymentMethods.OrderBy(d => d.OrderIndex).ThenBy(d => d.Id).ToArrayAsync();

                return(paymentMethods.Select(d => this.CreatePaymentMethodModel(d)).ToArray());
            }
        }
        public async Task <bool> HasEnoughStocksOfArticle(int articleId, int sizeId, int?colorId, int quantity)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                int  colorIdValue    = colorId == null ? 0 : colorId.Value;
                bool hasEnoughStocks = await dataContext.Stocks.AnyAsync(s => s.ArticleId == articleId && s.SizeId == sizeId && s.ColorId == colorIdValue && s.Quantity >= quantity);

                return(hasEnoughStocks);
            }
        }
        public async Task<bool> HasEnoughStocksOfArticle(int articleId, int sizeId, int? colorId, int quantity)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                int colorIdValue = colorId == null ? 0 : colorId.Value;
                bool hasEnoughStocks = await dataContext.Stocks.AnyAsync(s => s.ArticleId == articleId && s.SizeId == sizeId && s.ColorId == colorIdValue && s.Quantity >= quantity);

                return hasEnoughStocks;
            }
        }
 public async Task UpdateOrdersCounts(IEnumerable <ArticleOrderCountModel> ordersCounts)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         foreach (ArticleOrderCountModel articleOrderCounts in ordersCounts)
         {
             await dataContext.Database.ExecuteSqlCommandAsync(
                 "UPDATE Articles SET OrdersCount = OrdersCount + @p1 WHERE Id = @p0",
                 articleOrderCounts.ArticleId,
                 articleOrderCounts.OrderCount);
         }
     }
 }
Example #22
0
        public HashSet <int> GetLikedArticlesByUser(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                List <int> userLikesIds = dataContext.UserLikes.Where(ul => ul.UserId == userId).Select(ul => ul.ArticleId).ToList();
                if (userLikesIds.Count == 0)
                {
                    return(null);
                }

                HashSet <int> userLikesSet = new HashSet <int>(userLikesIds);
                return(userLikesSet);
            }
        }
        public async Task CreateFeedbackSubmission(string email, string name, string message)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                dataContext.FeedbackSubmissions.Add(new FeedbackSubmission()
                {
                    Email = email,
                    Name = name,
                    Message = message
                });

                await dataContext.SaveChangesAsync();
            }
        }
        public HashSet<int> GetLikedArticlesByUser(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                List<int> userLikesIds = dataContext.UserLikes.Where(ul => ul.UserId == userId).Select(ul => ul.ArticleId).ToList();
                if (userLikesIds.Count == 0)
                {
                    return null;
                }

                HashSet<int> userLikesSet = new HashSet<int>(userLikesIds);
                return userLikesSet;
            }
        }
        public async Task CreateFeedbackSubmission(string email, string name, string message)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                dataContext.FeedbackSubmissions.Add(new FeedbackSubmission()
                {
                    Email   = email,
                    Name    = name,
                    Message = message
                });

                await dataContext.SaveChangesAsync();
            }
        }
        public async Task<SimpleOrderModel> GetOrder(int id)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Order order = await dataContext.Orders.FindAsync(id);

                return new SimpleOrderModel()
                {
                    Id = order.Id,
                    PaymentMethodId = order.PaymentMethodId,
                    TotalPrice = order.TotalPrice,
                    UserId = order.UserId
                };
            }
        }
Example #27
0
        public async Task <SimpleOrderModel> GetOrder(int id)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Order order = await dataContext.Orders.FindAsync(id);

                return(new SimpleOrderModel()
                {
                    Id = order.Id,
                    PaymentMethodId = order.PaymentMethodId,
                    TotalPrice = order.TotalPrice,
                    UserId = order.UserId
                });
            }
        }
        public async Task<int> SaveOrder(Order order, IEnumerable<OrderDetail> orderDetails)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                foreach (OrderDetail orderDetail in orderDetails)
                {
                    order.OrderDetails.Add(orderDetail);
                }

                dataContext.Orders.Add(order);

                await dataContext.SaveChangesAsync();
            }

            return order.Id;
        }
        public async Task<IEnumerable<CollectionModel>> GetAllCollections()
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable<CollectionModel> collection = await dataContext.Collections.OrderByDescending(c => c.DateCreated).Select(c => new CollectionModel()
                    {
                        Id = c.Id,
                        Name = c.Name,
                        Description = c.Description,
                        ImageUrl = c.ImageUrl,
                        DateCreated = c.DateCreated
                    }).ToListAsync();

                return collection;
            }
        }
        public IEnumerable <ArticleModel> GetArticlesByIds(IEnumerable <int> articleIds)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] articlesInCollection = dataContext.Articles.Where(a => articleIds.Contains(a.Id) && a.Visible).OrderByDescending(a => a.DateCreated).ToArray();
                if (articlesInCollection.Length == 0)
                {
                    return(null);
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[]    articlesInCollectionModels = articlesInCollection.Select(a => converter.ToModel(a, null)).ToArray();

                return(articlesInCollectionModels);
            }
        }
        public async Task <IEnumerable <CollectionModel> > GetAllCollections()
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable <CollectionModel> collection = await dataContext.Collections.OrderByDescending(c => c.DateCreated).Select(c => new CollectionModel()
                {
                    Id          = c.Id,
                    Name        = c.Name,
                    Description = c.Description,
                    ImageUrl    = c.ImageUrl,
                    DateCreated = c.DateCreated
                }).ToListAsync();

                return(collection);
            }
        }
Example #32
0
        public async Task <int> SaveOrder(Order order, IEnumerable <OrderDetail> orderDetails)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                foreach (OrderDetail orderDetail in orderDetails)
                {
                    order.OrderDetails.Add(orderDetail);
                }

                dataContext.Orders.Add(order);

                await dataContext.SaveChangesAsync();
            }

            return(order.Id);
        }
        public async Task<bool> UnregisterLike(Guid userId, int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                UserLike registeredLike = await dataContext.UserLikes.FirstAsync(ul => ul.UserId == userId && ul.ArticleId == articleId);
                if (registeredLike == null)
                {
                    return false;
                }

                dataContext.UserLikes.Remove(registeredLike);

                await dataContext.SaveChangesAsync();
            }

            return true;
        }
        public async Task <IEnumerable <ArticleModel> > GetRecommendedArticles()
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] articlesInCollection = await dataContext.Articles.Where(a => a.IsRecommended && a.Visible).OrderByDescending(a => a.DateCreated).ToArrayAsync();

                if (articlesInCollection.Length == 0)
                {
                    return(null);
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[]    articlesInCollectionModels = articlesInCollection.Select(a => converter.ToModel(a, null)).ToArray();

                return(articlesInCollectionModels);
            }
        }
Example #35
0
        public async Task <bool> UnregisterLike(Guid userId, int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                UserLike registeredLike = await dataContext.UserLikes.FirstAsync(ul => ul.UserId == userId && ul.ArticleId == articleId);

                if (registeredLike == null)
                {
                    return(false);
                }

                dataContext.UserLikes.Remove(registeredLike);

                await dataContext.SaveChangesAsync();
            }

            return(true);
        }
Example #36
0
        public async Task <IEnumerable <StatusHistoryModel> > GetOrderHistory(int orderId, Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable <StatusHistoryModel> statusHistory = await dataContext.OrderStatusesHistories.
                                                                 Include(h => h.OrderStatus).
                                                                 Where(h => h.OrderId == orderId && h.Order.UserId == userId).
                                                                 OrderBy(h => h.StatusAssignDate).
                                                                 Select(h => new StatusHistoryModel()
                {
                    Name         = h.OrderStatus.Name,
                    DateAssigned = h.StatusAssignDate
                })
                                                                 .ToArrayAsync();

                return(statusHistory);
            }
        }
Example #37
0
        public async Task <OrderStatusModel> GetStatus(int statusId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                OrderStatus orderStatus = await dataContext.OrderStatuses.FindAsync(statusId);

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

                return(new OrderStatusModel()
                {
                    Id = orderStatus.Id,
                    Name = orderStatus.Name
                });
            }
        }
        public async Task <bool> LikeArticle(int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article likedArticle = await dataContext.Articles.FindAsync(articleId);

                if (likedArticle == null)
                {
                    return(false);
                }

                likedArticle.LikesCount++;

                await dataContext.SaveChangesAsync();
            }

            return(true);
        }
        public async Task <ArticlesListModel> GetArticlesInCategory(string categoryUrl, string filter, string orderBy, SortDirection sortDirection, Guid?currentUserId)
        {
            ArticlesListModel articlesListModel = null;

            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Category category = await dataContext.Categories.FirstOrDefaultAsync(c => c.UrlName == categoryUrl);

                if (category == null && !categoryUrl.Equals(ArticlesProvider.ALL_CATEGORIES_URL_NAME, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(null);
                }

                articlesListModel          = new ArticlesListModel();
                articlesListModel.Category = new CategoriesConverter().ToModel(category);

                IQueryable <Article> articlesQuery = dataContext.Articles
                                                     .Where(article => article.Visible);
                if (category != null)
                {
                    articlesQuery = articlesQuery.Where(article => article.Categories.Any(c => c.Id == category.Id));
                }

                if (!string.IsNullOrEmpty(filter))
                {
                    articlesQuery = articlesQuery
                                    .Where(article => article.Title.Contains(filter) || article.Description.Contains(filter) || article.MaterialDescription.Contains(filter));
                }

                if (!string.IsNullOrEmpty(orderBy))
                {
                    articlesQuery = articlesQuery.Sort(orderBy, sortDirection);
                }

                List <Article> articlesList = await articlesQuery.ToListAsync();

                HashSet <int> userLikes = this.GetUserLikes(currentUserId);

                ArticlesConverter converter = new ArticlesConverter();
                articlesListModel.Articles = articlesList.Select(a => converter.ToModel(a, userLikes)).ToList();
            }

            return(articlesListModel);
        }
        public async Task <IEnumerable <ArticleModel> > GetFeaturedArticles(Guid?currentUserId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] featuredArticles = await dataContext.Articles.Where(a => a.IsFeatured && a.Visible).OrderByDescending(a => a.DateCreated).ToArrayAsync();

                if (featuredArticles.Length == 0)
                {
                    return(null);
                }

                HashSet <int> userLikes = this.GetUserLikes(currentUserId);

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[]    featuredArticlesModels = featuredArticles.Select(a => converter.ToModel(a, userLikes)).ToArray();

                return(featuredArticlesModels);
            }
        }
Example #41
0
        public async Task <bool> SubscribeEmail(string email)
        {
            if (await this.IsEmailSubscribed(email))
            {
                return(false);
            }

            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                dataContext.EmailSubscriptions.Add(new EmailSubscription()
                {
                    Email = email
                });

                await dataContext.SaveChangesAsync();
            }

            return(true);
        }
        public async Task<bool> SubscribeEmail(string email)
        {
            if (await this.IsEmailSubscribed(email))
            {
                return false;
            }

            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                dataContext.EmailSubscriptions.Add(new EmailSubscription()
                {
                    Email = email
                });

                await dataContext.SaveChangesAsync();
            }

            return true;
        }
        public async Task<ArticlesListModel> GetArticlesInCategory(string categoryUrl, string filter, string orderBy, SortDirection sortDirection, Guid? currentUserId)
        {
            ArticlesListModel articlesListModel = null;
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Category category = await dataContext.Categories.FirstOrDefaultAsync(c => c.UrlName == categoryUrl);
                if (category == null && !categoryUrl.Equals(ArticlesProvider.ALL_CATEGORIES_URL_NAME, StringComparison.InvariantCultureIgnoreCase))
                {
                    return null;
                }

                articlesListModel = new ArticlesListModel();
                articlesListModel.Category = new CategoriesConverter().ToModel(category);

                IQueryable<Article> articlesQuery = dataContext.Articles
                    .Where(article => article.Visible);
                if (category != null)
                {
                    articlesQuery = articlesQuery.Where(article => article.Categories.Any(c => c.Id == category.Id));
                }

                if (!string.IsNullOrEmpty(filter))
                {
                    articlesQuery = articlesQuery
                        .Where(article => article.Title.Contains(filter) || article.Description.Contains(filter) || article.MaterialDescription.Contains(filter));
                }

                if (!string.IsNullOrEmpty(orderBy))
                {
                    articlesQuery = articlesQuery.Sort(orderBy, sortDirection);
                }

                List<Article> articlesList = await articlesQuery.ToListAsync();
                HashSet<int> userLikes = this.GetUserLikes(currentUserId);

                ArticlesConverter converter = new ArticlesConverter();
                articlesListModel.Articles = articlesList.Select(a => converter.ToModel(a, userLikes)).ToList();
            }

            return articlesListModel;
        }
        public async Task<bool> RegisterLike(Guid userId, int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                bool isLikeRegistered = await dataContext.UserLikes.AnyAsync(ul => ul.UserId == userId && ul.ArticleId == articleId);
                if (isLikeRegistered)
                {
                    return false;
                }

                dataContext.UserLikes.Add(new UserLike()
                {
                    UserId = userId,
                    ArticleId = articleId
                });

                await dataContext.SaveChangesAsync();
            }

            return true;
        }
Example #45
0
        public async Task <bool> RegisterLike(Guid userId, int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                bool isLikeRegistered = await dataContext.UserLikes.AnyAsync(ul => ul.UserId == userId && ul.ArticleId == articleId);

                if (isLikeRegistered)
                {
                    return(false);
                }

                dataContext.UserLikes.Add(new UserLike()
                {
                    UserId    = userId,
                    ArticleId = articleId
                });

                await dataContext.SaveChangesAsync();
            }

            return(true);
        }
        public async Task <IEnumerable <ArticleModel> > GetRelatedArticles(int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article parentArticle = await dataContext.Articles.FindAsync(articleId);

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

                Article[] relatedArticles = parentArticle.RelatedArticles.OrderByDescending(a => a.DateCreated).ToArray();
                if (relatedArticles.Length == 0)
                {
                    return(null);
                }

                ArticlesConverter converter             = new ArticlesConverter();
                ArticleModel[]    relatedArticlesModels = relatedArticles.Select(a => converter.ToModel(a, null)).ToArray();

                return(relatedArticlesModels);
            }
        }
        public async Task <IEnumerable <ArticleModel> > GetLikedArticles(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IQueryable <UserLike> userLikesQuery = dataContext.UserLikes.Where(ul => ul.UserId == userId);
                Article[]             likedArticles  = await dataContext.Articles.Join(userLikesQuery, a => a.Id, ul => ul.ArticleId, (a, ul) => a).OrderBy(a => a.Title).ToArrayAsync();

                if (likedArticles.Length == 0)
                {
                    return(new ArticleModel[0]);
                }

                ArticlesConverter converter           = new ArticlesConverter();
                ArticleModel[]    likedArticlesModels = likedArticles.Select(a =>
                {
                    ArticleModel likedArticleModel = converter.ToModel(a, null);
                    likedArticleModel.IsLiked      = true;

                    return(likedArticleModel);
                }).ToArray();

                return(likedArticlesModels);
            }
        }
        public async Task<bool> HasArticleWithPrice(int articleId, decimal price)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                bool articleExists = await dataContext.Articles.AnyAsync(a => a.Id == articleId && (a.Price == price || a.OriginalPrice == price));

                return articleExists;
            }
        }
        public async Task<IEnumerable<StatusHistoryModel>> GetOrderHistory(int orderId, Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IEnumerable<StatusHistoryModel> statusHistory = await dataContext.OrderStatusesHistories.
                    Include(h => h.OrderStatus).
                    Where(h => h.OrderId == orderId && h.Order.UserId == userId).
                    OrderBy(h => h.StatusAssignDate).
                    Select(h => new StatusHistoryModel()
                    {
                        Name = h.OrderStatus.Name,
                        DateAssigned = h.StatusAssignDate
                    })
                    .ToArrayAsync();

                return statusHistory;
            }
        }
        public async Task<IEnumerable<ArticleModel>> GetArticlesInCollection(int collectionId, Guid? currentUserId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] articlesInCollection = await dataContext.Articles.Where(a => a.CollectionId == collectionId && a.Visible).OrderByDescending(a => a.DateCreated).ToArrayAsync();
                if (articlesInCollection.Length == 0)
                {
                    return null;
                }

                HashSet<int> userLikes = this.GetUserLikes(currentUserId);

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] articlesInCollectionModels = articlesInCollection.Select(a => converter.ToModel(a, userLikes)).ToArray();

                return articlesInCollectionModels;
            }
        }
        public async Task<IEnumerable<ArticleModel>> GetRelatedArticles(int articleId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article parentArticle = await dataContext.Articles.FindAsync(articleId);
                if (parentArticle == null)
                {
                    return null;
                }

                Article[] relatedArticles = parentArticle.RelatedArticles.OrderByDescending(a => a.DateCreated).ToArray();
                if (relatedArticles.Length == 0)
                {
                    return null;
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] relatedArticlesModels = relatedArticles.Select(a => converter.ToModel(a, null)).ToArray();

                return relatedArticlesModels;
            }
        }
        public async Task<OrderStatusModel> GetStatus(int statusId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                OrderStatus orderStatus = await dataContext.OrderStatuses.FindAsync(statusId);
                if (orderStatus == null)
                {
                    return null;
                }

                return new OrderStatusModel()
                {
                    Id = orderStatus.Id,
                    Name = orderStatus.Name
                };
            }
        }
        public async Task<IEnumerable<ArticleModel>> GetFeaturedArticles(Guid? currentUserId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] featuredArticles = await dataContext.Articles.Where(a => a.IsFeatured && a.Visible).OrderByDescending(a => a.DateCreated).ToArrayAsync();
                if (featuredArticles.Length == 0)
                {
                    return null;
                }

                HashSet<int> userLikes = this.GetUserLikes(currentUserId);

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] featuredArticlesModels = featuredArticles.Select(a => converter.ToModel(a, userLikes)).ToArray();

                return featuredArticlesModels;
            }
        }
 public async Task<Order> GetFullOrderData(int orderId)
 {
     using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
     {
         return await dataContext.Orders.Include(o => o.OrderDetails).Include(o => o.OrderDetails.Select(od => od.Article)).FirstOrDefaultAsync(o => o.Id == orderId);
     }
 }
        public async Task<IEnumerable<ArticleModel>> GetLikedArticles(Guid userId)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                IQueryable<UserLike> userLikesQuery = dataContext.UserLikes.Where(ul => ul.UserId == userId);
                Article[] likedArticles = await dataContext.Articles.Join(userLikesQuery, a => a.Id, ul => ul.ArticleId, (a, ul) => a).OrderBy(a => a.Title).ToArrayAsync();

                if (likedArticles.Length == 0)
                {
                    return new ArticleModel[0];
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] likedArticlesModels = likedArticles.Select(a => 
                    {
                        ArticleModel likedArticleModel = converter.ToModel(a, null);
                        likedArticleModel.IsLiked = true;

                        return likedArticleModel;
                    }).ToArray();

                return likedArticlesModels;
            }
        }
        public IEnumerable<ArticleModel> GetArticlesByIds(IEnumerable<int> articleIds)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] articlesInCollection = dataContext.Articles.Where(a => articleIds.Contains(a.Id) && a.Visible).OrderByDescending(a => a.DateCreated).ToArray();
                if (articlesInCollection.Length == 0)
                {
                    return null;
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] articlesInCollectionModels = articlesInCollection.Select(a => converter.ToModel(a, null)).ToArray();

                return articlesInCollectionModels;
            }
        }
        public async Task<IEnumerable<ArticleModel>> GetRecommendedArticles()
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                Article[] articlesInCollection = await dataContext.Articles.Where(a => a.IsRecommended && a.Visible).OrderByDescending(a => a.DateCreated).ToArrayAsync();
                if (articlesInCollection.Length == 0)
                {
                    return null;
                }

                ArticlesConverter converter = new ArticlesConverter();
                ArticleModel[] articlesInCollectionModels = articlesInCollection.Select(a => converter.ToModel(a, null)).ToArray();

                return articlesInCollectionModels;
            }
        }
        public async Task UpdateOrdersCounts(IEnumerable<ArticleOrderCountModel> ordersCounts)
        {
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                foreach (ArticleOrderCountModel articleOrderCounts in ordersCounts)
	            {
                    await dataContext.Database.ExecuteSqlCommandAsync(
                                    "UPDATE Articles SET OrdersCount = OrdersCount + @p1 WHERE Id = @p0",
                                    articleOrderCounts.ArticleId,
                                    articleOrderCounts.OrderCount);
	            }
            }
        }
        public async Task<bool> UpdateStocks(IEnumerable<StockChangeModel> stockChanges, ILogger logger)
        {
            if (stockChanges == null || !stockChanges.Any())
            {
                return true;
            }

            bool result = false;

            try
            {
                using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
                {
                    using (DbContextTransaction transaction = dataContext.Database.BeginTransaction())
                    {
                        try
                        {
                            foreach (StockChangeModel stockChange in stockChanges)
                            {
                                int stocksUpdatedCount = await dataContext.Database.ExecuteSqlCommandAsync(
                                    "UPDATE Stocks SET Quantity = Quantity + @p3 WHERE ArticleId = @p0 and SizeId = @p1 and ColorId = @p2",
                                    stockChange.ArticleId,
                                    stockChange.SizeId,
                                    stockChange.ColorId,
                                    stockChange.QuantityChange);

                                if (stocksUpdatedCount != 1)
                                {
                                    throw new InvalidOperationException(
                                        string.Format("Invalid updated stocks count: {0}. Change model: a: {1}, s: {2}, c: {3}, q: {4}",
                                            stocksUpdatedCount,
                                            stockChange.ArticleId,
                                            stockChange.SizeId,
                                            stockChange.ColorId,
                                            stockChange.QuantityChange));
                                }
                            }

                            transaction.Commit();

                            result = true;
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();

                            result = false;

                            logger.LogError(ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;

                logger.LogError(ex.ToString());
            }

            return result;
        }
        public FullArticleModel GetFullArticleByUrlName(string urlName, Guid? currentUserId)
        {
            FullArticleModel articleModel = null;
            using (PoshBoutiqueData dataContext = new PoshBoutiqueData())
            {
                string l = string.Empty;

                dataContext.Database.Log = s => l += s;

                Article article = dataContext.Articles
                    .Include(a => a.ArticleImages)
                    .Include(a => a.Stocks)
                    .Include(a => a.Stocks.Select(s => s.Color))
                    .Include(a => a.Stocks.Select(s => s.Size))
                    .FirstOrDefault(a => a.UrlName == urlName);

                articleModel = new FullArticleModel()
                {
                    Id = article.Id,
                    Title = article.Title,
                    UrlName = article.UrlName,
                    Description = article.Description,
                    MaterialDescription = article.MaterialDescription,
                    Price = article.Price,
                    OriginalPrice = article.OriginalPrice,
                    HasDiscount = article.OriginalPrice != null,
                    DiscountDescription = article.DiscountDescription,
                    ThumbnailUrl = article.ThumbnailUrl,
                    ShortDescription = article.ShortDescription
                };

                if (currentUserId == null)
                {
                    articleModel.IsLiked = false;
                }
                else
                {
                    articleModel.IsLiked = dataContext.UserLikes.Any(like => like.ArticleId == article.Id && like.UserId == currentUserId.Value);
                }

                Dictionary<int, SizeModel> sizesDictionary = article.Stocks.Select(s => s.Size).Distinct().ToDictionary(s => s.Id, s => new SizeModel()
                    {
                        Id = s.Id,
                        Name = s.Name,
                        OrderIndex = s.OrderIndex,
                        Quantity = 0
                    });

                foreach (Stock stock in article.Stocks)
                {
                    SizeModel sizeModel = sizesDictionary[stock.SizeId];
                    if (stock.ColorId == 0)
                    {
                        sizeModel.AddColor(null, stock.Quantity);

                        break;
                    }
                    else
                    {
                        sizeModel.AddColor(stock.Color, stock.Quantity);
                    }
                }

                articleModel.Sizes = sizesDictionary.Values.ToList().OrderBy(s => s.OrderIndex);
                articleModel.Images = article.ArticleImages.OrderBy(i => i.OrderIndex).Select(i => new ImageModel()
                    {
                        SmallUrl = i.SmallImageUrl,
                        MediumUrl = i.MediumImageUrl,
                        LargeUrl = i.LargelImageUrl
                    }).ToList();
            }

            return articleModel;
        }