public virtual async Task <Contact> GetContactByIdAsync(string contactId)
        {
            if (contactId == null)
            {
                throw new ArgumentNullException(nameof(contactId));
            }

            Contact result   = null;
            var     cacheKey = CacheKey.With(GetType(), "GetContactByIdAsync", contactId);
            var     dto      = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var contactDto = await _customerApi.GetContactByIdAsync(contactId);
                if (contactDto != null)
                {
                    cacheEntry.AddExpirationToken(CustomerCacheRegion.CreateChangeToken(contactDto.Id));
                    cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                }
                return(contactDto);
            });

            if (dto != null)
            {
                result = dto.ToContact();
                if (!dto.Organizations.IsNullOrEmpty())
                {
                    //Load contact organization
                    result.Organization = await GetOrganizationByIdAsync(dto.Organizations.FirstOrDefault());
                }
            }
            return(result);
        }
Beispiel #2
0
        public virtual async Task EvaluateProductInventoriesAsync(IEnumerable <Product> products, WorkContext workContext)
        {
            if (products == null)
            {
                throw new ArgumentNullException(nameof(products));
            }
            var productIds  = products.Select(x => x.Id).ToList();
            var cacheKey    = CacheKey.With(GetType(), "EvaluateProductInventoriesAsync", string.Join("-", productIds.OrderBy(x => x)));
            var inventories = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.SetAbsoluteExpiration(TimeSpan.FromMinutes(1));
                cacheEntry.AddExpirationToken(InventoryCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                return(await _inventoryApi.GetProductsInventoriesByPlentyIdsAsync(productIds));
            });

            var availFullfilmentCentersIds = workContext.CurrentStore.AvailFulfillmentCenterIds;

            foreach (var item in products)
            {
                //TODO: Change these conditions to DDD specification
                item.InventoryAll = inventories.Where(x => x.ProductId == item.Id).Select(x => x.ToInventory()).Where(x => availFullfilmentCentersIds.Contains(x.FulfillmentCenterId)).ToList();
                item.Inventory    = item.InventoryAll.OrderByDescending(x => Math.Max(0, (x.InStockQuantity ?? 0L) - (x.ReservedQuantity ?? 0L))).FirstOrDefault();

                if (workContext.CurrentStore.DefaultFulfillmentCenterId != null)
                {
                    item.Inventory = item.InventoryAll.FirstOrDefault(x => x.FulfillmentCenterId == workContext.CurrentStore.DefaultFulfillmentCenterId)
                                     ?? item.Inventory;
                }
            }
        }
Beispiel #3
0
        protected virtual async Task <Product[]> GetProductsAsync(IList <string> ids, ItemResponseGroup responseGroup, WorkContext workContext)
        {
            var cacheKey = CacheKey.With(GetType(), "GetProductsAsync", string.Join("-", ids.OrderBy(x => x)), responseGroup.ToString());
            var result   = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                return(await _productsApi.GetProductByPlentyIdsAsync(ids, ((int)responseGroup).ToString()));
            });

            return(result.Select(x => x.ToProduct(workContext.CurrentLanguage, workContext.CurrentCurrency, workContext.CurrentStore)).ToArray());
        }
Beispiel #4
0
        public async Task <IPagedList <Model.CustomerReviews.CustomerReview> > GetCustomerReviewsAsync(CustomerReviewSearchCriteria criteria)
        {
            var workContext = _workContextAccessor.WorkContext;
            var cacheKey    = CacheKey.With(GetType(), nameof(GetCustomerReviewsAsync), criteria.GetCacheKey(), workContext.CurrentLanguage.CultureName);

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) => {
                cacheEntry.AddExpirationToken(CustomerReviewCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                var result = await _customerReviewsApi.SearchCustomerReviewsAsync(criteria.ToSearchCriteriaDto());
                return new StaticPagedList <Model.CustomerReviews.CustomerReview>(result.Results.Select(x => x.ToCustomerReview()), criteria.PageNumber, criteria.PageSize, result.TotalCount.Value);
            }));
        }
Beispiel #5
0
        public async Task <Model.Stores.Store[]> GetAllStoresAsync()
        {
            var cacheKey = CacheKey.With(GetType(), "GetAllStoresAsync");

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(StoreCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                var storeDtos = await _storeApi.GetStoresAsync();
                return await Task.WhenAll(storeDtos.Select(x => ConvertStoreAndLoadDependeciesAsync(x)));
            }, cacheNullValue : false));
        }
        public async Task <IPagedList <CutomerReviewModel> > SearchReviewAsync(CustomerReviewSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchReviewAsync), criteria.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.ExpirationTokens.Add(CustomerReviewCacheRegion.CreateChangeToken(criteria.ProductIds.FirstOrDefault()));
                cacheEntry.ExpirationTokens.Add(_apiChangesWatcher.CreateChangeToken());

                var result = await _customerReviews.SearchCustomerReviewsAsync(criteria.ToSearchCriteriaDto());
                return new StaticPagedList <CutomerReviewModel>(result.Results.Select(c => c.ToCustomerReview()),
                                                                criteria.PageNumber, criteria.PageSize, result.TotalCount.Value);
            }
                                                                ));
        }
        public virtual async Task <string> GetDynamicContentHtmlAsync(string storeId, string placeholderName)
        {
            string htmlContent = null;

            //TODO: make full context
            var evaluationContext = new DynamicContentEvaluationContext
            {
                StoreId   = storeId,
                PlaceName = placeholderName
            };

            var cacheKey = CacheKey.With(GetType(), "GetDynamicContentHtmlAsync", storeId, placeholderName);

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(MarketingCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                var dynamicContentItems = (await _dynamicContentApi.EvaluateDynamicContentAsync(evaluationContext)).Select(x => x.ToDynamicContentItem());

                if (dynamicContentItems != null)
                {
                    var htmlContentSpec = new HtmlDynamicContentSpecification();
                    var htmlDynamicContent = dynamicContentItems.FirstOrDefault(htmlContentSpec.IsSatisfiedBy);
                    if (htmlDynamicContent != null)
                    {
                        var dynamicProperty = htmlDynamicContent.DynamicProperties.FirstOrDefault(htmlContentSpec.IsSatisfiedBy);
                        if (dynamicProperty != null && dynamicProperty.Values.Any(v => v.Value != null))
                        {
                            htmlContent = dynamicProperty.Values.First().Value.ToString();
                        }
                    }
                }
                return htmlContent;
            }));
        }
Beispiel #8
0
        public async Task <IPagedList <CustomerReview> > SearchReviewsAsync(CustomerReviewSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), nameof(SearchReviewsAsync), criteria.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(
                       cacheKey,
                       async cacheEntry =>
            {
                var reviewsChangeToken = CustomerReviewCacheRegion.CreateChangeToken();
                cacheEntry.AddExpirationToken(reviewsChangeToken);

                var apiChangeToken = _apiChangesWatcher.CreateChangeToken();
                cacheEntry.AddExpirationToken(apiChangeToken);

                var searchCriteriaDto = criteria.ToApiSearchCriteria();
                var foundCustomerReviews = await _customerReviewsApi.SearchCustomerReviewsAsync(searchCriteriaDto);
                var totalCount = foundCustomerReviews.TotalCount ?? 0;

                var customerReviews =
                    foundCustomerReviews.Results.Select(customerReview => customerReview.ToCustomerReview());
                return new StaticPagedList <CustomerReview>(
                    customerReviews,
                    criteria.PageNumber,
                    criteria.PageSize,
                    totalCount);
            }));
        }
        public async Task <Product[]> GetRecommendationsAsync(RecommendationEvalContext context)
        {
            var dynamicAssociationsContext = context as DynamicAssociationsEvalContext;

            if (dynamicAssociationsContext == null)
            {
                throw new InvalidCastException(nameof(context));
            }

            var cacheKey = CacheKey.With(GetType(), nameof(GetRecommendationsAsync), context.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(RecommendationsCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                var result = new List <Product>();
                var recommendedProductIds = await _associationsApi.EvaluateDynamicAssociationsAsync(dynamicAssociationsContext.ToContextDto());

                if (recommendedProductIds != null)
                {
                    result.AddRange(await _catalogService.GetProductsAsync(recommendedProductIds.ToArray(), ItemResponseGroup.Seo | ItemResponseGroup.Outlines | ItemResponseGroup.ItemWithPrices | ItemResponseGroup.ItemWithDiscounts | ItemResponseGroup.Inventory));
                }

                return result.ToArray();
            }));
        }
        public virtual async Task <Category[]> GetCategoriesAsync(string[] ids, CategoryResponseGroup responseGroup = CategoryResponseGroup.Info)
        {
            var workContext   = _workContextAccessor.WorkContext;
            var cacheKey      = CacheKey.With(GetType(), nameof(GetCategoriesAsync), string.Join("-", ids.OrderBy(x => x)), responseGroup.ToString());
            var categoriesDto = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                return(await _categoriesApi.GetCategoriesByPlentyIdsAsync(ids.ToList(), ((int)responseGroup).ToString()));
            });

            var result = categoriesDto.Select(x => x.ToCategory(workContext.CurrentLanguage, workContext.CurrentStore)).ToArray();

            //Set  lazy loading for child categories
            EstablishLazyDependenciesForCategories(result);
            return(result);
        }
        protected virtual async Task <IList <coreDto.SeoInfo> > GetAllSeoRecordsAsync(string slug)
        {
            var result = new List <coreDto.SeoInfo>();

            if (!string.IsNullOrEmpty(slug))
            {
                var cacheKey  = CacheKey.With(GetType(), "GetAllSeoRecords", slug);
                var apiResult = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
                {
                    cacheEntry.AddExpirationToken(RoutingCacheRegion.CreateChangeToken());
                    cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                    return(await _coreApi.GetSeoInfoBySlugAsync(slug));
                });

                result.AddRange(apiResult);
            }
            return(result);
        }
Beispiel #12
0
        public virtual async Task <IList <Pricelist> > EvaluatePricesListsAsync(PriceEvaluationContext evalContext, WorkContext workContext)
        {
            if (evalContext == null)
            {
                throw new ArgumentNullException(nameof(evalContext));
            }
            if (workContext == null)
            {
                throw new ArgumentNullException(nameof(workContext));
            }
            var cacheKey = CacheKey.With(GetType(), "EvaluatePricesListsAsync", evalContext.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(PricingCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                return (await _pricingApi.EvaluatePriceListsAsync(evalContext.ToPriceEvaluationContextDto())).Select(x => x.ToPricelist(workContext.AllCurrencies, workContext.CurrentLanguage)).ToList();
            }));
        }
        public async Task <Currency[]> GetAllCurrenciesAsync(Language language)
        {
            var cacheKey = CacheKey.With(GetType(), language.CultureName);

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                return (await _commerceApi.GetAllCurrenciesAsync()).Select(x => x.ToCurrency(language)).ToArray();
            }));
        }
        public async Task <Model.Stores.Store[]> GetAllStoresAsync()
        {
            var cacheKey = CacheKey.With(GetType(), "GetAllStoresAsync");

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(StoreCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                return (await _storeApi.GetStoresAsync()).Select(x => x.ToStore()).ToArray();
            }, cacheNullValue : false));
        }
        public virtual async Task <IEnumerable <DynamicContentItem> > EvaluateDynamicContentItemsAsync(DynamicContentEvaluationContext evalContext)
        {
            var cacheKey = CacheKey.With(GetType(), "EvaluateDynamicContentItemsAsync", evalContext.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(MarketingCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                var evalContextDto = evalContext.ToDynamicContentEvaluationContextDto();
                var dynamicContentItems = (await _dynamicContentApi.EvaluateDynamicContentAsync(evalContextDto)).Select(x => x.ToDynamicContentItem());

                return dynamicContentItems;
            }));
        }
Beispiel #16
0
        /// <summary>
        /// Async search categories by given criteria
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public virtual async Task <IPagedList <Category> > SearchCategoriesAsync(CategorySearchCriteria criteria)
        {
            var workContext  = _workContextAccessor.WorkContext;
            var cacheKey     = CacheKey.With(GetType(), "SearchCategoriesAsync", criteria.GetCacheKey(), workContext.CurrentStore.Id, workContext.CurrentLanguage.CultureName, workContext.CurrentCurrency.Code);
            var searchResult = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                criteria           = criteria.Clone() as CategorySearchCriteria;
                var searchCriteria = criteria.ToCategorySearchCriteriaDto(workContext);
                return(await _searchApi.SearchCategoriesAsync(searchCriteria));
            });

            var result = new PagedList <Category>(new List <Category>().AsQueryable(), 1, 1);

            if (searchResult.Items != null)
            {
                result = new PagedList <Category>(searchResult.Items.Select(x => x.ToCategory(workContext.CurrentLanguage, workContext.CurrentStore)).AsQueryable(), criteria.PageNumber, criteria.PageSize);
            }
            //Set  lazy loading for child categories
            EstablishLazyDependenciesForCategories(result.ToArray());
            return(result);
        }
Beispiel #17
0
        public async Task <IDictionary <string, object> > GetMemberIndexByIdAsync(string memberId)
        {
            ValidateParameters(memberId);

            var cacheKey = CacheKey.With(GetType(), "GetMemberIndexByIdAsync", memberId);
            var result   = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var indexDto = await _demoSearchApi.GetDocumentIndexAsyncAsync(nameof(Member), memberId);

                cacheEntry.AddExpirationToken(CustomerCacheRegion.CreateChangeToken(memberId));
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                return(indexDto);
            });

            return(result);
        }
        public async Task <IPagedList <FulfillmentCenter> > SearchFulfillmentCentersAsync(FulfillmentCenterSearchCriteria criteria)
        {
            var cacheKey = CacheKey.With(GetType(), "SearchFulfillmentCenters", criteria.GetCacheKey());

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(InventoryCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                var criteriaDto = new inventoryDto.FulfillmentCenterSearchCriteria
                {
                    SearchPhrase = criteria.SearchPhrase,
                    Skip = (criteria.PageNumber - 1) * criteria.PageSize,
                    Take = criteria.PageSize,
                    Sort = criteria.Sort
                };

                var searchResult = await _inventoryApi.SearchFulfillmentCentersAsync(criteriaDto);
                var centers = searchResult.Results.Select(x => x.ToFulfillmentCenter());
                return new StaticPagedList <FulfillmentCenter>(centers, criteria.PageNumber, criteria.PageSize, searchResult.TotalCount.Value);
            }));
        }
        public async Task <ProductPart[]> GetProductPartsAsync(string productId)
        {
            var workContext = _workContextAccessor.WorkContext;
            var cacheKey    = CacheKey.With(GetType(), nameof(GetProductPartsAsync), productId);

            var searchResult = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(CatalogCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                var searchPartsResultDto = await _demoCatalogApi.SearchAsync(new DemoProductPartSearchCriteria {
                    ConfiguredProductId = productId, Take = int.MaxValue
                });
                return(searchPartsResultDto);
            });

            var partItemIds = searchResult.Results?
                              .Where(x => x.PartItems != null).SelectMany(x => x.PartItems).Select(x => x.ItemId).Distinct()
                              .ToArray();

            var allPartItems = !partItemIds.IsNullOrEmpty() ? await GetProductsAsync(partItemIds) : null; // Potential recursion

            ProductPart ConvertDtoToProductPartAndAttachItsItems(DemoProductPart x, WorkContext workContext, Product[] allPartItems)
            {
                var productPart = x.ToProductPart(workContext.CurrentLanguage.CultureName);

                productPart.Items = x.PartItems?
                                    .OrderBy(partItemInfo => partItemInfo.Priority)
                                    .Select(partItemInfo => allPartItems?.FirstOrDefault(product => product.Id.EqualsInvariant(partItemInfo.ItemId)))
                                    .Where(product => product != null)
                                    .ToArray() ?? Array.Empty <Product>();
                return(productPart);
            }

            var productParts = searchResult.Results?.OrderBy(x => x.Priority).Select(x => ConvertDtoToProductPartAndAttachItsItems(x, workContext, allPartItems))
                               .ToArray <ProductPart>() ?? Array.Empty <ProductPart>();

            return(productParts);
        }
        public virtual async Task <Contact> GetContactByIdAsync(string contactId)
        {
            Contact result   = null;
            var     cacheKey = CacheKey.With(GetType(), "GetContactByIdAsync", contactId);
            var     dto      = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                var contactDto = await _customerApi.GetContactByIdAsync(contactId);
                if (contactDto != null)
                {
                    cacheEntry.AddExpirationToken(CustomerCacheRegion.CreateChangeToken(contactDto.Id));
                    cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());
                }
                return(contactDto);
            });

            if (dto != null)
            {
                result               = dto.ToContact();
                result.Orders        = LazyLoadCustomerOrders(result);
                result.QuoteRequests = LazyLoadCustomerQuotes(result);
                result.Subscriptions = LazyLoadCustomerSubscriptions(result);
            }
            return(result);
        }
Beispiel #21
0
        public async Task <IList <MenuLinkList> > LoadAllStoreLinkListsAsync(Store store, Language language)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store));
            }
            var cacheKey = CacheKey.With(GetType(), "LoadAllStoreLinkListsAsync", store.Id, language.CultureName);

            return(await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) =>
            {
                cacheEntry.AddExpirationToken(StaticContentCacheRegion.CreateChangeToken());
                cacheEntry.AddExpirationToken(_apiChangesWatcher.CreateChangeToken());

                var result = new List <MenuLinkList>();
                var listsDto = await _cmsApi.GetListsAsync(store.Id);
                if (listsDto != null)
                {
                    result.AddRange(listsDto.Select(x => x.ToMenuLinkList()));
                }

                result = result.GroupBy(x => x.Name).Select(x => x.FindWithLanguage(language)).Where(x => x != null).ToList().ToList();

                var allMenuLinks = result.SelectMany(x => x.MenuLinks).ToList();
                var productLinks = allMenuLinks.OfType <ProductMenuLink>().ToList();
                var categoryLinks = allMenuLinks.OfType <CategoryMenuLink>().ToList();

                Task <Product[]> productsLoadingTask = null;
                Task <Category[]> categoriesLoadingTask = null;

                //Parallel loading associated objects
                var productIds = productLinks.Select(x => x.AssociatedObjectId).ToArray();
                if (productIds.Any())
                {
                    productsLoadingTask = _catalogService.GetProductsAsync(productIds, ItemResponseGroup.ItemSmall);
                }
                var categoriesIds = categoryLinks.Select(x => x.AssociatedObjectId).ToArray();
                if (categoriesIds.Any())
                {
                    categoriesLoadingTask = _catalogService.GetCategoriesAsync(categoriesIds, CategoryResponseGroup.Info | CategoryResponseGroup.WithImages | CategoryResponseGroup.WithSeo | CategoryResponseGroup.WithOutlines);
                }
                //Populate link by associated product
                if (productsLoadingTask != null)
                {
                    var products = await productsLoadingTask;
                    foreach (var productLink in productLinks)
                    {
                        productLink.Product = products.FirstOrDefault(x => x.Id == productLink.AssociatedObjectId);
                    }
                }
                //Populate link by associated category
                if (categoriesLoadingTask != null)
                {
                    var categories = await categoriesLoadingTask;
                    foreach (var categoryLink in categoryLinks)
                    {
                        categoryLink.Category = categories.FirstOrDefault(x => x.Id == categoryLink.AssociatedObjectId);
                    }
                }

                return result.ToList();
            }));
        }