예제 #1
0
 protected virtual LoaderOptions CreateDefaultLoadOptions()
 {
     return(new LoaderOptions
     {
         LanguageLoaderOption.FallbackWithMaster(LanguageResolver.GetPreferredCulture())
     });
 }
예제 #2
0
        public IEnumerable <SkuSearchResultModel> SearchSkus(string query)
        {
            var market   = _currentMarket.GetCurrentMarket();
            var currency = _currencyservice.GetCurrentCurrency();

            var results = _findClient.Search <GenericProduct>()
                          .Filter(_ => _.VariationModels(), x => x.Code.PrefixCaseInsensitive(query))
                          .FilterMarket(market)
                          .Filter(x => x.Language.Name.Match(_languageResolver.GetPreferredCulture().Name))
                          .Track()
                          .FilterForVisitor()
                          .Select(_ => _.VariationModels())
                          .GetResult()
                          .SelectMany(x => x)
                          .ToList();;

            if (results != null && results.Any())
            {
                return(results.Select(variation =>
                {
                    var defaultPrice = _priceService.GetDefaultPrice(market.MarketId, DateTime.Now,
                                                                     new CatalogKey(variation.Code), currency);
                    var discountedPrice = defaultPrice != null ? _promotionService.GetDiscountPrice(defaultPrice.CatalogKey, market.MarketId,
                                                                                                    currency) : null;
                    return new SkuSearchResultModel
                    {
                        Sku = variation.Code,
                        ProductName = variation.Name,
                        UnitPrice = discountedPrice?.UnitPrice.Amount ?? 0
                    };
                }));
            }
            return(Enumerable.Empty <SkuSearchResultModel>());
        }
예제 #3
0
 private IEnumerable <FashionVariant> GetVariants(PackageContent currentContent)
 {
     return(_contentLoader
            .GetItems(currentContent.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture())
            .OfType <FashionVariant>()
            .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
            .ToArray());
 }
        public SearchFilter GetSearchFilterForNode(NodeContent nodeContent)
        {
            var configFilter = new SearchFilter
            {
                field        = BaseCatalogIndexBuilder.FieldConstants.Node,
                Descriptions = new Descriptions
                {
                    defaultLocale = _languageResolver.GetPreferredCulture().Name
                },
                Values = new SearchFilterValues()
            };

            var desc = new Description
            {
                locale = "en",
                Value  = _localizationService.GetString("/Facet/Category")
            };

            configFilter.Descriptions.Description = new[] { desc };

            var nodes                = _contentLoader.GetChildren <NodeContent>(nodeContent.ContentLink).ToList();
            var nodeValues           = new SimpleValue[nodes.Count];
            var index                = 0;
            var preferredCultureName = _languageResolver.GetPreferredCulture().Name;

            foreach (var node in nodes)
            {
                var val = new SimpleValue
                {
                    key          = node.Code,
                    value        = node.Code,
                    Descriptions = new Descriptions
                    {
                        defaultLocale = preferredCultureName
                    }
                };
                var desc2 = new Description
                {
                    locale = preferredCultureName,
                    Value  = node.DisplayName
                };
                val.Descriptions.Description = new[] { desc2 };

                nodeValues[index] = val;
                index++;
            }
            configFilter.Values.SimpleValue = nodeValues;
            return(configFilter);
        }
예제 #5
0
        public override ActionResult Index(CarouselBlock currentBlock)
        {
            var model = new CarouselBlockViewModel(currentBlock);

            foreach (var item in _contentLoader.GetItems(currentBlock.CarouselItems, _languageResolver.GetPreferredCulture()))
            {
                if (item.GetOriginalType().Equals(typeof(ImageMediaData)))
                {
                    var image         = _contentLoader.Get <ImageMediaData>(item.ContentLink);
                    var carouselImage = new CarouselImage()
                    {
                        Heading     = image.Title,
                        Description = image.Description,
                        Image       = image.ContentLink
                    };

                    model.Items.Add(new CarouselItem()
                    {
                        CarouselImage = carouselImage
                    });
                }
                else if (item.GetOriginalType().Equals(typeof(HeroBlock)))
                {
                    var heroBlock = _contentLoader.Get <HeroBlock>(item.ContentLink);
                    model.Items.Add(new CarouselItem()
                    {
                        HeroBlock = new BlockViewModel <HeroBlock>(heroBlock)
                    });
                }
            }
            return(PartialView("~/Features/Blocks/Views/CarouselBlock.cshtml", model));
        }
        private IEnumerable <SearchResult> CreateSearchResults(IEnumerable <EntryContentBase> documents, string keyword)
        {
            var culture    = _languageResolver.GetPreferredCulture();
            var references = documents.Select(_ => _.ContentLink)
                             .ToList();

            var childReferences = documents.OfType <GenericProduct>()
                                  .SelectMany(x => x.Variations())
                                  .Select(x => x)
                                  .ToList();

            var entries = _contentLoader.GetItems(childReferences, culture)
                          .OfType <EntryContentBase>()
                          .Where(x => x.Name.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0 ||
                                 x.Code.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0);

            foreach (var entry in documents)
            {
                yield return(CreateMySearchResult(entry));
            }

            foreach (var entry in entries)
            {
                yield return(CreateMySearchResult(entry));
            }
        }
예제 #7
0
 private IEnumerable <FashionVariant> GetVariations(FashionProduct currentContent)
 {
     return(_contentLoader
            .GetItems(currentContent.GetVariants(_relationRepository), _languageResolver.GetPreferredCulture())
            .Cast <FashionVariant>()
            .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v)));
 }
        public IContent Get(ContentAreaItem contentAreaItem)
        {
            if (!ExternalReview.IsInExternalReviewContext)
            {
                return(_defaultContentAreaLoader.Get(contentAreaItem));
            }

            // load common draft instead of published version
            var commonDraft = _contentVersionRepository.LoadCommonDraft(contentAreaItem.ContentLink,
                                                                        _languageResolver.GetPreferredCulture().Name);

            if (commonDraft != null)
            {
                var content = _contentLoader.Get <IContent>(commonDraft.ContentLink);
                if (content.IsPublished())
                {
                    // for published version return the original method result
                    var defaultContent = _defaultContentAreaLoader.Get(contentAreaItem);
                    return(defaultContent);
                }

                contentAreaItem.ContentLink = commonDraft.ContentLink;

                return(content);
            }

            return(_defaultContentAreaLoader.Get(contentAreaItem));
        }
        public IEnumerable <EnhancedStructureStoreContentDataModel> GetLatestVersions(IEnumerable <ContentReference> ids,
                                                                                      NameValueCollection queryString)
        {
            if (ids == null)
            {
                return(null);
            }

            var draftLinks = new List <ContentReference>();

            foreach (var id in ids)
            {
                if (_currentProject.ProjectId.HasValue)
                {
                    var projectReference = _projectContentResolver.GetProjectReference(id, _currentProject.ProjectId.Value);
                    draftLinks.Add(projectReference);
                    continue;
                }

                var content = _contentLoader.Get <IContent>(id) as IVersionable;
                if (content == null)
                {
                    draftLinks.Add(id);
                    continue;
                }

                if (content.Status == VersionStatus.Published)
                {
                    var contentVersion =
                        _contentVersionRepository.LoadCommonDraft(id, _languageResolver.GetPreferredCulture().Name);
                    if (contentVersion != null)
                    {
                        draftLinks.Add(contentVersion.ContentLink);
                        continue;
                    }
                }

                draftLinks.Add(id);
            }

            var contents = _contentLoader.GetItems(draftLinks,
                                                   new LoaderOptions {
                LanguageLoaderOption.FallbackWithMaster()
            });
            var queryParameters = new ContentQueryParameters
            {
                AllParameters    = queryString,
                CurrentPrincipal = PrincipalInfo.CurrentPrincipal
            };

            // The ContentVersionFilter modify content links.
            // We have to use this filter here to make sure that we will use proper links
            return(_contentStoreModelCreator
                   .CreateContentDataStoreModels <EnhancedStructureStoreContentDataModel>(contents, queryParameters).ToList());
        }
예제 #10
0
        private CatalogEntrySearchCriteria CreateCriteriaForQuickSearch(FilterOptionViewModel filterOptions)
        {
            var sortOrder = GetSortOrder().FirstOrDefault(x => x.Name.ToString() == filterOptions.Sort) ?? GetSortOrder().First();
            var market    = _currentMarket.GetCurrentMarket();

            var criteria = new CatalogEntrySearchCriteria
            {
                ClassTypes = new StringCollection {
                    "product"
                },
                Locale            = _languageResolver.GetPreferredCulture().Name,
                MarketId          = market.MarketId,
                StartingRecord    = 0,
                RecordsToRetrieve = filterOptions.PageSize,
                Sort         = new SearchSort(new SearchSortField(sortOrder.Key, sortOrder.SortDirection == SortDirection.Descending)),
                SearchPhrase = GetEscapedSearchPhrase(filterOptions.Q)
            };

            return(criteria);
        }
        public IContent Get(ContentAreaItem contentAreaItem)
        {
            if (!ExternalReview.IsInExternalReviewContext)
            {
                return(_defaultContentAreaLoader.Get(contentAreaItem));
            }

            ContentReference referenceToLoad;

            if (ExternalReview.ProjectId.HasValue)
            {
                // load version from project
                referenceToLoad = _projectContentResolver.GetProjectReference(contentAreaItem.ContentLink,
                                                                              ExternalReview.ProjectId.Value);
            }
            else
            {
                // load common draft instead of published version
                var loadCommonDraft = _contentVersionRepository.LoadCommonDraft(contentAreaItem.ContentLink,
                                                                                _languageResolver.GetPreferredCulture().Name);
                if (loadCommonDraft == null)
                {
                    // fallback to default implementation if there is no common draft in a given language
                    return(_defaultContentAreaLoader.Get(contentAreaItem));
                }
                referenceToLoad = loadCommonDraft.ContentLink;
            }

            if (referenceToLoad != null)
            {
                var content = _contentLoader.Get <IContent>(referenceToLoad);
                if (HasExpired(content as IVersionable))
                {
                    return(null);
                }

                if (content.IsPublished())
                {
                    // for published version return the original method result
                    return(_defaultContentAreaLoader.Get(contentAreaItem));
                }

                if (!contentAreaItem.IsReadOnly)
                {
                    contentAreaItem.ContentLink = referenceToLoad;
                }

                return(content);
            }

            return(_defaultContentAreaLoader.Get(contentAreaItem));
        }
예제 #12
0
        public bool IsPublished(IContent content, PublishedStateCondition condition)
        {
            if (ExternalReview.IsInExternalReviewContext && ExternalReview.CustomLoaded.Contains(content.ContentLink.ToString()))
            {
                var cachedContent = ExternalReview.GetCachedContent(_languageResolver.GetPreferredCulture(), content.ContentLink);
                if (cachedContent != null)
                {
                    return(true);
                }
            }

            return(_defaultService.IsPublished(content, condition));
        }
        /// <summary>
        /// Returns content version by date
        /// </summary>
        /// <param name="contentLink">Version agnostic content id</param>
        /// <param name="date">Date of version</param>
        /// <returns>ContentReference to version available at <see cref="date"/></returns>
        public RestResultBase GetContentVersionByDate(ContentReference contentLink, DateTime date, string language)
        {
            if (ContentReference.IsNullOrEmpty(contentLink))
            {
                return(new RestStatusCodeResult(HttpStatusCode.Conflict));
            }

            if (string.IsNullOrWhiteSpace(language))
            {
                language = _languageResolver.GetPreferredCulture().Name;
            }

            var contentVersions = _contentVersionRepository.List(contentLink.ToReferenceWithoutVersion(), language).ToList();

            if (!contentVersions.Any())
            {
                return(Rest(null));
            }

            var version = contentVersions.Where(x => x.Saved < date).OrderByDescending(x => x.Saved).FirstOrDefault();

            if (version == null)
            {
                var oldestVersion = contentVersions.OrderBy(x => x.Saved).First();
                if (date <= oldestVersion.Saved)
                {
                    return(Rest(oldestVersion.ContentLink));
                }
                var newestVersion = contentVersions.OrderByDescending(x => x.Saved).First();
                if (date <= newestVersion.Saved)
                {
                    return(Rest(newestVersion.ContentLink));
                }
            }

            return(Rest(version?.ContentLink));
        }
예제 #14
0
        private IEnumerable <TVariant> GetVariants <TVariant, TEntryBase>(TEntryBase currentContent) where TVariant : VariationContent where TEntryBase : EntryContentBase
        {
            var bundle = currentContent as BundleContent;

            if (bundle != null)
            {
                return(_contentLoader
                       .GetItems(bundle.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture())
                       .OfType <TVariant>()
                       .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
                       .ToArray());
            }

            var package = currentContent as PackageContent;

            if (package != null)
            {
                return(_contentLoader
                       .GetItems(package.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture())
                       .OfType <TVariant>()
                       .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
                       .ToArray());
            }

            var product = currentContent as ProductContent;

            if (product != null)
            {
                return(_contentLoader
                       .GetItems(product.GetVariants(_relationRepository), _languageResolver.GetPreferredCulture())
                       .OfType <TVariant>()
                       .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
                       .ToArray());
            }

            return(Enumerable.Empty <TVariant>());
        }
예제 #15
0
        public virtual IEnumerable <ShipmentViewModel> CreateShipmentsViewModel(ICart cart)
        {
            var preferredCulture = _languageResolver.GetPreferredCulture();

            foreach (var shipment in cart.GetFirstForm().Shipments)
            {
                var shipmentModel = new ShipmentViewModel
                {
                    ShipmentId      = shipment.ShipmentId,
                    CartItems       = new List <CartItemViewModel>(),
                    Address         = _addressBookService.ConvertToModel(shipment.ShippingAddress),
                    ShippingMethods = CreateShippingMethodViewModels(cart.MarketId, cart.Currency, shipment)
                };


                var currentShippingMethod = shipmentModel.ShippingMethods.FirstOrDefault();
                if (shipment.ShippingMethodId != Guid.Empty)
                {
                    currentShippingMethod = shipmentModel.ShippingMethods.FirstOrDefault(x => x.Id == shipment.ShippingMethodId);
                }
                else
                {
                    currentShippingMethod = shipmentModel.ShippingMethods.FirstOrDefault();
                }

                shipmentModel.ShippingMethodId           = currentShippingMethod?.Id ?? shipment.ShippingMethodId;
                shipmentModel.CurrentShippingMethodName  = currentShippingMethod?.DisplayName ?? "In store pickup";
                shipmentModel.CurrentShippingMethodPrice = currentShippingMethod?.Price ?? new Money(0, cart.Currency);
                shipmentModel.WarehouseCode = shipment.WarehouseCode;

                var entries = _contentLoader.GetItems(shipment.LineItems.Select(x => _referenceConverter.GetContentLink(x.Code)),
                                                      preferredCulture).OfType <EntryContentBase>();

                foreach (var lineItem in shipment.LineItems)
                {
                    var entry = entries.FirstOrDefault(x => x.Code == lineItem.Code);
                    if (entry == null)
                    {
                        //Entry was deleted, skip processing.
                        continue;
                    }

                    shipmentModel.CartItems.Add(_cartItemViewModelFactory.CreateCartItemViewModel(cart, lineItem, entry));
                }

                yield return(shipmentModel);
            }
        }
        public ContentReference LoadUnpublishedVersion(ContentReference baseReference)
        {
            if (ExternalReview.ProjectId.HasValue)
            {
                // load version from project
                return(_projectContentResolver.GetProjectReference(baseReference,
                                                                   ExternalReview.ProjectId.Value));
            }

            // load common draft instead of published version
            var loadCommonDraft = _contentVersionRepository.LoadCommonDraft(baseReference,
                                                                            _languageResolver.GetPreferredCulture().Name);

            if (loadCommonDraft == null)
            {
                // fallback to default implementation if there is no common draft in a given language
                return(null);
            }

            return(loadCommonDraft.ContentLink);
        }
예제 #17
0
        public async Task <TrackingResponseData> TrackCart(HttpContextBase httpContext, ICart cart)
        {
            if (_contextModeResolver.CurrentMode != ContextMode.Default)
            {
                return(null);
            }

            if (cart != null)
            {
                var items        = GetCartDataItems(cart);
                var trackingData = new CartTrackingData(
                    items,
                    cart.Currency.CurrencyCode,
                    _languageResolver.GetPreferredCulture().Name,
                    GetRequestData(httpContext),
                    GetCommerceUserData(httpContext));
                return(await _trackingService.TrackAsync(trackingData, httpContext,
                                                         _contentRouteHelperAccessor().Content));
            }

            return(null);
        }
        public IContent Get(ContentAreaItem contentAreaItem)
        {
            if (!ExternalReview.IsInExternalReviewContext)
            {
                return(_defaultContentAreaLoader.Get(contentAreaItem));
            }

            ContentReference referenceToLoad;

            if (ExternalReview.ProjectId.HasValue)
            {
                // load version from project
                referenceToLoad = _projectContentResolver.GetProjectReference(contentAreaItem.ContentLink,
                                                                              ExternalReview.ProjectId.Value);
            }
            else
            {
                // load common draft instead of published version
                referenceToLoad = _contentVersionRepository.LoadCommonDraft(contentAreaItem.ContentLink,
                                                                            _languageResolver.GetPreferredCulture().Name).ContentLink;
            }

            if (referenceToLoad != null)
            {
                var content = _contentLoader.Get <IContent>(referenceToLoad);
                if (content.IsPublished())
                {
                    // for published version return the original method result
                    var defaultContent = _defaultContentAreaLoader.Get(contentAreaItem);
                    return(defaultContent);
                }

                contentAreaItem.ContentLink = referenceToLoad;

                return(content);
            }

            return(_defaultContentAreaLoader.Get(contentAreaItem));
        }
        public virtual IEnumerable <ShipmentViewModel> CreateShipmentsViewModel(ICart cart)
        {
            var preferredCulture = _languageResolver.GetPreferredCulture();

            foreach (var shipment in cart.GetFirstForm().Shipments)
            {
                var shipmentModel = new ShipmentViewModel
                {
                    ShipmentId      = shipment.ShipmentId,
                    CartItems       = new List <CartItemViewModel>(),
                    Address         = _addressBookService.ConvertToModel(shipment.ShippingAddress),
                    ShippingMethods = CreateShippingMethodViewModels(cart.Market, cart.Currency, shipment)
                };

                shipmentModel.ShippingMethodId = shipment.ShippingMethodId == Guid.Empty && shipmentModel.ShippingMethods.Any() ?
                                                 shipmentModel.ShippingMethods.First().Id
                                               : shipment.ShippingMethodId;

                var variants = _contentLoader.GetItems(shipment.LineItems.Select(x => _referenceConverter.GetContentLink(x.Code)),
                                                       preferredCulture).OfType <VariationContent>();

                foreach (var lineItem in shipment.LineItems)
                {
                    var variant = variants.Single(x => x.Code == lineItem.Code);

                    var productLink = variant.GetParentProducts(_relationRepository).FirstOrDefault();
                    if (ContentReference.IsNullOrEmpty(productLink))
                    {
                        continue;
                    }

                    shipmentModel.CartItems.Add(_cartItemViewModelFactory.CreateCartItemViewModel(cart, lineItem, variant));
                }

                yield return(shipmentModel);
            }
        }
예제 #20
0
        private IEnumerable <SearchResult> CreateSearchResults(IEnumerable <EntryContentBase> documents)
        {
            var culture    = _languageResolver.GetPreferredCulture();
            var references = documents.Select(_ => _.ContentLink)
                             .ToList();

            var childReferences = documents.OfType <GenericProduct>()
                                  .SelectMany(x => x.Variations())
                                  .Select(x => x)
                                  .ToList();

            var entries = _contentLoader.GetItems(childReferences, culture)
                          .OfType <EntryContentBase>();

            foreach (var entry in documents)
            {
                yield return(CreateMySearchResult(entry));
            }

            foreach (var entry in entries)
            {
                yield return(CreateMySearchResult(entry));
            }
        }
예제 #21
0
        public async Task <JsonResult> AddToCart(RequestParamsToCart param) // only use Code
        {
            if (WishList.Cart == null)
            {
                _wishlist = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultWishListName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            // return 0 if the variant already exist in wishlist
            // return 1 if added susscessfully
            var result       = new AddToCartResult();
            var allLineItems = WishList.Cart.GetAllLineItems();
            var contentLink  = _referenceConverter.GetContentLink(param.Code);
            var message      = "";
            var productName  = "";
            var entryLink    = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            if (_contentLoader.Get <EntryContentBase>(contentLink) is GenericBundle bundle) // Add bundle
            {
                var variantCodes = _contentLoader
                                   .GetItems(bundle.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture())
                                   .OfType <VariationContent>()
                                   .Where(v => v.IsAvailableInCurrentMarket(_currentMarket) && !_filterPublished.ShouldFilter(v))
                                   .Select(x => x.Code);
                var allLineItemCodes = allLineItems.Select(x => x.Code);
                var allNewCodes      = variantCodes.Where(x => !allLineItemCodes.Contains(x));
                if (!allNewCodes.Any())
                {
                    return(Json(new ChangeCartJsonResult {
                        StatusCode = 0, Message = productName + " already exist in the wishlist."
                    }));
                }
                else
                {
                    foreach (var v in allNewCodes)
                    {
                        result = _cartService.AddToCart(WishList.Cart, new RequestParamsToCart {
                            Code = v, Quantity = 1, Store = "delivery", SelectedStore = ""
                        });
                        if (result.ValidationMessages.Count > 0)
                        {
                            message += string.Join("\n", result.ValidationMessages);
                        }
                    }
                }
            }
            else // Add variant
            {
                if (allLineItems.Any(item => item.Code.Equals(param.Code, StringComparison.OrdinalIgnoreCase)))
                {
                    return(Json(new ChangeCartJsonResult {
                        StatusCode = 0, Message = productName + " already exist in the wishlist."
                    }));
                }

                result = _cartService.AddToCart(WishList.Cart,
                                                new RequestParamsToCart {
                    Code = param.Code, Quantity = 1, Store = "delivery", SelectedStore = ""
                });
            }

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(WishList.Cart);
                await _trackingService.TrackWishlist(HttpContext);

                return(Json(new ChangeCartJsonResult
                {
                    StatusCode = 1,
                    CountItems = (int)WishList.Cart.GetAllLineItems().Sum(x => x.Quantity),
                    Message = productName + " is added to the wishlist successfully.\n" + message
                }));
            }
            return(Json(new ChangeCartJsonResult {
                StatusCode = -1, Message = result.GetComposedValidationMessage()
            }));
        }
        public async Task <ActionResult> ChangeCartItem(RequestParamsToCart param) // change quantity
        {
            ModelState.Clear();

            var validationIssues = _cartService.ChangeCartItem(CartWithValidationIssues.Cart, param.ShipmentId, param.Code, param.Quantity, param.Size, param.NewSize);

            _orderRepository.Save(CartWithValidationIssues.Cart);
            var model = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, null);

            if (validationIssues.Any())
            {
                foreach (var item in validationIssues.Keys)
                {
                    model.Message += GetValidationMessages(item, validationIssues);
                }
            }
            var trackingResponse = await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

            //model.Recommendations = trackingResponse.GetCartRecommendations(_referenceConverter);
            var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(CartWithValidationIssues.Cart, null);

            if (param.RequestFrom == "changeSizeItem")
            {
                var preferredCulture = _languageResolver.GetPreferredCulture();
                var newCode          = _productService.GetSiblingVariantCodeBySize(param.Code, param.NewSize);
                var shipment         = CartWithValidationIssues.Cart.GetFirstForm().Shipments.FirstOrDefault(x => x.ShipmentId == param.ShipmentId);
                var lineItem         = shipment.LineItems.FirstOrDefault(x => x.Code == newCode);
                var entries          = _contentLoader.GetItems(shipment.LineItems.Select(x => _referenceConverter.GetContentLink(x.Code)),
                                                               preferredCulture).OfType <EntryContentBase>();
                var entry            = entries.FirstOrDefault(x => x.Code == lineItem.Code);
                var newItemViewModel = _cartItemViewModelFactory.CreateCartItemViewModel(CartWithValidationIssues.Cart, lineItem, entry);
                ViewData["ShipmentId"] = param.ShipmentId;
                return(PartialView("_ItemTemplate", newItemViewModel));
            }

            var productName = "";
            var entryLink   = _referenceConverter.GetContentLink(param.Code);

            productName = _contentLoader.Get <EntryContentBase>(entryLink).DisplayName;

            var result = new ChangeCartJsonResult
            {
                CountItems    = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                SubTotal      = viewModel.Subtotal,
                Total         = viewModel.Total,
                ShippingTotal = viewModel.ShippingTotal,
                TaxTotal      = viewModel.TaxTotal,
                TotalDiscount = viewModel.TotalDiscount
            };

            if (validationIssues.Count > 0)
            {
                result.StatusCode = 0;
                result.Message    = string.Join("\n", validationIssues.Select(x => string.Join("\n", x.Value.Select(v => v.ToString()))));
            }
            else
            {
                result.StatusCode = 1;
                result.Message    = productName + " has changed from the cart.";
            }

            return(Json(result));
        }
        public PartialRouteData GetPartialVirtualPath(ICategoryRoutableContent content, string language, RouteValueDictionary routeValues, RequestContext requestContext)
        {
            if (requestContext.IsInEditMode())
            {
                return(null);
            }

            // Single category
            object currentCategory;

            if (routeValues.TryGetValue(CategoryRoutingConstants.CurrentCategory, out currentCategory))
            {
                ContentReference categoryLink = currentCategory as ContentReference;

                if (ContentReference.IsNullOrEmpty(categoryLink))
                {
                    return(null);
                }

                CategoryData category;

                if (CategoryLoader.TryGet(categoryLink, out category) == false)
                {
                    return(null);
                }

                // Remove from query now that it's handled.
                routeValues.Remove(CategoryRoutingConstants.CurrentCategory);

                return(new PartialRouteData
                {
                    BasePathRoot = content.ContentLink,
                    PartialVirtualPath = $"{category.RouteSegment}/"
                });
            }

            // Multiple categories
            object currentCategories;

            if (routeValues.TryGetValue(CategoryRoutingConstants.CurrentCategories, out currentCategories))
            {
                var categoryContentLinks = currentCategories as IEnumerable <ContentReference>;

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

                var categorySegments = new List <string>();

                foreach (var categoryContentLink in categoryContentLinks)
                {
                    CategoryData category;
                    if (ContentLoader.TryGet(categoryContentLink, out category) == false)
                    {
                        return(null);
                    }

                    categorySegments.Add(category.RouteSegment);
                }

                categorySegments.Sort(StringComparer.Create(LanguageResolver.GetPreferredCulture(), true));

                // Remove from query now that it's handled.
                routeValues.Remove(CategoryRoutingConstants.CurrentCategories);

                return(new PartialRouteData
                {
                    BasePathRoot = content.ContentLink,
                    PartialVirtualPath = $"{string.Join(CategoryPartialRouter.CategorySeparator, categorySegments)}/"
                });
            }

            return(null);
        }
예제 #24
0
 public virtual IEnumerable <T> GetVariants <T>(PackageContent currentContent) where T : VariationContent
 {
     return(GetVariants <T>(currentContent.GetEntries(_relationRepository), _languageResolver.GetPreferredCulture()));
 }
예제 #25
0
        public ContentReference LoadUnpublishedVersion(ContentReference baseReference)
        {
            if (ExternalReview.ProjectId.HasValue)
            {
                // load version from project
                return(_projectContentResolver.GetProjectReference(baseReference,
                                                                   ExternalReview.ProjectId.Value, _languageResolver.GetPreferredCulture().Name));
            }

            // load common draft instead of published version
            ContentVersion loadCommonDraft;

            try
            {
                loadCommonDraft = _contentVersionRepository.LoadCommonDraft(baseReference, _languageResolver.GetPreferredCulture().Name);
            }
            catch (ContentNotFoundException)
            {
                _log.Debug($"Advanced Reviews: Content {baseReference} not found for LoadUnpublishedVersion");
                loadCommonDraft = null;
            }

            if (loadCommonDraft == null)
            {
                // fallback to default implementation if there is no common draft in a given language
                return(null);
            }

            return(loadCommonDraft.ContentLink);
        }
예제 #26
0
        public IEnumerable <Dependency> GetUnpublishedDependencies(ContentReference contentLink)
        {
            var dependencies       = new List <Dependency>();
            var root               = _contentRepository.Get <IContent>(contentLink);
            var directDependencies = GetLanguageAgnosticDependencies(root).ToList();
            var you = _localizationService.GetStringByCulture("/episerver/shared/text/yousubject",
                                                              CultureInfo.CurrentCulture);
            var currentUser = _httpContextAccessor()?.User?.Identity?.Name;

            foreach (var directDependency in directDependencies)
            {
                var content = _contentRepository.Get <IContent>(directDependency);
                if (!(content is BlockData))
                {
                    continue;
                }

                var reference        = GetUnpublishedVersion(content, _languageResolver.GetPreferredCulture());
                var referenceContent = reference != null?_contentRepository.Get <IContent>(reference) : content;

                var dependency = new Dependency
                {
                    CanBePublished = reference != null,
                    ContentLink    = reference ?? content.ContentLink,

                    Name                   = referenceContent.Name,
                    TypeIdentifier         = GetTypeIdentifier(referenceContent),
                    TreePath               = GetTreePath(referenceContent),
                    Uri                    = referenceContent.GetUri(),
                    IsPartOfActiveApproval = IsPartOfActiveApproval(referenceContent)
                };

                if (referenceContent is IChangeTrackable changeTrackable)
                {
                    var isCurrentUser = changeTrackable.ChangedBy.Equals(currentUser,
                                                                         StringComparison.InvariantCultureIgnoreCase);
                    dependency.Changed   = TimeAgoFormatter.RelativeDate(changeTrackable.Saved);
                    dependency.ChangedBy = isCurrentUser ? you : changeTrackable.ChangedBy;
                }

                var subDependencies = GetLanguageAgnosticDependencies(referenceContent).ToList();
                foreach (var subDependency in subDependencies)
                {
                    var subContent   = _contentRepository.Get <IContent>(subDependency);
                    var subReference = GetUnpublishedVersion(subContent, _languageResolver.GetPreferredCulture());
                    if (subReference == null)
                    {
                        continue;
                    }

                    if (dependencies.SelectMany(d => d.References.Select(x => x.ContentLink)).Contains(subReference))
                    {
                        continue;
                    }

                    var subContentVersion         = _contentRepository.Get <IContent>(subReference);
                    var richContentReferenceModel = new RichContentReferenceModel
                    {
                        ContentLink            = subReference,
                        Language               = subContentVersion.LanguageBranch(),
                        Name                   = subContentVersion.Name,
                        TreePath               = GetTreePath(subContentVersion),
                        Uri                    = subContent.GetUri(),
                        TypeIdentifier         = GetTypeIdentifier(subContentVersion),
                        IsPartOfActiveApproval = IsPartOfActiveApproval(subContentVersion)
                    };

                    if (subContentVersion is IChangeTrackable subContentTrackable)
                    {
                        var isCurrentUser = subContentTrackable.ChangedBy.Equals(currentUser,
                                                                                 StringComparison.InvariantCultureIgnoreCase);
                        richContentReferenceModel.Changed   = TimeAgoFormatter.RelativeDate(subContentTrackable.Saved);
                        richContentReferenceModel.ChangedBy = isCurrentUser ? you : subContentTrackable.ChangedBy;
                    }

                    dependency.References.Add(richContentReferenceModel);
                }

                if (dependency.CanBePublished || dependency.References.Count > 0)
                {
                    dependencies.Add(dependency);
                }
            }

            return(dependencies);
        }