private void Populate(PromotionEntry entry, EntryContentBase catalogEntry, IPriceValue price)
        {
            entry.Quantity = 1;
            entry.Owner    = catalogEntry;
            entry["Id"]    = catalogEntry.Code;

            if (catalogEntry.Property != null)
            {
                foreach (var prop in catalogEntry.Property.Where(x => x.IsPropertyData))
                {
                    entry[prop.Name] = prop.Value;
                }
            }

            entry["ExtendedPrice"] = price.UnitPrice.Amount;
            var inventories = _inventoryService.QueryByEntry(new [] { price.CatalogKey.CatalogEntryCode }).ToList();

            if (!inventories.Any())
            {
                return;
            }

            entry["AllowBackordersAndPreorders"] = inventories.Any(i => i.CanBackorder(DateTime.UtcNow)) && inventories.Any(i => i.CanPreorder(DateTime.UtcNow));
            entry["InStockQuantity"]             = inventories.Sum(i => i.BackorderAvailableQuantity);
            entry["PreorderQuantity"]            = inventories.Sum(i => i.PreorderAvailableQuantity);
            entry["BackorderQuantity"]           = inventories.Sum(i => i.BackorderAvailableQuantity);
        }
        public ActionResult Rss(EntryContentBase currentContent)
        {
            if (Request.Url != null)
            {
                string pageBaseUrl = string.Format("{0}://{1}{2}", "https", Request.Url.Host,
                                                   Request.Url.IsDefaultPort ? string.Empty : ":" + Request.Url.Port);

                var imageUrl = string.Empty;
                if (currentContent.CommerceMediaCollection.Any())
                {
                    imageUrl = Url.ContentUrl(currentContent.CommerceMediaCollection.First().AssetLink);
                }

                var description = string.Empty;
                if (currentContent["Overview"] != null)
                {
                    description = ((XhtmlString)currentContent["Overview"]).ToHtmlString().StripHtml();
                }

                var feed = new SyndicationFeed(currentContent.Name, description, new Uri(Request.Url.AbsoluteUri), null)
                {
                    ImageUrl = new Uri(pageBaseUrl + imageUrl),
                };

                return(new FeedResult(new Rss20FeedFormatter(feed)));
            }
            return(null);
        }
示例#3
0
        public virtual ProductTileViewModel GetProductTileViewModel(EntryContentBase entry)
        {
            if (entry is PackageContent)
            {
                return(CreateProductViewModelForEntry((PackageContent)entry));
            }

            if (entry is ProductContent)
            {
                var product = (ProductContent)entry;
                var variant = _contentLoader.GetItems(product.GetVariants(), _preferredCulture).
                              Cast <VariationContent>().FirstOrDefault();

                return(CreateProductViewModelForVariant(product, variant));
            }

            if (entry is VariationContent)
            {
                var parentLink = entry.GetParentProducts(_relationRepository).SingleOrDefault();
                var product    = _contentLoader.Get <ProductContent>(parentLink);

                return(CreateProductViewModelForVariant(product, (VariationContent)entry));
            }

            throw new ArgumentException("BundleContent is not supported", "entry");
        }
示例#4
0
        public virtual ProductTileViewModel GetProductTileViewModel(EntryContentBase entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            if (entry is PackageContent)
            {
                return(CreateProductViewModelForEntry((PackageContent)entry));
            }

            if (entry is ProductContent)
            {
                var product = (ProductContent)entry;
                var variant = GetAvailableVariants(product.GetVariants()).FirstOrDefault();

                return(CreateProductViewModelForVariant(product, variant));
            }

            if (entry is VariationContent)
            {
                ProductContent product    = null;
                var            parentLink = entry.GetParentProducts(_relationRepository).SingleOrDefault();
                if (!ContentReference.IsNullOrEmpty(parentLink))
                {
                    product = _contentLoader.Get <ProductContent>(parentLink);
                }

                return(CreateProductViewModelForVariant(product, (VariationContent)entry));
            }

            throw new ArgumentException("BundleContent is not supported", nameof(entry));
        }
 private void MergePriorityProducts(ProductSearchBlock currentContent, List <ProductListViewModel> productListViewModels)
 {
     if (currentContent.PriorityProducts != null)
     {
         foreach (var contentAreaItem in currentContent.PriorityProducts.Items)
         {
             var item = contentAreaItem.GetContent();
             if (item != null)
             {
                 EntryContentBase entryContent = _contentLoader.Get <EntryContentBase>(item.ContentLink);
                 if (entryContent != null)
                 {
                     var viewModelInitializer = entryContent as IProductListViewModelInitializer;
                     if (viewModelInitializer != null)
                     {
                         // Remove priority products from list
                         productListViewModels.RemoveAll(
                             x => x.ContentLink.CompareToIgnoreWorkID(entryContent.ContentLink));
                         // Add to beginning
                         ProductListViewModel priorityProduct =
                             _productService.GetProductListViewModel(viewModelInitializer);
                         productListViewModels.Insert(0, priorityProduct);
                     }
                 }
             }
         }
     }
 }
示例#6
0
 /// <summary>
 /// Renders the Twitter header tags for <see cref="EntryContentBase" />
 /// </summary>
 /// <param name="htmlHelper">The HTML helper.</param>
 /// <param name="content">The content.</param>
 /// <param name="twitterUsername">The twitter username.</param>
 /// <returns>The <see cref="IHtmlString" />.</returns>
 /// <exception cref="T:System.Web.HttpException">The Web application is running under IIS 7 in Integrated mode.</exception>
 /// <exception cref="T:System.ArgumentException">The specified <see cref="UriPartial.Authority"/> is not valid.</exception>
 /// <exception cref="T:System.InvalidOperationException">The current <see cref="T:System.Uri" /> instance is not an absolute instance.</exception>
 /// <exception cref="T:System.MemberAccessException">The <see cref="T:System.Lazy`1" /> instance is initialized to use the default constructor of the type that is being lazily initialized, and permissions to access the constructor are missing.</exception>
 /// <exception cref="T:System.MissingMemberException">The <see cref="T:System.Lazy`1" /> instance is initialized to use the default constructor of the type that is being lazily initialized, and that type does not have a public, parameterless constructor.</exception>
 public static IHtmlString SummaryLargeImageTwitterCard(
     this HtmlHelper htmlHelper,
     EntryContentBase content,
     string twitterUsername)
 {
     return(htmlHelper.TwitterCard(content.ToSummaryLargeImageTwitterCard(twitterUsername: twitterUsername)));
 }
示例#7
0
        public ICollection <ProductAsset> BuildKaChingProductAssets(EntryContentBase entryContent)
        {
            if (entryContent.CommerceMediaCollection == null ||
                entryContent.CommerceMediaCollection.Count == 0)
            {
                return(null);
            }

            var assets = new List <ProductAsset>(entryContent.CommerceMediaCollection.Count);

            // Load all media assets (except the first) in one go, for the particular catalog entry.
            // Skip the first item because it will already be exported as the main image on the product object.
            IDictionary <ContentReference, MediaData> mediaByContentLink = _contentLoader
                                                                           .GetItems(
                entryContent.CommerceMediaCollection
                .Skip(1)
                .Distinct(CommerceMediaComparer.Default)
                .Select(x => x.AssetLink),
                CultureInfo.InvariantCulture)
                                                                           .OfType <MediaData>()
                                                                           .ToDictionary(x => x.ContentLink);

            foreach (CommerceMedia commerceMedia in entryContent.CommerceMediaCollection.Skip(1))
            {
                // Look up the referenced asset from the pre-loaded media assets.
                if (!mediaByContentLink.TryGetValue(commerceMedia.AssetLink, out MediaData mediaData))
                {
                    continue;
                }

                Uri absoluteUrl = GetAbsoluteUrl(mediaData.ContentLink);

                string mimeType;
                switch (mediaData.MimeType)
                {
                case "application/pdf":
                    mimeType = "document/pdf";
                    break;

                case "image/jpeg":
                case "image/png":
                    mimeType = mediaData.MimeType;
                    break;

                default:
                    continue;
                }

                var asset = new ProductAsset
                {
                    MimeType = mimeType,
                    Name     = new L10nString(mediaData.Name),
                    Url      = absoluteUrl?.ToString()
                };

                assets.Add(asset);
            }

            return(assets);
        }
示例#8
0
        /// <summary>
        /// Updates the <see cref="T:EPiServer.Commerce.Order.ILineItem"/> item placed price or raises <see cref="T:EPiServer.Commerce.Order.ValidationIssue"/> if their is no valid price.
        ///
        /// </summary>
        /// <param name="lineItem">The line item.</param><param name="customerContact"/><param name="market">The market.</param><param name="currency">The currency.</param><param name="onValidationError">A callback that is invoked if a validation issue is detected.</param>
        /// <returns>
        /// False if is there is no valid price
        /// </returns>
        public override bool UpdatePlacedPrice(ILineItem lineItem, CustomerContact customerContact, IMarket market, Currency currency, Action <ILineItem, ValidationIssue> onValidationError)
        {
            EntryContentBase entryContent = lineItem.GetEntryContent(_referenceConverter, _contentLoader);

            if (entryContent == null)
            {
                onValidationError(lineItem, ValidationIssue.RemovedDueToUnavailableItem);
                return(false);
            }
            if (lineItem.Properties[Constants.Quote.PreQuotePrice] != null && !string.IsNullOrEmpty(lineItem.Properties[Constants.Quote.PreQuotePrice].ToString()))
            {
                return(true);
            }

            Money?placedPrice = GetPlacedPrice(entryContent, lineItem.Quantity, customerContact, market, currency);

            if (placedPrice.HasValue)
            {
                if (new Money(currency.Round(lineItem.PlacedPrice), currency) == placedPrice.Value)
                {
                    return(true);
                }
                onValidationError(lineItem, ValidationIssue.PlacedPricedChanged);
                lineItem.PlacedPrice = placedPrice.Value.Amount;
                return(true);
            }
            onValidationError(lineItem, ValidationIssue.RemovedDueToInvalidPrice);
            return(false);
        }
示例#9
0
        private void Populate(PromotionEntry entry, EntryContentBase catalogEntry, IPriceValue price)
        {
            entry.Quantity = 1;
            entry.Owner    = catalogEntry;
            entry["Id"]    = catalogEntry.Code;

            if (catalogEntry.Property != null)
            {
                foreach (var prop in catalogEntry.Property.Where(x => x.IsPropertyData))
                {
                    entry[prop.Name] = prop.Value;
                }
            }

            entry["ExtendedPrice"] = price.UnitPrice.Amount;
            var inventories = _inventoryService.List(price.CatalogKey, _warehouseRepository.List()).ToList();

            if (!inventories.Any())
            {
                return;
            }

            entry["AllowBackordersAndPreorders"] = inventories.Any(i => i.AllowBackorder) && inventories.Any(i => i.AllowPreorder);
            entry["InStockQuantity"]             = inventories.Sum(i => i.InStockQuantity - i.ReservedQuantity);
            entry["PreorderQuantity"]            = inventories.Sum(i => i.PreorderQuantity);
            entry["BackorderQuantity"]           = inventories.Sum(i => i.BackorderQuantity);
            entry["InventoryStatus"]             = inventories.First().InventoryStatus;
        }
示例#10
0
        private VariationContent GetVariationContent(EntryContentBase content)
        {
            var variationContent = content as VariationContent;

            if (variationContent != null)
            {
                return(variationContent);
            }

            var variantContainer = content as IVariantContainer;

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

            var relation = variantContainer.GetVariantRelations().FirstOrDefault();

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

            return(ContentLoader.Get <IContent>(relation.Target, _languageSelectorFactory.Create(content.Language.Name)) as VariationContent);
        }
示例#11
0
        private string GetAssociationMetaData(EntryContentBase currentContent)
        {
            // not good, find a better way than do this twice
            IEnumerable <EPiServer.Commerce.Catalog.Linking.Association> assoc = currentContent.GetAssociations();
            StringBuilder strB = new StringBuilder();

            if (assoc.Count() >= 1)
            {
                // Fix code and formatting, but it works
                EPiServer.Commerce.Catalog.Linking.Association a = assoc.FirstOrDefault(); // get the only one .. so far for test
                strB.Append("GroupName: " + a.Group.Name);
                strB.Append(" - ");
                strB.Append("GroupDescription: " + a.Group.Description); // doesn't show - investigate
                strB.Append(" - ");
                strB.Append("GroupSort: " + a.Group.SortOrder);
                strB.Append(" - ");
                strB.Append("TypeId: " + a.Type.Id); // where the filter could be applied
                strB.Append(" - ");
                strB.Append("TypeDescr: " + a.Type.Description);
                // there is more to get out
                ContentReference theRef = a.Target;
                strB.Append("...in TrousersController");
            }
            else
            {
                strB.Append("Nothing");
            }

            return(strB.ToString());
        }
        /// <summary>
        /// Gets all children for an entry, whether it's product-variation, bundle-variation/product, package-variation/product relation.
        /// </summary>
        /// <param name="entry">The catalog entry to retrieve children for</param>
        /// <returns></returns>
        public IEnumerable <EntryContentBase> GetChildren(EntryContentBase entry)
        {
            IEnumerable <EntryRelation>    relations  = _relationRepository.GetChildren <EntryRelation>(entry.ContentLink);
            IEnumerable <EntryContentBase> variations = relations.Select(x => _contentLoader.Get <EntryContentBase>(x.Child));

            return(variations.Where(x => x != null));
        }
        public IPriceValue GetDiscountPrice(IPriceValue price, EntryContentBase entry, Currency currency, PromotionHelperFacade promotionHelper)
        {
            var promotionEntry = CreatePromotionEntry(entry, price);
            var filter         = new PromotionFilter
            {
                IgnoreConditions = false,
                IgnorePolicy     = false,
                IgnoreSegments   = false,
                IncludeCoupons   = false
            };

            var sourceSet = new PromotionEntriesSet();

            sourceSet.Entries.Add(promotionEntry);
            var promotionContext = promotionHelper.Evaluate(filter, sourceSet, sourceSet, false);

            if (promotionContext.PromotionResult.PromotionRecords.Count > 0)
            {
                return(new PriceValue
                {
                    CatalogKey = price.CatalogKey,
                    CustomerPricing = CustomerPricing.AllCustomers,
                    MarketId = price.MarketId,
                    MinQuantity = 1,
                    UnitPrice = new Money(price.UnitPrice.Amount - GetDiscountPrice(promotionContext), currency),
                    ValidFrom = DateTime.UtcNow,
                    ValidUntil = null
                });
            }
            return(price);
        }
示例#14
0
        protected string GetMediaUrl(CatalogContentBase content) // ok for making lab of it
        {
            IList <CommerceMedia> mediaList = new List <CommerceMedia>();

            // check the model type and fill up with te right stuff
            if (content.ContentType == CatalogContentType.CatalogNode)
            {
                NodeContent node = content as NodeContent;
                mediaList = node.CommerceMediaCollection;
            }

            if (content.ContentType == CatalogContentType.CatalogEntry)
            {
                EntryContentBase entry = content as EntryContentBase;
                mediaList = entry.CommerceMediaCollection; //
            }

            // just get the first
            CommerceMedia media = mediaList.FirstOrDefault(); // ...do it easy in this lab

            if (media == null)
            {
                return(String.Empty);
            }

            // load the image url, if it exist... and return it
            var contentLinkMap = linkMapper.Find(new Guid(media.AssetKey));

            if (contentLinkMap == null)
            {
                return(String.Empty);
            }

            return(contentLinkMap.MappedUrl.ToString());
        }
        public static IEnumerable <Price> Prices(this EntryContentBase entryContentBase)
        {
            //var market = MarketService.Value.GetAllMarkets().FirstOrDefault(x => x.DefaultLanguage.Name.Equals(entryContentBase.Language.Name));
            var market = CurrentMarket.Value.GetCurrentMarket();

            if (market == null)
            {
                return(Enumerable.Empty <Price>());
            }

            var priceFilter = new PriceFilter
            {
                CustomerPricing = new[] { CustomerPricing.AllCustomers }
            };

            if (entryContentBase is ProductContent productContent)
            {
                var variationLinks = productContent.GetVariants();
                return(variationLinks.GetPrices(market.MarketId, priceFilter));
            }

            if (entryContentBase is PackageContent packageContent)
            {
                return(packageContent.ContentLink.GetPrices(market.MarketId, priceFilter));
            }

            return(entryContentBase is VariationContent variationContent
                ? variationContent.ContentLink.GetPrices(market.MarketId, priceFilter)
                : Enumerable.Empty <Price>());
        }
示例#16
0
        public static decimal CalculateRelationsWeight <T>(this EntryContentBase entry) where T : EntryRelation
        {
            if (entry == null)
            {
                return(0);
            }

            var relations     = _injectedRelationRepository.Service.GetChildren <T>(entry.ContentLink);
            var contentLoader = _injectedContentLoader.Service;

            decimal weight = 0;

            foreach (var entryRelation in relations)
            {
                if (contentLoader.TryGet(entryRelation.Child, out EntryContentBase relationEntry))
                {
                    var stockPlacementEntry = relationEntry as IStockPlacement;

                    if (stockPlacementEntry != null)
                    {
                        weight += (decimal)stockPlacementEntry.Weight * entryRelation.Quantity.GetValueOrDefault(1);
                    }
                }
            }

            return(weight);
        }
示例#17
0
        /// <summary>
        /// Gets the URL.
        /// </summary>
        /// <param name="entry">The entry.</param>
        /// <param name="relationRepository">The relation repository.</param>
        /// <param name="urlResolver">The URL resolver.</param>
        /// <param name="language">The language.</param>
        /// <returns>The Url for the <param name="entry"></param>.</returns>
        /// <exception cref="T:System.Web.HttpException">The Web application is running under IIS 7 in Integrated mode.</exception>
        /// <exception cref="T:System.InvalidOperationException">The current <see cref="T:System.Uri" /> instance is not an absolute instance.</exception>
        /// <exception cref="T:System.ArgumentException">The specified <see cref="UriPartial.Authority"/> is not valid.</exception>
        /// <exception cref="T:System.ArgumentNullException">Parent products are <see langword="null" />.</exception>
        /// <exception cref="T:System.NotSupportedException">The query collection is read-only.</exception>
        internal static string GetUrl(
            this EntryContentBase entry,
            IRelationRepository relationRepository,
            UrlResolver urlResolver,
            string language)
        {
            ContentReference parentLink = entry.GetParentProducts(relationRepository: relationRepository).FirstOrDefault();

            ContentReference productLink = entry is VariationContent
                                               ? entry.GetParentProducts(relationRepository : relationRepository)
                                           .FirstOrDefault() ?? entry.ContentLink
                                               : entry.ContentLink;

            UrlBuilder urlBuilder = string.IsNullOrEmpty(value: language)
                                        ? new UrlBuilder(urlResolver.GetUrl(contentLink: productLink))
                                        : new UrlBuilder(
                urlResolver.GetUrl(contentLink: productLink, language: language));

            if (parentLink != null && entry.Code != null)
            {
                urlBuilder.QueryCollection.Add("variationCode", value: entry.Code);
            }

            Global.UrlRewriteProvider.ConvertToExternal(url: urlBuilder, null, toEncoding: Encoding.UTF8);

            string externalUrl = HttpContext.Current == null
                                     ? UriSupport.AbsoluteUrlBySettings(urlBuilder.ToString())
                                     : $"{HttpContext.Current.Request.Url.GetLeftPart(part: UriPartial.Authority)}{urlBuilder}";

            return(externalUrl);
        }
示例#18
0
        public virtual ProductTileViewModel GetProductTileViewModel(EntryContentBase entry)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            if (entry is PackageContent)
            {
                return(CreateProductViewModelForEntry((PackageContent)entry));
            }

            if (entry is ProductContent)
            {
                var product = (ProductContent)entry;
                var variant = _catalogContentService.GetVariants <FashionVariant>(product).FirstOrDefault();

                return(CreateProductViewModelForVariant(product, variant));
            }

            if (entry is VariationContent)
            {
                var product = _catalogContentService.GetParentProduct <ProductContent>(entry);
                return(CreateProductViewModelForVariant(product, (VariationContent)entry));
            }

            throw new ArgumentException("BundleContent is not supported", nameof(entry));
        }
示例#19
0
        public IRecommendations GetRecommendedProducts(EntryContentBase catalogEntry, string userId, int maxCount)
        {
            if (catalogEntry == null)
            {
                throw new ArgumentNullException("catalogEntry");
            }

            var    client       = SearchClient.Instance;
            string language     = catalogEntry.Language.Name;
            string mainCategory = catalogEntry.GetMainCategory(language);
            string category     = catalogEntry.GetCategoryName(language);

            var result = client.Search <FindProduct>()
                         .Filter(x => x.CategoryName.Match(category))
                         .Filter(x => x.MainCategoryName.Match(mainCategory))
                         .Filter(x => !x.Code.Match(catalogEntry.Code))
                         .Filter(x => x.Language.Match(language))
                         .StaticallyCacheFor(TimeSpan.FromMinutes(1))
                         .Take(maxCount)
                         .GetResult();

            List <ContentReference> links = new List <ContentReference>();

            foreach (FindProduct product in result)
            {
                links.Add(_referenceConverter.GetContentLink(product.Id, CatalogContentType.CatalogEntry, 0));
            }

            IRecommendations recommendations = new Recommendations("RecForProduct", _contentRepository.GetItems(links, catalogEntry.Language));

            return(recommendations);
        }
示例#20
0
 /// <summary>
 /// Gets the URL.
 /// </summary>
 /// <param name="entry">The entry.</param>
 /// <returns>The Url for the <param name="entry"></param>.</returns>
 /// <exception cref="T:System.Web.HttpException">The Web application is running under IIS 7 in Integrated mode.</exception>
 /// <exception cref="T:System.InvalidOperationException">The current <see cref="T:System.Uri" /> instance is not an absolute instance.</exception>
 /// <exception cref="T:System.ArgumentException">The specified <see cref="UriPartial.Authority"/> is not valid.</exception>
 /// <exception cref="T:System.NotSupportedException">The query collection is read-only.</exception>
 /// <exception cref="T:System.ArgumentNullException">Parent products are <see langword="null" />.</exception>
 /// <exception cref="T:System.MemberAccessException">The <see cref="T:System.Lazy`1" /> instance is initialized to use the default constructor of the type that is being lazily initialized, and permissions to access the constructor are missing.</exception>
 /// <exception cref="T:System.MissingMemberException">The <see cref="T:System.Lazy`1" /> instance is initialized to use the default constructor of the type that is being lazily initialized, and that type does not have a public, parameterless constructor.</exception>
 internal static string GetUrl(this EntryContentBase entry)
 {
     return(GetUrl(
                entry: entry,
                relationRepository: RelationRepository.Value,
                urlResolver: UrlResolver.Value));
 }
        public static ProductTileViewModel GetProductTileViewModel(this EntryContentBase entry, IMarket market, Currency currency)
        {
            var placedPrice = entry.Prices()
                              .Where(id => id.MarketId == market.MarketId)
                              .OrderBy(sort => sort.UnitPrice.Amount)
                              .FirstOrDefault(x => x.UnitPrice.Currency == currency);
            var entryRecommendations = entry as IProductRecommendations;
            var product   = entry;
            var entryUrl  = "";
            var firstCode = placedPrice != null && placedPrice.EntryContent is VariationContent ? (placedPrice.EntryContent as VariationContent).Code : "";
            var type      = typeof(GenericProduct);

            if (entry is GenericProduct)
            {
                entryUrl = UrlResolver.Value.GetUrl(product.ContentLink);
            }

            if (entry is GenericBundle)
            {
                type      = typeof(GenericBundle);
                firstCode = product.Code;
                entryUrl  = UrlResolver.Value.GetUrl(product.ContentLink);
            }

            if (entry is GenericPackage)
            {
                type      = typeof(GenericPackage);
                firstCode = product.Code;
                entryUrl  = UrlResolver.Value.GetUrl(product.ContentLink);
            }

            if (entry is GenericVariant)
            {
                var variantEntry = entry as GenericVariant;
                type     = typeof(GenericVariant);
                product  = ContentLoader.Value.Get <EntryContentBase>(entry.GetParentProducts().FirstOrDefault()) as GenericProduct;
                entryUrl = UrlResolver.Value.GetUrl(product.ContentLink) + "?variationCode=" + variantEntry.Code;
            }

            return(new ProductTileViewModel
            {
                ProductId = product.ContentLink.ID,
                Brand = entry.Property.Keys.Contains("Brand") ? entry.Property["Brand"]?.Value?.ToString() ?? "" : "",
                Code = product.Code,
                DisplayName = entry.DisplayName,
                Description = entry.Property.Keys.Contains("Description") ? entry.Property["Description"]?.Value != null ? ((XhtmlString)entry.Property["Description"].Value).ToHtmlString() : "" : "",
                LongDescription = ShortenLongDescription(entry.Property.Keys.Contains("LongDescription") ? entry.Property["LongDescription"]?.Value != null ? ((XhtmlString)entry.Property["LongDescription"].Value).ToHtmlString() : "" : ""),
                PlacedPrice = placedPrice?.UnitPrice ?? new Money(0, currency),
                DiscountedPrice = placedPrice == null ? new Money(0, currency) : PromotionService.Value.GetDiscountPrice(placedPrice.EntryContent.GetCatalogKey(), market.MarketId, currency).UnitPrice,
                FirstVariationCode = firstCode,
                ImageUrl = AssetUrlResolver.Value.GetAssetUrl <IContentImage>(entry),
                Url = entryUrl,
                IsAvailable = entry.Prices().Where(price => price.MarketId == market.MarketId)
                              .Any(x => x.UnitPrice.Currency == currency),
                OnSale = entry.Property.Keys.Contains("OnSale") && ((bool?)entry.Property["OnSale"]?.Value ?? false),
                NewArrival = entry.Property.Keys.Contains("NewArrival") && ((bool?)entry.Property["NewArrival"]?.Value ?? false),
                ShowRecommendations = entryRecommendations != null ? entryRecommendations.ShowRecommendations : true,
                EntryType = type
            });
        }
        public IPriceValue GetDiscountPrice(IPriceValue price, EntryContentBase entry, Currency currency, PromotionHelperFacade promotionHelper)
        {
            var promotionEntry = CreatePromotionEntry(entry, price);
            var filter = new PromotionFilter
            {
                IgnoreConditions = false,
                IgnorePolicy = false,
                IgnoreSegments = false,
                IncludeCoupons = false
            };

            var sourceSet = new PromotionEntriesSet();
            sourceSet.Entries.Add(promotionEntry);
            var promotionContext = promotionHelper.Evaluate(filter, sourceSet, sourceSet, false);

            if (promotionContext.PromotionResult.PromotionRecords.Count > 0)
            {
                return new PriceValue
                {
                    CatalogKey = price.CatalogKey,
                    CustomerPricing = CustomerPricing.AllCustomers,
                    MarketId = price.MarketId,
                    MinQuantity = 1,
                    UnitPrice = new Money(price.UnitPrice.Amount - GetDiscountPrice(promotionContext), currency),
                    ValidFrom = DateTime.UtcNow,
                    ValidUntil = null
                };
            }
            return price;
        }
示例#23
0
        public override ActionResult Index(RelatedStuffBlockType currentBlock)
        {
            ContentReference cRef = currentBlock.TheRef; // gets null, even though it´s set in the model class

            //GetInfo(currentBlock);

            GetContentName();
            GetParentContentName();

            GetAssociations();

            CheckOtherStuff();

            ContentReference p = OtherClass.proppen; // if we can make it happen - gets the CastleProxy

            //var x =  p.;

            EntryContentBase daStuff = loader.Service.Get <EntryContentBase>(p); // gets the CastleProxy
            string           s       = daStuff.Code;

            RelatedStuffBlockViewModel model = new RelatedStuffBlockViewModel()
            {
                theContent          = GetContentName(),
                theParentContent    = GetParentContentName(),
                Name                = currentBlock.Name,
                RelatingTo          = currentBlock.RelatingTo, // set a dummy string, try to override in the model
                associations        = GetAssociatedReferences(),
                Type                = this.Type,
                Group               = this.Group,
                theEntryContentBase = daStuff
            };


            return(PartialView(model));
        }
        public static string GetImage(this EntryContentBase productContent, string preset = null, string groupName = null)
        {
            var urlResolver = ServiceLocator.Current.GetInstance <UrlResolver>();

            CommerceMedia commerceMedia;

            if (groupName == null)
            {
                commerceMedia =
                    productContent.CommerceMediaCollection.OrderBy(m => m.SortOrder)
                    .FirstOrDefault(z => z.GroupName == null || z.GroupName.ToLower() == "default");
            }
            else
            {
                commerceMedia =
                    productContent.CommerceMediaCollection.OrderBy(m => m.SortOrder)
                    .FirstOrDefault(z => z.GroupName.ToLower() == groupName);
            }

            if (commerceMedia != null)
            {
                var    contentReference = commerceMedia.AssetLink;
                string defaultImage     = urlResolver.GetUrl(contentReference, null,
                                                             new VirtualPathArguments()
                {
                    ContextMode = ContextMode.Default
                });
                if (preset != null)
                {
                    defaultImage = defaultImage + "?preset=" + preset;
                }
                return(defaultImage);
            }
            return(null);
        }
        public static string AssetSwatchUrl(this EntryContentBase entry)
        {
            if (entry != null)
            {
                var permanentLinkMapper = ServiceLocator.Current.GetInstance <IPermanentLinkMapper>();
                var urlResolver         = ServiceLocator.Current.GetInstance <UrlResolver>();

                if (entry.CommerceMediaCollection != null)
                {
                    foreach (var commerceMedia in entry.CommerceMediaCollection)
                    {
                        if (commerceMedia.GroupName != null && commerceMedia.GroupName.ToLower() == "swatch")
                        {
                            var contentLink = commerceMedia.AssetContentLink(permanentLinkMapper);
                            return(urlResolver.GetUrl(contentLink));
                        }
                    }

                    // Use first
                    string defaultImage = entry.GetDefaultImage("swatch");
                    return(defaultImage);
                }
            }
            return(null);
        }
示例#26
0
        private CartActionResult AddToCart(string name, LineItem lineItem)
        {
            string code = lineItem.Code;

            if (lineItem.Quantity < 1)
            {
                lineItem.Quantity = 1;
            }

            string messages = string.Empty;
            ICart  cart     = LoadOrCreateCart(DefaultCartName);
            var    result   = AddToCart(cart, code, lineItem.Quantity, out messages);

            // Populate with additional fields before saving
            ILineItem addedLineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);

            if (addedLineItem != null)
            {
                // Need content for easier access to more information
                ContentReference itemLink     = _referenceConverter.GetContentLink(code);
                EntryContentBase entryContent = _contentLoader.Get <EntryContentBase>(itemLink);

                AddPropertiesToLineItem(addedLineItem, lineItem, entryContent);

                AddCustomProperties(lineItem, addedLineItem);
            }

            _orderRepository.Save(cart);

            // TODO: Always returns success, if we get warnings, we need to show them
            return(new CartActionResult {
                Success = true, Message = messages
            });
        }
        protected virtual string GetProductViewTrackingScript(IContent content, Guid userId)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }
            EntryContentBase entry = content as EntryContentBase;

            if (entry is VariationContent)
            {
                // Get parent product
                var parentProducts = GetParentProductsForVariation(entry as VariationContent);
                var productContent = parentProducts.FirstOrDefault();
                // This implementation will use the first one
                if (productContent != null)
                {
                    entry = productContent;
                }
            }

            string        productCode      = entry.Code;
            List <string> parentCategories = entry.GetParentCategoryCodes(entry.Language.Name);

            return(GenerateClickUrl(userId, productCode, parentCategories));
        }
示例#28
0
        public decimal GetTheRightPrice(EntryContentBase CurrentContent)
        {
            IEnumerable <IPriceValue> priceValues;

            // need to check if anonymous or not ... so the EffectiveGroup does not bother
            // Anonymous... could use the DefaultPrice, but may miss the tiered price if set at Anonymous
            if (CustomerContext.Current.CurrentContact == null)
            {
                PriceFilter filter = new PriceFilter()
                {
                    Quantity        = 1M,
                    Currencies      = new Currency[] { _marketService.GetCurrentMarket().Currencies.FirstOrDefault() }, // only have one at the moment...
                    CustomerPricing = new CustomerPricing[]
                    {
                        new CustomerPricing(CustomerPricing.PriceType.AllCustomers, null),
                    },
                    ReturnCustomerPricing = false //
                };

                // The rest needed, CatKey, Market, TimeStamp
                CatalogKey catalogKey = new CatalogKey(CurrentContent.Code); // 3 overloads

                priceValues = _priceService.GetPrices(
                    currentMarket.Service.GetCurrentMarket().MarketId.Value, FrameworkContext.Current.CurrentDateTime, catalogKey, filter);
            }
            else
            {
                // Logged on
                // no custom PriceTypes... yet
                PriceFilter filter = new PriceFilter()
                {
                    Quantity        = 1M,
                    Currencies      = new Currency[] { _marketService.GetCurrentMarket().Currencies.FirstOrDefault() }, // only have one at the moment...
                    CustomerPricing = new CustomerPricing[]
                    {
                        new CustomerPricing(CustomerPricing.PriceType.AllCustomers, null),
                        new CustomerPricing(CustomerPricing.PriceType.PriceGroup, CustomerContext.Current.CurrentContact.EffectiveCustomerGroup), // or several...
                        new CustomerPricing(CustomerPricing.PriceType.UserName, CustomerContext.Current.CurrentContact.FirstName)
                    },
                    ReturnCustomerPricing = false //
                                                  // ... if true; gets all that applies
                };

                // The rest needed, CatKey, Market, TimeStamp
                CatalogKey catalogKey = new CatalogKey(new Guid(CurrentContent.ApplicationId), CurrentContent.Code); // 3 overloads

                priceValues = _priceService.GetPrices(
                    currentMarket.Service.GetCurrentMarket().MarketId.Value, FrameworkContext.Current.CurrentDateTime, catalogKey, filter);
            }

            if (priceValues.Count() > 0)
            {
                return(priceValues.ToList().OrderBy(x => x.UnitPrice.Amount).FirstOrDefault().UnitPrice.Amount);
            }
            else
            {
                return(0); // should not actually, could use default price... it's a demo
            }
        }
示例#29
0
 public static string AssetSwatch(this HtmlHelper html, EntryContentBase entry)
 {
     if (entry != null)
     {
         return(entry.AssetSwatchUrl());
     }
     return("");
 }
 public static string AssetSwatch(this HtmlHelper html, EntryContentBase entry)
 {
     if (entry != null)
     {
         return entry.AssetSwatchUrl();
     }
     return "";
 }
        public static IEnumerable <string> Outline(this EntryContentBase productContent)
        {
            var nodes = ContentLoader.Value
                        .GetItems(productContent.GetNodeRelations().Select(x => x.Parent), productContent.Language)
                        .OfType <NodeContent>();

            return(nodes.Select(x => GetOutlineForNode(x.Code)));
        }
 public static double GetAverageRating(this EntryContentBase entryContentBase)
 {
     if (entryContentBase.Property["AverageRating"] != null && entryContentBase.Property["AverageRating"].Value != null)
     {
         return((double)entryContentBase.Property["AverageRating"].Value);
     }
     return(0.0);
 }
        private string GetImageUrl(EntryContentBase product, UrlResolver urlResolver)
        {
            var mediaReferences = product.AssetImageUrls();

            if (mediaReferences != null && mediaReferences.Any())
            {
                var media = mediaReferences.FirstOrDefault();
                var mediaUrl = urlResolver.GetUrl(media);
                return mediaUrl + "?preset=imagenarrow";
            }
            return string.Empty;
        }
        public static MvcHtmlString AssetImage(this HtmlHelper html, EntryContentBase entry, IPermanentLinkMapper permanentLinkMapper)
        {
            var commerceMedia = entry.GetCommerceMedia();
            if (commerceMedia == null)
            {
                return MvcHtmlString.Empty;
            }

            var contentLink = commerceMedia.AssetContentLink(permanentLinkMapper);

            return html.Partial(UIHint.Image, contentLink);
        }
 private PromotionEntry CreatePromotionEntry(EntryContentBase entry, IPriceValue price)
 {
     var catalogNodes = string.Empty;
     var catalogs = string.Empty;
     foreach (var node in entry.GetNodeRelations(_linksRepository).Select(x => _contentLoader.Get<NodeContent>(x.Target)))
     {
         var entryCatalogName = _catalogSystem.GetCatalogDto(node.CatalogId).Catalog[0].Name;
         catalogs = string.IsNullOrEmpty(catalogs) ? entryCatalogName : catalogs + ";" + entryCatalogName;
         catalogNodes = string.IsNullOrEmpty(catalogNodes) ? node.Code : catalogNodes + ";" + node.Code;
     }
     var promotionEntry = new PromotionEntry(catalogs, catalogNodes, entry.Code, price.UnitPrice.Amount);
     Populate(promotionEntry, entry, price);
     return promotionEntry;
 }
        public static List<string> AssetImageUrls(this HtmlHelper html, EntryContentBase entry)
        {
            var output = new List<string>();
            var urlResolver = ServiceLocator.Current.GetInstance<UrlResolver>();

            if (entry != null)
            {
                foreach (var imageLink in html.AssetImageReferences(entry))
                {
                    output.Add(urlResolver.GetUrl(imageLink));
                }
            }

            return output;
        }
 public FindProduct(EntryContentBase entryContentBase, string language)
 {
     IndexId = entryContentBase.ContentLink.ID + "_" + language;
     Id = entryContentBase.ContentLink.ID;
     Code = entryContentBase.Code;
     Name = entryContentBase.Name;
     DisplayName = entryContentBase.DisplayName;
     Language = language;
     Description = Description ?? null;
     ParentCategoryId = entryContentBase.GetProductCategoryIds(language);
     ParentCategoryName = entryContentBase.GetParentCategoryNames(language);
     MainCategoryName = entryContentBase.GetMainCategory(language);
     CategoryName = entryContentBase.GetCategoryName(language);
     ProductUrl = urlResolverInjected.Service.GetUrl(entryContentBase.ContentLink, language);
     DefaultImageUrl = entryContentBase.GetDefaultImage();
 }
示例#38
0
 public IPriceValue GetDiscountPrice(IPriceValue price, EntryContentBase entry, Currency currency, IMarket market)
 {
     var discountedPrice = _promotionEngine.GetDiscountPrices(new[] { entry.ContentLink }, market, currency, _referenceConverter, _lineItemCalculator);
     if (discountedPrice.Any())
     {
         var highestDiscount = discountedPrice.SelectMany(x => x.DiscountPrices).OrderBy(x => x.Price).FirstOrDefault().Price;
         return new PriceValue
         {
             CatalogKey = price.CatalogKey,
             CustomerPricing = CustomerPricing.AllCustomers,
             MarketId = price.MarketId,
             MinQuantity = 1,
             UnitPrice = highestDiscount,
             ValidFrom = DateTime.UtcNow,
             ValidUntil = null
         };
     }
     return price;
 }
示例#39
0
 public FindProduct(EntryContentBase entryContentBase, string language)
 {
     IndexId = entryContentBase.ContentLink.ID + "_" + language;
     Id = entryContentBase.ContentLink.ID;
     Code = entryContentBase.Code;
     Name = entryContentBase.Name;
     DisplayName = entryContentBase.DisplayName;
     Language = language;
     Description = Description ?? null;
     Overview = Overview ?? null;
     ParentCategoryId = entryContentBase.GetProductCategoryIds(language);
     ParentCategoryName = entryContentBase.GetParentCategoryNames(language);
     MainCategoryName = entryContentBase.GetMainCategory(language);
     CategoryName = entryContentBase.GetCategoryName(language);
     ProductUrl = _urlResolver.Service.GetUrl(entryContentBase.ContentLink, language);
     DefaultImageUrl = entryContentBase.GetDefaultImage();
     AverageRating = entryContentBase.GetAverageRating();
     DefaultInventory = entryContentBase.GetStock();
 }
        protected void PopulateCommonData(EntryContentBase content, IMarket currentMarket, CustomerContact currentContact)
        {
            Code = content.Code;
            ContentLink = content.ContentLink;
            DisplayName = content.DisplayName ?? content.Name;
            ProductUrl = _urlResolver.GetUrl(ContentLink);
            Description = content.GetPropertyValue("Description");
            Overview = content.GetPropertyValue("Overview");
            AverageRating = content.GetPropertyValue<double>("AverageRating");

            InStock = content.GetStock() > 0;

            ContentType = content.GetType().Name;

            if (string.IsNullOrEmpty(Overview))
                Overview = Description;

            CurrentContactIsCustomerClubMember = currentContact.IsCustomerClubMember();
        }
        public WineFindProduct(EntryContentBase entryContentBase, string language)
            : base(entryContentBase, language)
        {
            WineSKUContent wineSkuContent = entryContentBase as WineSKUContent;
            if (wineSkuContent != null)
            {
                Varieties = wineSkuContent.GrapeMix;
                Vintage = wineSkuContent.Vintage;
                Taste = wineSkuContent.Taste;
                Style = wineSkuContent.Style;
                Country = wineSkuContent.Country;
                Region = wineSkuContent.Region;
                Maturity = wineSkuContent.Maturity;
                Alcohol = wineSkuContent.Alcohol;
                Closure = wineSkuContent.Closure;
                Brand = wineSkuContent.Facet_Brand;

            }
        }
 public static List<ContentReference> AssetImageReferences(this HtmlHelper html, EntryContentBase entry)
 {
     return entry.AssetImageUrls();
 }
        public static MvcHtmlString AssetUrl(this HtmlHelper html, EntryContentBase entry, UrlResolver urlResolver, IPermanentLinkMapper permanentLinkMapper)
        {
            var commerceMedia = entry.GetCommerceMedia();
            if (commerceMedia == null)
            {
                return new MvcHtmlString(null);
            }

            return AssetUrl(commerceMedia.AssetContentLink(permanentLinkMapper), urlResolver);
        }
        private List<EntryContentBase> GetAttachedVariants(EntryContentBase content)
        {
            var returnContents = new List<EntryContentBase>();

            if (content is ProductContent)
            {
                var productContent = content as ProductContent;
                var variations = _contentLoader.GetItems(productContent.GetVariants(_relationRepository), content.Language).OfType<EntryContentBase>();
                returnContents.AddRange(variations);
            }

            return returnContents;
        }
 public static MvcHtmlString AssetUrl(this HtmlHelper html, EntryContentBase entry)
 {
     return AssetUrl(html, entry, ServiceLocator.Current.GetInstance<UrlResolver>(), ServiceLocator.Current.GetInstance<IPermanentLinkMapper>());
 }
        private void Populate(PromotionEntry entry, EntryContentBase catalogEntry, IPriceValue price)
        {
            entry.Quantity = 1;
            entry.Owner = catalogEntry;
            entry["Id"] = catalogEntry.Code;

            if (catalogEntry.Property != null)
            {
                foreach (var prop in catalogEntry.Property.Where(x => x.IsPropertyData))
                {
                    entry[prop.Name] = prop.Value;
                }
            }

            entry["ExtendedPrice"] = price.UnitPrice.Amount;
            var inventories = _inventoryService.List(price.CatalogKey, _warehouseRepository.List()).ToList();
            if (!inventories.Any())
            {
                return;
            }

            entry["AllowBackordersAndPreorders"] = inventories.Any(i => i.AllowBackorder) && inventories.Any(i => i.AllowPreorder);
            entry["InStockQuantity"] = inventories.Sum(i => i.InStockQuantity - i.ReservedQuantity);
            entry["PreorderQuantity"] = inventories.Sum(i => i.PreorderQuantity);
            entry["BackorderQuantity"] = inventories.Sum(i => i.BackorderQuantity);
            entry["InventoryStatus"] = inventories.First().InventoryStatus;
        }
        private void AddMedia(EntryContentBase content, Entry entry)
        {
            if (entry.images != null && entry.images.Any())
            {
                for (int i = 0; i < entry.images.Count; i++)
                {
                    var imageLink = entry.images[i];
                    var path = imageLink.path;
                    var groupName = string.IsNullOrEmpty(imageLink.groupName) ? "default" : imageLink.groupName;

                    var existingMedia = _urlResolver.Route(new UrlBuilder(path)) as MediaData;

                    if (existingMedia != null)
                    {
                        // See if it is already linked
                        var commerceMedia = content.CommerceMediaCollection.FirstOrDefault(m => m.AssetLink.Equals(existingMedia.ContentLink));
                        if (commerceMedia == null)
                        {
                            // Attach media to this product
                            content.CommerceMediaCollection.Add(
                                new CommerceMedia()
                                {
                                    AssetLink = existingMedia.ContentLink,
                                    AssetType = "episerver.core.icontentimage",
                                    GroupName = groupName,
                                    SortOrder = i
                                });
                            _log.Debug("Attaching media '{0}' to {1}", path, content.Name);
                        }
                    }
                    else
                    {
                        // NOTE! We do not fail the import if the media does not exist
                        // TODO: Upload media to folder. Needs to make sure
                        // the path is correct
                    }
                }
            }
        }
        public ContentReference Update(EntryContentBase content, Entry entry, SaveAction saveAction)
        {
            if (string.IsNullOrEmpty(entry.urlSegment) == false)
            {
                content.RouteSegment = entry.urlSegment;
            }
            else
            {
                content.RouteSegment = entry.code.ToLowerInvariant();
            }

            //Set the Name
            content.Name = entry.name;
            content.DisplayName = entry.name;

            // Override with language
            var displayName = GetPropertyValue(entry.properties, content.Language.IetfLanguageTag, "DisplayName");
            if (string.IsNullOrEmpty(displayName) == false)
            {
                content.DisplayName = displayName;
            }

            SetProperties(content, entry.properties);

            // Configure Variation
            ConfigureVariationDefaults(content as VariationContent);

            // Add media
            AddMedia(content, entry);

            //Publish the new content and return its ContentReference.
            var contentReference = _contentRepository.Save(content, saveAction, AccessLevel.NoAccess);

            // Set default inventory
            if (Defaults.variationDefaultInventoryStock > 0)
            {
                SetDefaultInventory(entry.code, Defaults.variationDefaultInventoryStock);
            }

            // Set prices
            SetPrices(entry.code, entry.prices);

            return contentReference;
        }
        protected void SetProperties(EntryContentBase content, List<Property> properties)
        {
            if (properties == null)
                return;

            // Only look at properties for the current language
            foreach (Property importProperty in properties.Where(p => (string.IsNullOrEmpty(p.language) || p.language == content.Language.IetfLanguageTag)))
            {
                PropertyData propertyData = content.Property[importProperty.name];
                if(propertyData != null &&
                    (propertyData.Type == PropertyDataType.String || propertyData.Type == PropertyDataType.LongString))
                {
                    _log.Debug("Setting value for {0} ({1})", importProperty.name, importProperty.language ?? "null");
                    propertyData.Value = importProperty.value;
                }
            }
        }