Ejemplo n.º 1
0
        public void ExportAllProductRecommendations()
        {
            var catalog = _contentLoader
                          .GetChildren <CatalogContent>(_referenceConverter.GetRootLink())
                          .FirstOrDefault();

            if (catalog == null)
            {
                return;
            }

            ExportProductRecommendations(catalog, ExportState);
        }
        private void ExportCategoryStructure(string tagsUrl, string foldersUrl)
        {
            var root  = _contentLoader.GetChildren <CatalogContent>(_referenceConverter.GetRootLink());
            var first = root.FirstOrDefault();

            var children = _contentLoader.GetChildren <NodeContent>(first.ContentLink);

            var result = BuildTagsAndFolders(children);

            if (ExportState != null)
            {
                ExportState.ModelName = "tags and folders";
                ExportState.Total     = result.Folders.Aggregate(0, (a, f) => a + f.CountNodesInTree()) + result.Tags.Count;
            }

            Post(result.Tags.Values.ToList(), tagsUrl);
            if (ExportState != null)
            {
                ExportState.Uploaded += result.Tags.Count;
            }

            Post(result.Folders, foldersUrl);

            ResetState(false);
        }
        public override List <Feed> Build()
        {
            var generatedFeeds = new List <Feed>();

            var feed = GenerateFeedEntity() ?? throw new ArgumentNullException($"{nameof(GenerateFeedEntity)} returned null");

            var entries           = new List <Entry>();
            var catalogReferences = _contentLoader.GetDescendents(_referenceConverter.GetRootLink());

            foreach (var catalogReference in catalogReferences)
            {
                var catalogContent = _contentLoader.Get <CatalogContentBase>(catalogReference);
                var entry          = GenerateEntry(catalogContent);

                if (entry != null)
                {
                    entries.Add(entry);
                }
            }

            feed.Entries = entries;
            generatedFeeds.Add(feed);

            return(generatedFeeds);
        }
        public override ActionResult Index()
        {
            var model = new BestBetsViewModel(CurrentLanguage)
            {
                BestBetsByLanguage = GetBestBetsByLanguage(),
                TypeName           = GetTypeName(),
            };

            bool commerceSelected = _settings.GetCommerceIndexName(CurrentLanguage).Equals(CurrentIndex);

            if (commerceSelected)
            {
                model.SearchProviderKey = "catalog";
                model.SelectorTypes     = new List <string> {
                    typeof(EntryContentBase).FullName.ToLower()
                };
                model.SelectorRoots = new List <ContentReference> {
                    _referenceConverter.GetRootLink()
                };
            }
            else
            {
                model.SearchProviderKey = "pages";
            }

            return(View("~/Views/ElasticSearchAdmin/BestBets/Index.cshtml", model));
        }
        public void Dump()
        {
            var languageBranch = _languageBranchRepository.ListAll().First();

            var currentMarket = _currentMarket.GetCurrentMarket();
            var market        = (MarketImpl)_marketService.GetMarket(currentMarket.MarketId);

            market.DefaultCurrency = Currency.EUR;
            market.DefaultLanguage = languageBranch.Culture;
            _marketService.UpdateMarket(market);

            var rootLink = _referenceConverter.GetRootLink();
            var catalog  = _contentRepository.GetDefault <CatalogContent>(rootLink, languageBranch.Culture);

            catalog.Name             = "Catalog";
            catalog.DefaultCurrency  = market.DefaultCurrency;
            catalog.CatalogLanguages = new ItemCollection <string> {
                languageBranch.LanguageID
            };
            catalog.DefaultLanguage = "en";
            catalog.WeightBase      = "kg";
            catalog.LengthBase      = "cm";
            var catalogRef = _contentRepository.Save(catalog, SaveAction.Publish, AccessLevel.NoAccess);

            var category = _contentRepository.GetDefault <NodeContent>(catalogRef);

            category.Name        = "Category";
            category.DisplayName = "Category";
            category.Code        = "category";
            var categoryRef = _contentRepository.Save(category, SaveAction.Publish, AccessLevel.NoAccess);

            var product = _contentRepository.GetDefault <ProductContent>(categoryRef);

            product.Name        = "Product";
            product.DisplayName = "Product";
            product.Code        = "product";
            var productRef = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var variant = _contentRepository.GetDefault <VariationContent>(productRef);

            variant.Name        = "Variant";
            variant.DisplayName = "Variant";
            variant.Code        = "test";
            variant.MinQuantity = 1;
            variant.MaxQuantity = 100;
            _contentRepository.Save(variant, SaveAction.Publish, AccessLevel.NoAccess);

            var price = new PriceValue
            {
                UnitPrice       = new Money(100, market.DefaultCurrency),
                CatalogKey      = new CatalogKey(variant.Code),
                MarketId        = market.MarketId,
                ValidFrom       = DateTime.Today.AddYears(-1),
                ValidUntil      = DateTime.Today.AddYears(1),
                CustomerPricing = CustomerPricing.AllCustomers,
                MinQuantity     = 0
            };

            _priceService.SetCatalogEntryPrices(price.CatalogKey, new[] { price });
        }
Ejemplo n.º 6
0
 private void UpdateAllCatalogContent()
 {
     foreach (var catalog in _contentRepository.GetChildren <CatalogContent>(_referenceConverter.GetRootLink()))
     {
         UpdateCatalogContentRecursive(catalog.ContentLink, new CultureInfo("en"));
     }
 }
Ejemplo n.º 7
0
        public override string Execute()
        {
            var tokinizer     = new Tokinizer(stopwords);
            var documentStore = new DocumentStorageMemory();
            var vocabulary    = new Vocabulary();
            var search        = new SearchEngine(vocabulary, documentStore, tokinizer);

            var bigram = new NGram(2, new Sentencezer(new Tokinizer(new HashSet <string>()
            {
                "-", "\"", "(", ")", ":", ";", ","
            })));
            var trigram = new NGram(3, new Sentencezer(new Tokinizer(new HashSet <string>()
            {
                "-", "\"", "(", ")", ":", ";", ","
            })));
            var numberOfDocuments = 0;

            foreach (var contentData in _contentLoader.GetAllChildren <MovieProduct>(_referenceConverter.GetRootLink()))
            {
                if (contentData is ISearch movieProduct)
                {
                    search.Indexing <ISearch>(contentData.ContentLink.ID, movieProduct);
                    bigram.Insert <ISearch>(movieProduct);
                    trigram.Insert <ISearch>(movieProduct);
                    numberOfDocuments++;
                    Debug.WriteLine(movieProduct.Title);
                }
            }

            _blobRepository.Save("BiGram", bigram.Export());
            _blobRepository.Save("TriGram", trigram.Export());
            _blobRepository.Save("Vocabulary", vocabulary.Export());
            _blobRepository.Save("Search", search.Export());
            return($"Number of documents; {numberOfDocuments}, number of words {vocabulary.Count()}");
        }
Ejemplo n.º 8
0
        public void CheckReferenceConverter()
        {
            // variationController has demo code for "Loading examples"
            ContentReference theRef = _referenceConverter.GetContentLink("Shirts_1");
            int theInt = _referenceConverter.GetObjectId(theRef);

            CatalogContentType theType = _referenceConverter.GetContentType(theRef);

            ContentReference theSameRef = _referenceConverter.GetContentLink
                                              (theInt, CatalogContentType.CatalogNode, 0);

            string theCode = _referenceConverter.GetCode(theSameRef);

            ContentReference catalogRoot = _referenceConverter.GetRootLink();

            List <string> codes = new List <string>
            {
                "Shirts_1",
                "Men_1"
            };

            IDictionary <string, ContentReference> theDict;

            theDict = _referenceConverter.GetContentLinks(codes);
        }
Ejemplo n.º 9
0
        protected virtual ContentReference GetContentLink(ContentQueryParameters parameters, ListingMode listingMode)
        {
            if (listingMode == ListingMode.WidgetListing)
            {
                return(ReferenceConverter.GetRootLink());
            }

            return(parameters.ReferenceId);
        }
        public void RegisterDefaultRoute(bool enableOutgoingSeoUri)
        {
            var commerceRootContent = _contentLoader.Get <CatalogContentBase>(_referenceConverter.GetRootLink());

            var pageLink = ContentReference.IsNullOrEmpty(SiteDefinition.Current.StartPage)
                ? SiteDefinition.Current.RootPage
                : SiteDefinition.Current.StartPage;

            RegisterRoute(pageLink, commerceRootContent, enableOutgoingSeoUri);
        }
        public void CheckReferenceConverter(ContentReference contentReference, AdminViewModel model)
        {
            RefInfo refInfo = new RefInfo();

            refInfo.Ref         = contentReference;
            refInfo.Code        = _referenceConverter.GetCode(contentReference);
            refInfo.DbId        = _referenceConverter.GetObjectId(contentReference);
            refInfo.CatalogType = _referenceConverter.GetContentType(contentReference).ToString();
            refInfo.RootRef     = _referenceConverter.GetRootLink();

            model.Refs.Add(refInfo);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a list of Parent categories for a product
        /// </summary>
        /// <param name="productContent">Product to get parent categories from</param>
        /// <param name="language">Current language name</param>
        /// <returns>List of Categories as CatalogContentBase</returns>
        public static List <CatalogContentBase> GetProductCategories(this CatalogContentBase productContent, string language)
        {
            var allRelations = relationRepository.GetRelationsBySource(productContent.ContentLink);
            var categories   = allRelations.OfType <NodeRelation>().ToList();
            List <CatalogContentBase> parentCategories = new List <CatalogContentBase>();

            if (categories.Any())
            {
                // Add all categories (nodes) that this product is part of
                foreach (var nodeRelation in categories)
                {
                    if (nodeRelation.Target != referenceConverter.GetRootLink())
                    {
                        CatalogContentBase parentCategory =
                            contentLoader.Get <CatalogContentBase>(nodeRelation.Target,
                                                                   new LanguageSelector(language));
                        if (parentCategory != null && parentCategory.ContentType != CatalogContentType.Catalog)
                        {
                            parentCategories.Add(parentCategory);
                        }
                    }
                }
            }

            var content = productContent;

            // Now walk the category tree until we hit the catalog node itself
            while (content.ParentLink != null && content.ParentLink != referenceConverter.GetRootLink())
            {
                CatalogContentBase parentCategory =
                    contentLoader.Get <CatalogContentBase>(content.ParentLink, new LanguageSelector(language));
                if (parentCategory.ContentType != CatalogContentType.Catalog)
                {
                    parentCategories.Add(parentCategory);
                }
                content = parentCategory;
            }
            return(parentCategories);
        }
Ejemplo n.º 13
0
        public override ActionResult Index(CategoryBlock currentBlock)
        {
            var categories = !ContentReference.IsNullOrEmpty(currentBlock.Catalog)
                ? _contentLoader.GetChildren <NodeContent>(currentBlock.Catalog)
                : _contentLoader.GetChildren <NodeContent>(_referenceConverter.GetRootLink());

            var model = new CategoryBlockViewModel(currentBlock)
            {
                Heading       = currentBlock.Heading,
                CategoryItems = categories.Select(ToViewModel).ToList()
            };

            return(PartialView("~/Features/Blocks/CategoryBlock/CategoryBlock.cshtml", model));
        }
        public override string Execute()
        {
            if (_contentLoader.TryGet(_referenceConverter.GetRootLink(), out IContent content))
            {
                var securableContent         = (IContentSecurable)content;
                var defaultAccessControlList = (IContentSecurityDescriptor)securableContent.GetContentSecurityDescriptor().CreateWritableClone();
                defaultAccessControlList.AddEntry(new AccessControlEntry(RoleNames.CommerceAdmins, AccessLevel.FullAccess, SecurityEntityType.Role));
                defaultAccessControlList.AddEntry(new AccessControlEntry(EveryoneRole.RoleName, AccessLevel.Read, SecurityEntityType.Role));

                _contentSecurityRepository.Save(content.ContentLink, defaultAccessControlList, SecuritySaveType.Replace);
                return("fix");
            }
            return("nothing to fix");
        }
Ejemplo n.º 15
0
        protected override IEnumerable <XElement> GetSitemapXmlElements()
        {
            var rootContentReference = _referenceConverter.GetRootLink();

            if (SitemapData.RootPageId != -1)
            {
                rootContentReference = new ContentReference(SitemapData.RootPageId)
                {
                    ProviderName = "CatalogContent"
                };
            }

            IList <ContentReference> descendants = ContentRepository.GetDescendents(rootContentReference).ToList();

            return(GenerateXmlElements(descendants));
        }
Ejemplo n.º 16
0
        public override ActionResult AddNewIndexWithMappings()
        {
            base.AddNewIndexWithMappings();
            Type indexType = typeof(IndexItem);

            foreach (KeyValuePair <string, string> lang in Languages)
            {
                var commerceIndexName = _settings.GetCommerceIndexName(lang.Key);
                CreateIndex(indexType, commerceIndexName);

                ContentReference commerceRoot = _referenceConverter.GetRootLink();
                UpdateMappingForTypes(commerceRoot, indexType, commerceIndexName, lang.Key);
            }

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 17
0
        public override string Execute()
        {
            var allMarkets = _marketService.GetAllMarkets();
            var added      = 0;

            foreach (var variant in _contentLoader.GetAllChildren <MovieVariant>(_referenceConverter.GetRootLink()))
            {
                var newPrices     = new List <PriceDetailValue>();
                var currentPrices = _priceDetailService.List(variant.ContentLink);
                //     var currentPrices2 = _priceService.GetCatalogEntryPrices(new CatalogKey(variant.Code));

                var markets = currentPrices?.Select(x => x.MarketId).Distinct().ToHashSet();

                foreach (var market in allMarkets)
                {
                    if (!markets.Contains(market.MarketId))
                    {
                        foreach (var currency in market.Currencies)
                        {
                            PriceDetailValue newPriceEntry = new PriceDetailValue();

                            newPriceEntry.CatalogKey      = new CatalogKey(variant.Code);
                            newPriceEntry.MinQuantity     = 0;
                            newPriceEntry.MarketId        = market.MarketId;
                            newPriceEntry.UnitPrice       = new Money(GetPrice(currency), currency);
                            newPriceEntry.ValidFrom       = DateTime.Now.AddDays(-1);
                            newPriceEntry.ValidUntil      = DateTime.Now.AddYears(20);
                            newPriceEntry.CustomerPricing = new CustomerPricing(0, "");
                            newPrices.Add(newPriceEntry);
                        }
                    }
                }

                if (newPrices.Any())
                {
                    _priceDetailService.Save(newPrices);
                    added += newPrices.Count;
                }
            }
            return($"Added {added} prices");
        }
Ejemplo n.º 18
0
        private CategoriesFilterViewModel GetCategoriesFilter(IContent currentContent, string query)
        {
            var bestBets         = new BestBetRepository().List().Where(i => i.PhraseCriterion.Phrase.CompareTo(query) == 0);
            var ownStyleBestBets = bestBets.Where(i => i.BestBetSelector is CommerceBestBetSelector && i.HasOwnStyle);
            var catalogId        = 0;
            var node             = currentContent as NodeContent;

            if (node != null)
            {
                catalogId = node.CatalogId;
            }
            var catalog = _contentLoader.GetChildren <CatalogContentBase>(_referenceConverter.GetRootLink())
                          .FirstOrDefault(x => catalogId == 0 || x.CatalogId == catalogId);

            if (catalog == null)
            {
                return(new CategoriesFilterViewModel());
            }

            var viewModel = new CategoriesFilterViewModel();
            var nodes     = _findClient.Search <NodeContent>()
                            .Filter(x => x.ParentLink.ID.Match(catalog.ContentLink.ID))
                            .FilterForVisitor()
                            .GetContentResult();

            foreach (var nodeContent in nodes)
            {
                var nodeFilter = new CategoryFilter
                {
                    DisplayName = nodeContent.DisplayName,
                    Url         = _urlResolver.GetUrl(nodeContent.ContentLink),
                    IsActive    = currentContent != null && currentContent.ContentLink == nodeContent.ContentLink,
                    IsBestBet   = ownStyleBestBets.Any(x => ((CommerceBestBetSelector)x.BestBetSelector).ContentLink.ID == nodeContent.ContentLink.ID)
                };
                viewModel.Categories.Add(nodeFilter);

                GetChildrenNode(currentContent, nodeContent, nodeFilter, ownStyleBestBets);
            }
            return(viewModel);
        }
Ejemplo n.º 19
0
        private List <CatalogContentBase> GetProductCategories(CatalogContentBase productContent, string language)
        {
            var allRelations = _linksRepository.GetRelationsBySource(productContent.ContentLink);
            var categories   = allRelations.OfType <NodeRelation>().ToList();
            List <CatalogContentBase> parentCategories = new List <CatalogContentBase>();

            try
            {
                if (categories.Any())
                {
                    foreach (var nodeRelation in categories)
                    {
                        if (nodeRelation.Target != _referenceConverter.GetRootLink())
                        {
                            CatalogContentBase parentCategory =
                                _contentLoader.Get <CatalogContentBase>(nodeRelation.Target,
                                                                        new LanguageSelector(language));
                            if (parentCategory != null)
                            {
                                parentCategories.Add(parentCategory);
                            }
                        }
                    }
                }
                else if (productContent.ParentLink != null && productContent.ParentLink != _referenceConverter.GetRootLink())
                {
                    CatalogContentBase parentCategory =
                        _contentLoader.Get <CatalogContentBase>(productContent.ParentLink,
                                                                new LanguageSelector(language));
                    parentCategories.Add(parentCategory);
                }
            }
            catch (Exception ex)
            {
                _log.Debug(string.Format("Failed to get categories from product {0}, Code: {1}.", productContent.Name, productContent.ContentLink), ex);
            }
            return(parentCategories);
        }
Ejemplo n.º 20
0
        public ContentReference GetOrCreateCatelog(string catalogName)
        {
            var root = _referenceConverter.GetRootLink();

            var catalogs = _contentRepository.GetChildren <CatalogContent>(root);
            var catalog  = catalogs?.Where(x => x.Name == catalogName).FirstOrDefault();

            if (catalog != null)
            {
                return(catalog.ContentLink);
            }

            var newCatalog = _contentRepository.GetDefault <CatalogContent>(root);

            newCatalog.Name            = catalogName;
            newCatalog.DefaultCurrency = "USD";
            newCatalog.DefaultLanguage = "en";
            newCatalog.WeightBase      = "kgs";
            newCatalog.LengthBase      = "cm";
            var contentReference = _contentRepository.Save(newCatalog, SaveAction.Publish, AccessLevel.NoAccess);

            return(contentReference);
        }
        public override string Execute()
        {
            var numberOfDocuments = 0;

            _elasticClient.Indices.Delete("movie");
            _elasticClient.Indices.Create("movie", x => x.Map <MovieDocument>(mm => mm.Properties(p => p.Keyword(t => t.Name(n => n.Genres)))));
            foreach (var contentData in _contentLoader.GetAllChildren <MovieProduct>(_referenceConverter.GetRootLink()))
            {
                if (contentData is ISearch movieProduct)
                {
                    var indexMove = new MovieDocument
                    {
                        Id    = contentData.TheMovieDbId,
                        Adult = movieProduct.Adult,
                        BelongsToCollection = movieProduct.BelongsToCollection,
                        Casts           = movieProduct.Casts?.ToList() ?? new List <Cast>(),
                        ContentLink     = movieProduct.ContentLink,
                        Crews           = movieProduct.Crews?.ToList() ?? new List <Crew>(),
                        Genres          = movieProduct.Genres ?? "",
                        OrginalLang     = movieProduct.OrginalLang ?? "",
                        OriginalTitle   = movieProduct.OriginalTitle ?? "",
                        Overview        = movieProduct.Overview ?? "",
                        Popularity      = movieProduct.Popularity,
                        Poster          = movieProduct.Poster,
                        ReleaseDate     = movieProduct.ReleaseDate,
                        SpokenLanguages = movieProduct.SpokenLanguages ?? "",
                        Title           = movieProduct.Title ?? "",
                        VoteAverage     = movieProduct.VoteAverage,
                        VoteCount       = movieProduct.VoteCount
                    };

                    var indexResponse = _elasticClient.IndexDocument(indexMove);
                    numberOfDocuments++;
                }
            }
            return($"Number of documents; {numberOfDocuments}");
        }
Ejemplo n.º 22
0
        private CategoriesFilterViewModel GetCategoriesFilter(IContent currentContent)
        {
            var catalogId = 0;
            var node      = currentContent as NodeContent;

            if (node != null)
            {
                catalogId = node.CatalogId;
            }
            var catalog = _contentLoader.GetChildren <CatalogContentBase>(_referenceConverter.GetRootLink())
                          .FirstOrDefault(x => catalogId == 0 || x.CatalogId == catalogId);

            if (catalog == null)
            {
                return(new CategoriesFilterViewModel());
            }

            var viewModel = new CategoriesFilterViewModel();

            foreach (var nodeContent in _contentLoader.GetChildren <NodeContent>(catalog.ContentLink))
            {
                var nodeFilter = new CategoryFilter
                {
                    DisplayName = nodeContent.DisplayName,
                    Url         = _urlResolver.GetUrl(nodeContent.ContentLink),
                    IsActive    = currentContent != null && currentContent.ContentLink == nodeContent.ContentLink
                };
                viewModel.Categories.Add(nodeFilter);

                var nodeChildren = _contentLoader.GetChildren <NodeContent>(nodeContent.ContentLink);
                foreach (var nodeChild in nodeChildren)
                {
                    var nodeChildFilter = new CategoryFilter
                    {
                        DisplayName = nodeChild.DisplayName,
                        Url         = _urlResolver.GetUrl(nodeChild.ContentLink),
                        IsActive    = currentContent != null && currentContent.ContentLink == nodeChild.ContentLink
                    };

                    nodeFilter.Children.Add(nodeChildFilter);
                    if (nodeChildFilter.IsActive)
                    {
                        nodeFilter.IsActive = true;
                    }

                    var nodeChildrenOfNodeChild = _contentLoader.GetChildren <NodeContent>(nodeChild.ContentLink);
                    foreach (var nodeChildOfChild in nodeChildrenOfNodeChild)
                    {
                        var nodeChildOfChildFilter = new CategoryFilter
                        {
                            DisplayName = nodeChildOfChild.DisplayName,
                            Url         = _urlResolver.GetUrl(nodeChildOfChild.ContentLink),
                            IsActive    = currentContent != null && currentContent.ContentLink == nodeChildOfChild.ContentLink
                        };

                        nodeChildFilter.Children.Add(nodeChildOfChildFilter);
                        if (nodeChildOfChildFilter.IsActive)
                        {
                            nodeFilter.IsActive = nodeChildFilter.IsActive = true;
                        }
                    }
                }
            }
            return(viewModel);
        }
Ejemplo n.º 23
0
        public void Dump()
        {
            var languageBranch = _languageBranchRepository.ListAll().First();

            var taxCategory = CatalogTaxManager.CreateTaxCategory("Tax category", true);

            CatalogTaxManager.SaveTaxCategory(taxCategory);

            var jurisdictionDto = new JurisdictionDto();
            var applicationId   = AppContext.Current.ApplicationId;

            jurisdictionDto.Jurisdiction.AddJurisdictionRow("Jurisdiction", null, languageBranch.LanguageID, (int)JurisdictionManager.JurisdictionType.Tax, null, null, null, null, null, null, applicationId, "ABC");
            jurisdictionDto.JurisdictionGroup.AddJurisdictionGroupRow(applicationId, "Group", (int)JurisdictionManager.JurisdictionType.Tax, "ABC");
            JurisdictionManager.SaveJurisdiction(jurisdictionDto);

            var taxDto = new TaxDto();

            taxDto.Tax.AddTaxRow((int)TaxType.SalesTax, "Tax", 1, applicationId);
            taxDto.TaxValue.AddTaxValueRow(20d, taxDto.Tax[0], "Tax category", jurisdictionDto.JurisdictionGroup[0].JurisdictionGroupId, DateTime.Now, Guid.Empty);
            TaxManager.SaveTax(taxDto);

            var currentMarket = _currentMarket.GetCurrentMarket();
            var market        = (MarketImpl)_marketService.GetMarket(currentMarket.MarketId);

            market.DefaultCurrency = Currency.EUR;
            market.DefaultLanguage = languageBranch.Culture;
            _marketService.UpdateMarket(market);

            var rootLink = _referenceConverter.GetRootLink();
            var catalog  = _contentRepository.GetDefault <CatalogContent>(rootLink, languageBranch.Culture);

            catalog.Name             = "Catalog";
            catalog.DefaultCurrency  = market.DefaultCurrency;
            catalog.CatalogLanguages = new ItemCollection <string> {
                languageBranch.LanguageID
            };
            catalog.DefaultLanguage = "en";
            catalog.WeightBase      = "kg";
            catalog.LengthBase      = "cm";
            var catalogRef = _contentRepository.Save(catalog, SaveAction.Publish, AccessLevel.NoAccess);

            var category = _contentRepository.GetDefault <NodeContent>(catalogRef);

            category.Name        = "Category";
            category.DisplayName = "Category";
            category.Code        = "category";
            var categoryRef = _contentRepository.Save(category, SaveAction.Publish, AccessLevel.NoAccess);

            var product = _contentRepository.GetDefault <ProductContent>(categoryRef);

            product.Name        = "Product";
            product.DisplayName = "Product";
            product.Code        = "product";
            var productRef = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var variant = _contentRepository.GetDefault <VariationContent>(productRef);

            variant.Name          = "Variant";
            variant.DisplayName   = "Variant";
            variant.Code          = Constants.VariationCode;
            variant.TaxCategoryId = taxCategory.TaxCategory.First().TaxCategoryId;
            variant.MinQuantity   = 1;
            variant.MaxQuantity   = 100;
            _contentRepository.Save(variant, SaveAction.Publish, AccessLevel.NoAccess);

            var price = new PriceValue
            {
                UnitPrice       = new Money(100, market.DefaultCurrency),
                CatalogKey      = new CatalogKey(applicationId, variant.Code),
                MarketId        = market.MarketId,
                ValidFrom       = DateTime.Today.AddYears(-1),
                ValidUntil      = DateTime.Today.AddYears(1),
                CustomerPricing = CustomerPricing.AllCustomers,
                MinQuantity     = 0
            };

            _priceService.SetCatalogEntryPrices(price.CatalogKey, new[] { price });

            var campaign = _contentRepository.GetDefault <SalesCampaign>(SalesCampaignFolder.CampaignRoot);

            campaign.Name       = "QuickSilver";
            campaign.Created    = DateTime.UtcNow.AddHours(-1);
            campaign.IsActive   = true;
            campaign.ValidFrom  = DateTime.Today;
            campaign.ValidUntil = DateTime.Today.AddYears(1);
            var campaignRef = _contentRepository.Save(campaign, SaveAction.Publish, AccessLevel.NoAccess);

            var promotion = _contentRepository.GetDefault <BuyFromCategoryGetItemDiscount>(campaignRef);

            promotion.IsActive            = true;
            promotion.Name                = "25 % off";
            promotion.Category            = categoryRef;
            promotion.Discount.UseAmounts = false;
            promotion.Discount.Percentage = 25m;
            _contentRepository.Save(promotion, SaveAction.Publish, AccessLevel.NoAccess);

            var paymentDto = new PaymentMethodDto();
            var created    = DateTime.UtcNow.AddHours(-1);

            paymentDto.PaymentMethod.AddPaymentMethodRow(Constants.PaymentMethodId, "Payment", "Payment", languageBranch.LanguageID, "Keyword", true, true, typeof(GenericPaymentGateway).AssemblyQualifiedName, typeof(OtherPayment).AssemblyQualifiedName, false, 1, created, created, applicationId);
            paymentDto.MarketPaymentMethods.AddMarketPaymentMethodsRow(market.MarketId.Value, paymentDto.PaymentMethod[0]);
            PaymentManager.SavePayment(paymentDto);
        }
Ejemplo n.º 24
0
        public override List <Feed> Build()
        {
            var generatedFeeds = new List <Feed>();
            var siteUrl        = _siteDefinitionRepository.List().FirstOrDefault()?.SiteUrl.ToString();

            var feed = new Feed
            {
                Updated = DateTime.UtcNow,
                Title   = "My products",
                Link    = siteUrl
            };

            var entries           = new List <Entry>();
            var catalogReferences = _contentLoader.GetDescendents(_referenceConverter.GetRootLink());

            foreach (var catalogReference in catalogReferences)
            {
                var catalogContent   = _contentLoader.Get <CatalogContentBase>(catalogReference);
                var variationContent = catalogContent as FashionVariant;
                if (variationContent != null)
                {
                    var product      = _contentLoader.Get <CatalogContentBase>(variationContent.GetParentProducts().FirstOrDefault()) as FashionProduct;
                    var variantCode  = variationContent.Code;
                    var defaultPrice = _pricingService.GetDefaultPrice(variantCode);

                    var entry = new Entry
                    {
                        Id                    = variantCode,
                        Title                 = variationContent.DisplayName,
                        Description           = product?.Description.ToHtmlString(),
                        Link                  = variationContent.GetUrl(),
                        Condition             = "new",
                        Availability          = "in stock",
                        Brand                 = product?.Brand,
                        MPN                   = string.Empty,
                        GTIN                  = "725272730706",
                        GoogleProductCategory = string.Empty,
                        Shipping              = new List <Shipping>
                        {
                            new Shipping
                            {
                                Price   = "1 USD",
                                Country = "US",
                                Service = "Standard"
                            }
                        }
                    };

                    var image = variationContent.GetDefaultAsset <IContentImage>();
                    if (!string.IsNullOrEmpty(image))
                    {
                        entry.ImageLink = Uri.TryCreate(new Uri(siteUrl), image, out var imageUri) ? imageUri.ToString() : image;
                    }

                    if (defaultPrice != null)
                    {
                        var discountPrice = _pricingService.GetDiscountPrice(variantCode);

                        entry.Price     = defaultPrice.UnitPrice.FormatPrice();
                        entry.SalePrice = discountPrice != null?discountPrice.UnitPrice.FormatPrice() : string.Empty;

                        entry.SalePriceEffectiveDate = $"{DateTime.UtcNow:yyyy-MM-ddThh:mm:ss}/{DateTime.UtcNow.AddDays(7):yyyy-MM-ddThh:mm:ss}";
                    }

                    entries.Add(entry);
                }
            }

            feed.Entries = entries;
            generatedFeeds.Add(feed);

            return(generatedFeeds);
        }
Ejemplo n.º 25
0
        public ActionResult ExportCatalog(ConfigurationViewModel model)
        {
            if (model.LocalSelectedCatalogName.IsNullOrEmpty())
            {
                model = GetConfigurationViewModel();
                ModelState.AddModelError(nameof(model.LocalSelectedCatalogName), "Catalog is required.");
                return(View("Index", model));
            }

            if (model.MediaFolder.IsNullOrEmpty())
            {
                model = GetConfigurationViewModel();
                ModelState.AddModelError(nameof(model.MediaFolder), "Media folder is required.");
                return(View("Index", model));
            }

            var catalog = ContentRepository.GetChildren <CatalogContent>(ReferenceConverter.GetRootLink())
                          .FirstOrDefault(_ => _.Name.Equals(model.LocalSelectedCatalogName));

            if (catalog == null)
            {
                model = GetConfigurationViewModel();
                ModelState.AddModelError(nameof(model.LocalSelectedCatalogName), "Catalog is required.");
                return(View("Index", model));
            }

            var mediaFolder = ContentRepository.Get <ContentFolder>(ContentReference.Parse(model.MediaFolder));

            if (mediaFolder == null)
            {
                model = GetConfigurationViewModel();
                ModelState.AddModelError(nameof(model.MediaFolder), "Media folder is required.");
                return(View("Index", model));
            }

            if (model.CatalogExportLocation.Equals("Remote", StringComparison.InvariantCultureIgnoreCase) && model.LocalCatalogName.IsNullOrEmpty())
            {
                model = GetConfigurationViewModel();
                ModelState.AddModelError(nameof(model.LocalCatalogName), "Blob Storage Catalog name is required.");
                return(View("Index", model));
            }

            using (var stream = new MemoryStream())
            {
                _catalogImportExport.Export(model.LocalSelectedCatalogName, stream, "");
                stream.Position = 0;

                var document = XDocument.Load(stream);
                document.Element("Catalogs").Element("MetaDataScheme").ReplaceWith(GetMetaDataScheme());
                document.Element("Catalogs").Element("Dictionaries").ReplaceWith(GetDictionaries());


                var newStream = new MemoryStream();
                var writer    = XmlWriter.Create(newStream);
                document.Save(writer);
                writer.Close();
                newStream.Position = 0;
                var media = InstallService.ExportEpiserverContent(mediaFolder.ContentLink, ContentExport.ExportPages);

                var zip = CreateArchiveStream(new Dictionary <string, Stream>()
                {
                    { "Catalog.xml", newStream },
                    { "ProductAssets.episerverdata", media }
                });

                var zipName = model.LocalCatalogName.IsNullOrEmpty() ? model.LocalSelectedCatalogName : model.LocalCatalogName;
                if (!zipName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
                {
                    zipName += ".zip";
                }

                if (model.CatalogExportLocation.Equals("Remote", StringComparison.InvariantCultureIgnoreCase))
                {
                    StorageService.Add($"Catalogs/{zipName}", zip, zip.Length);
                    return(RedirectToAction("Index"));
                }

                return(File(zip, "application/octet-stream", zipName));
            }
        }
Ejemplo n.º 26
0
        private ProductSearchResults GetSearchResults(IContent currentContent,
                                                      CommerceFilterOptionViewModel filterOptions,
                                                      string selectedfacets,
                                                      IEnumerable <Filter> filters = null,
                                                      int catalogId = 0)
        {
            //If contact belong organization, only find product that belong the categories that has owner is this organization
            var            contact             = PrincipalInfo.CurrentPrincipal.GetCustomerContact();
            var            organizationId      = contact?.ContactOrganization?.PrimaryKeyId ?? Guid.Empty;
            CatalogContent catalogOrganization = null;

            if (organizationId != Guid.Empty)
            {
                //get category that has owner id = organizationId
                catalogOrganization = _contentRepository
                                      .GetChildren <CatalogContent>(_referenceConverter.GetRootLink())
                                      .FirstOrDefault(x => !string.IsNullOrEmpty(x.Owner) && x.Owner.Equals(organizationId.ToString(), StringComparison.OrdinalIgnoreCase));
            }

            var pageSize = filterOptions.PageSize > 0 ? filterOptions.PageSize : DefaultPageSize;
            var market   = _currentMarket.GetCurrentMarket();

            var query = _findClient.Search <EntryContentBase>();

            query = ApplyTermFilter(query, filterOptions.Q, filterOptions.TrackData);
            query = query.Filter(x => x.Language.Name.Match(_languageResolver.GetPreferredCulture().Name));

            if (organizationId != Guid.Empty && catalogOrganization != null)
            {
                query = query.Filter(x => x.Outline().PrefixCaseInsensitive(catalogOrganization.Name));
            }

            var nodeContent = currentContent as NodeContent;

            if (nodeContent != null)
            {
                var outline = GetOutline(nodeContent.Code);
                query = query.FilterOutline(new[] { outline });
            }

            query = query.FilterMarket(market);
            var facetQuery = query;

            query = FilterSelected(query, filterOptions.FacetGroups);
            query = ApplyFilters(query, filters);
            query = OrderBy(query, filterOptions);
            //Exclude products from search
            //query = query.Filter(x => (x as ProductContent).ExcludeFromSearch.Match(false));

            if (catalogId != 0)
            {
                query = query.Filter(x => x.CatalogId.Match(catalogId));
            }

            query = query.ApplyBestBets()
                    .Skip((filterOptions.Page - 1) * pageSize)
                    .Take(pageSize)
                    .StaticallyCacheFor(TimeSpan.FromMinutes(1));

            var result = query.GetContentResult();

            return(new ProductSearchResults
            {
                ProductViewModels = CreateProductViewModels(result, currentContent, filterOptions.Q),
                FacetGroups = GetFacetResults(filterOptions.FacetGroups, facetQuery, selectedfacets),
                TotalCount = result.TotalMatching,
                DidYouMeans = string.IsNullOrEmpty(filterOptions.Q) ? null : _findClient.Statistics().GetDidYouMean(filterOptions.Q),
                Query = filterOptions.Q,
            });
        }
Ejemplo n.º 27
0
        private CatalogContent GetCatalogFromName(string catalog)
        {
            var catalogs = _contentRepository.GetChildren <CatalogContent>(_referenceConverter.GetRootLink());

            return(catalogs.FirstOrDefault(c => c.Name.Equals(catalog, StringComparison.InvariantCultureIgnoreCase)));
        }
 protected override List<ContentReference> GetContentReferences()
 {
     OnStatusChanged("Loading all references from database...");
     return _contentLoader.GetDescendents(_referenceConverter.GetRootLink()).ToList();
 }
 private CatalogContent GetRootCatalog()
 {
     return(_contentLoaderWrapper.GetChildren <CatalogContent>(_referenceConverter.GetRootLink())?.FirstOrDefault());
 }
Ejemplo n.º 30
0
 protected virtual List <CatalogContent> GetLocalCatalogs()
 {
     return(ContentRepository.GetChildren <CatalogContent>(ReferenceConverter.GetRootLink())
            .ToList());
 }