Exemple #1
0
        public IEnumerable <SearchResultItem> Search(SearchParams searchParams, out int totalCount, int startIndex = 1, int count = 10)
        {
            var items =
                GetFromCacheOrLoadAndAddToCache(
                    $"SEARCHRESULT:{searchParams.SearchPattern?.ToLower()}:{string.Join(",",searchParams.SearchEntities.Select(x => x.FullName))}",
                    () =>
            {
                var strictResults =
                    _searchItemGateway.FindStrict(searchParams.SearchPattern, searchParams.SearchEntities);
                var fulltextResults  = _searchItemGateway.Find(searchParams.SearchPattern, searchParams.SearchEntities).OrderByDescending(x => x.Relevance);
                var dirtyResults     = strictResults.Concat(fulltextResults);
                var distinctByEntity = dirtyResults.Distinct(new SearchResultEqualityComparer()).ToList();
                return(distinctByEntity);
            });


            var dataRes = items.OrderByDescending(x => x.Relevance).Skip(startIndex - 1).Take(count);

            totalCount = items.Count;

            var res = new List <SearchResultItem>();

            foreach (var searchResultItem in dataRes)
            {
                var resItem = Mapper.Map <SearchResultItem>(searchResultItem);
                if (searchResultItem.HeartId.HasValue)
                {
                    // берём Url из Heart-ов, если определён HeartId
                    // на уровне базы в результате поиска есть ЛИБО heartId, ЛИБО url
                    resItem.Url = _heartService.GetCanonicalUrl(searchResultItem.HeartId.Value);
                }
                res.Add(resItem);
            }
            return(res);
        }
Exemple #2
0
        public int CreatePage(Page page)
        {
            page.Type = page.GetType().FullName;
            int heartId;

            using (var ts = new TransactionScope())
            {
                heartId      = _heartService.CreateHeart(page);
                page.HeartId = heartId;
                var newPage = Mapper.Map <Data.Models.Page>(page);
                _pageGateway.Insert(newPage);
                page.CanonicalUrl = _heartService.GetCanonicalUrl(page.RelativeUrl);
                _searchService.UpdateIndex(page);
                ts.Complete();
            }
            AddOrUpdateCacheObject(GetPageCacheKey(page.RelativeUrl), page);
            return(heartId);
        }
Exemple #3
0
        //private string GetCannonicalCategoryUrlPrefix(string relativeUrl)
        //{
        //    string res = String.Empty;
        //    bool hasParent = false;
        //    {
        //        var rec = _categoryGateway.SelectOneByRelativeUrl(relativeUrl);
        //        if (rec.ParentCategoryId.HasValue)
        //        {
        //            var parent = _categoryGateway.SelectOne(rec.ParentCategoryId.Value);
        //            res = parent.RelativeUrl;
        //            hasParent = parent.ParentCategoryId.HasValue;
        //        }
        //    }
        //    if (String.IsNullOrEmpty(res) || !hasParent)
        //    {
        //        return res;
        //    }
        //    return String.Format("{0}/{1}", GetCannonicalCategoryUrlPrefix(res), res);
        //}

        //private void FillCanonicalUrls(ICollection<Category> categories)
        //{
        //    foreach (var category in categories)
        //    {
        //        category.CanonicalUrl = GetCategoryCanonicalUrl(category.RelativeUrl);
        //        if (category.ChildrenCategories.Any())
        //        {
        //            FillCanonicalUrls(category.ChildrenCategories);
        //        }
        //    }
        //}

        public void FillData(Category category)
        {
            var heart = _heartService.GetHeart(category.HeartId);

            category.FillHeart(heart);
            category.CanonicalUrl = _heartService.GetCanonicalUrl(category.HeartId);

            foreach (var child in category.ChildrenCategories)
            {
                FillData(child);
            }
        }
Exemple #4
0
        private void FillData(GoodsItem goodsItem, bool activeActionsOnly = true)
        {
            var heart = _heartService.GetHeart(goodsItem.HeartId);

            goodsItem.FillHeart(heart);

            goodsItem.CanonicalUrl = _heartService.GetCanonicalUrl(heart.HeartId);

            FillImages(goodsItem);
            FillCompatibles(goodsItem);
            FillCats(goodsItem);
            FillActions(goodsItem, activeActionsOnly);
            FillPacks(goodsItem);
            FillSpecs(goodsItem);
            FillManufacturers(goodsItem);

            goodsItem.Rating = _goodsReviewService.GetGoodsRating(goodsItem.HeartId);

            if (activeActionsOnly)
            {
                goodsItem.Actions.Clear();
                goodsItem.Actions = _shopActionService.GetActiveActionsForGoodsItem(goodsItem.HeartId);
            }
        }
Exemple #5
0
        private void AddElementToYml(XmlDocument resultDocument, XmlNode offersElement, decimal bid, string siteUrl, YmlExportSettings settings, GoodsItem goodsItem, GoodsPack goodsPack = null)
        {
            XmlNode offerElement = resultDocument.CreateElement("offer");

            offersElement.AppendChild(offerElement);

            XmlAttribute currentAttribute = resultDocument.CreateAttribute("id");

            currentAttribute.Value = goodsPack == null?goodsItem.HeartId.ToString() : $"{goodsItem.HeartId}p{goodsPack.PackInfo.Size}";

            offerElement.Attributes.Append(currentAttribute);

            currentAttribute       = resultDocument.CreateAttribute("available");
            currentAttribute.Value = "true";
            offerElement.Attributes.Append(currentAttribute);

            if (bid != 0)
            {
                currentAttribute       = resultDocument.CreateAttribute("bid");
                currentAttribute.Value = bid.ToString(CultureInfo.InvariantCulture);
                offerElement.Attributes.Append(currentAttribute);
            }

            var url = _heartService.GetCanonicalUrl(goodsItem.HeartId);

            if (goodsPack != null)
            {
                url = $"{url}#p{goodsPack.PackInfo.Size}";
            }

            XmlNode currentElement = resultDocument.CreateElement("url");

            offerElement.AppendChild(currentElement);
            currentElement.InnerText = $"{siteUrl}/{url}";

            decimal price = goodsPack == null
                ? goodsItem.DiscountedPrice
                : goodsItem.DiscountedPriceForPack(goodsPack.PackId);

            currentElement = resultDocument.CreateElement("price");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = price.ToString(CultureInfo.InvariantCulture);

            decimal oldPrice = goodsPack == null
                ? goodsItem.Price
                : goodsItem.PriceForPack(goodsPack.PackId);

            if (oldPrice > price)
            {
                currentElement = resultDocument.CreateElement("oldprice");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = oldPrice.ToString(CultureInfo.InvariantCulture);
            }

            currentElement = resultDocument.CreateElement("currencyId");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = "RUR";

            currentElement = resultDocument.CreateElement("categoryId");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText =
                (goodsItem.ParentHeartId ?? goodsItem.Categories.First().ID).ToString();

            if (!string.IsNullOrEmpty(goodsItem.MainImageId))
            {
                currentElement = resultDocument.CreateElement("picture");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = $"{siteUrl}/Gallery/Image/{goodsItem.MainImageId}";
            }
            currentElement = resultDocument.CreateElement("pickup");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = settings.Pickup.ToString().ToLower();

            currentElement = resultDocument.CreateElement("delivery");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = "true";

            currentElement = resultDocument.CreateElement("name");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = goodsPack == null ? goodsItem.Name : $"{goodsItem.Name} {goodsPack.PackInfo.Name}";


            if (goodsItem.ManufacturerId.HasValue)
            {
                currentElement = resultDocument.CreateElement("vendor");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = goodsItem.Manufacturer.Name;
            }

            currentElement = resultDocument.CreateElement("description");
            offerElement.AppendChild(currentElement);
            currentElement.InnerText = goodsItem.Description;

            // Код ниже неверен
            if (goodsItem.CompatibleGoods.Any())
            {
                List <int> ids = new List <int>();
                foreach (var set in goodsItem.CompatibleGoods)
                {
                    foreach (var pair in set.CompatibleGoods)
                    {
                        ids.Add(pair.ID);
                    }
                }
                ids = ids.Distinct().ToList();
                string recs = String.Join(",", ids.Distinct());
                currentElement = resultDocument.CreateElement("rec");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = recs;
            }


            foreach (var specVal in goodsItem.GoodsSpecs)
            {
                currentElement = resultDocument.CreateElement("param");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = specVal.Value;

                currentAttribute       = resultDocument.CreateAttribute("name");
                currentAttribute.Value = specVal.Spec.Name;
                currentElement.Attributes.Append(currentAttribute);

                if (!String.IsNullOrEmpty(specVal.Spec.Postfix))
                {
                    currentAttribute       = resultDocument.CreateAttribute("unit");
                    currentAttribute.Value = specVal.Spec.Postfix;
                    currentElement.Attributes.Append(currentAttribute);
                }
            }

            if (goodsPack != null)
            {
                currentElement = resultDocument.CreateElement("param");
                offerElement.AppendChild(currentElement);
                currentElement.InnerText = goodsPack.PackInfo.Size.ToString(CultureInfo.InvariantCulture);

                currentAttribute       = resultDocument.CreateAttribute("name");
                currentAttribute.Value = "Вес";
                currentElement.Attributes.Append(currentAttribute);

                currentAttribute       = resultDocument.CreateAttribute("unit");
                currentAttribute.Value = goodsPack.PackInfo.Dimension.Short;
                currentElement.Attributes.Append(currentAttribute);
            }
        }
Exemple #6
0
        public ICollection <NewsItem> GetNewsPage(NewsFilter filter, int pageNumber, int pageSize, out int totalCount)
        {
            ICollection <int> newsIds;

            if (string.IsNullOrWhiteSpace(filter.TextQuery))
            {
                // если поискового запроса нет, забираем айдишники вообще всех новостей
                //TODO: для ускорения можно закэшировать
                newsIds = _newsItemGateway.SelectIds();
            }
            else
            {
                // если есть поисковый запрос, забираем из поискового индекса айдишники нужных
                int searchTotal;
                var searchResults =
                    _searchService.Search(new SearchParams(filter.TextQuery, new Type[] { typeof(NewsItem) }),
                                          out searchTotal, 1, int.MaxValue);
                newsIds = searchResults.Select(x => int.Parse(x.EntityId)).Distinct().ToList();
            }
            if (!newsIds.Any())
            {
                // если после фильтрации ничего не осталось, возвращаем пустой список
                totalCount = 0;
                return(new List <NewsItem>());
            }

            if (!string.IsNullOrEmpty(filter.CategoryQuery))
            {
                newsIds = FilterByCategories(newsIds, filter.CategoryQuery);
                if (!newsIds.Any())
                {
                    // если после фильтрации ничего не осталось, возвращаем пустой список
                    totalCount = 0;
                    return(new List <NewsItem>());
                }
            }

            if (!string.IsNullOrEmpty(filter.TagName))
            {
                newsIds = FilterByTag(newsIds, filter.TagName);
                if (!newsIds.Any())
                {
                    // если после фильтрации ничего не осталось, возвращаем пустой список
                    totalCount = 0;
                    return(new List <NewsItem>());
                }
            }

            var dataFilter = new FinalNewsFilter()
            {
                OnlyPosted          = filter.OnlyPosted,
                NewsIds             = newsIds,
                BlogId              = filter.BlogId,
                OnlyFutureEventDate = filter.OnlyFutureEventDate,
                RecordTypes         = filter.RecordTypes.Select(x => x.ToString()).ToArray(),
                SortBy              = filter.SortBy.ToString(),
                SortOrder           = filter.SortOrder
            };
            var dataRes = _newsItemGateway.SelectFilteredPage(dataFilter, pageNumber, pageSize, out totalCount);
            var res     = Mapper.Map <ICollection <NewsItem> >(dataRes);

            var hearts = _heartService.GetHearts(res.Select(x => x.HeartId));

            foreach (var newsItem in res)
            {
                var heart = hearts.Single(x => x.HeartId == newsItem.HeartId);
                newsItem.FillHeart(heart);
                newsItem.CanonicalUrl = _heartService.GetCanonicalUrl(heart.HeartId);
                FillItem(newsItem);
            }
            return(res);
        }