public static void RenderBreadCrumb(this HtmlHelper html, ContentReference contentLink = null,
            IContentLoader contentLoader = null)
        {
            contentLink = contentLink ?? html.ViewContext.RequestContext.GetContentLink();

            contentLoader = contentLoader ?? ServiceLocator.Current.GetInstance<IContentLoader>();

            var pagePath = NavigationPath(contentLink, contentLoader);

            var path = FilterForVisitor.Filter(pagePath).OfType<PageData>().Select(x => x.PageLink);

            if (!path.Any())
            {

            }

            var writer = html.ViewContext.Writer;

            writer.WriteLine("<ol class=\"breadcrumb\">");

            foreach (var part in path)
            {
                if (part.CompareToIgnoreWorkID(contentLink))
                {
                    writer.WriteLine("<li class=\"active\">");

                    var currentPage = contentLoader.Get<PageData>(contentLink);

                    writer.WriteLine(html.Encode(currentPage.PageName));
                }
                else
                {
                    writer.WriteLine("<li>");
                    writer.WriteLine(html.PageLink(part));
                }

                writer.WriteLine("</li>");
            }

            writer.WriteLine("</ol>");
        }
示例#2
0
        public virtual string BuildRedirectionUrl(IPurchaseOrder purchaseOrder)
        {
            var queryCollection = new NameValueCollection
            {
                { "contactId", _customerContext.CurrentContactId.ToString() },
                { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
            };

            var confirmationPage = _contentRepository.GetFirstChild <OrderConfirmationPage>(_contentLoader.Get <StartPage>(ContentReference.StartPage).CheckoutPage);

            return(new UrlBuilder(confirmationPage.LinkURL)
            {
                QueryCollection = queryCollection
            }.ToString());
        }
示例#3
0
 private StartPage GetStartPage()
 {
     return(_contentLoader.Get <StartPage>(ContentReference.StartPage));
 }
        public ActionResult Index(OrderHistoryPage currentPage, OrderFilter filter, int?page, int?size, int?isPaging)
        {
            if (isPaging.HasValue)
            {
                filter = GetFilter();
            }
            else
            {
                SetCookieFilter(filter);
            }
            var pageNum        = page ?? 1;
            var pageSize       = size ?? 10;
            var orders         = _orderRepository.Load <IPurchaseOrder>(PrincipalInfo.CurrentPrincipal.GetContactId(), _cartService.DefaultCartName);
            var purchaseOrders = FilterOrders(orders, filter)
                                 .OrderByDescending(x => x.Created)
                                 .Skip((pageNum - 1) * pageSize)
                                 .Take(pageSize)
                                 .ToList();

            var viewModel = new OrderHistoryViewModel(currentPage)
            {
                CurrentContent = currentPage,
                Orders         = new List <OrderViewModel>(),
            };

            OrderFilter.LoadDefault(filter, _paymentMethodViewModelFactory);
            LoadAvailableAddresses(filter);

            foreach (var purchaseOrder in purchaseOrders)
            {
                // Assume there is only one form per purchase.
                var form           = purchaseOrder.GetFirstForm();
                var billingAddress = new AddressModel();
                var payment        = form.Payments.FirstOrDefault();
                if (payment != null)
                {
                    billingAddress = _addressBookService.ConvertToModel(payment.BillingAddress);
                }
                var orderViewModel = new OrderViewModel
                {
                    PurchaseOrder = purchaseOrder,
                    Items         = form.GetAllLineItems().Select(lineItem => new OrderHistoryItemViewModel
                    {
                        LineItem = lineItem,
                    }).GroupBy(x => x.LineItem.Code).Select(group => group.First()),
                    BillingAddress    = billingAddress,
                    ShippingAddresses = new List <AddressModel>()
                };

                foreach (var orderAddress in purchaseOrder.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
                {
                    var shippingAddress = _addressBookService.ConvertToModel(orderAddress);
                    orderViewModel.ShippingAddresses.Add(shippingAddress);
                }

                viewModel.Orders.Add(orderViewModel);
            }
            viewModel.OrderDetailsPageUrl =
                UrlResolver.Current.GetUrl(_contentLoader.Get <CommerceHomePage>(ContentReference.StartPage).OrderDetailsPage);

            viewModel.PagingInfo.PageNumber  = pageNum;
            viewModel.PagingInfo.TotalRecord = purchaseOrders.Count();
            viewModel.PagingInfo.PageSize    = pageSize;
            viewModel.OrderHistoryUrl        = Request.Url.PathAndQuery;
            viewModel.Filter = filter;
            return(View(viewModel));
        }
        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.Count() == 0)
                {
                    return(Json(new ChangeCartJsonResult {
                        StatusCode = 0, Message = productName + " already exist in the wishlist."
                    }));
                }
                else
                {
                    foreach (var v in allNewCodes)
                    {
                        result = _cartService.AddToCart(WishList.Cart, v, 1, "delivery", "");
                        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, param.Code, 1, "delivery", "");
            }

            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()
            }));
        }
        private static PageData ToPage(ContentReference reference, IContentLoader repository)
        {
            var page = repository.Get <PageData>(reference);

            return(page);
        }
示例#7
0
        public object RoutePartial(PageData content, SegmentContext segmentContext)
        {
            if (!_externalReviewOptions.IsEnabled)
            {
                return(null);
            }

            var nextSegment = segmentContext.GetNextValue(segmentContext.RemainingPath);

            if (string.IsNullOrWhiteSpace(nextSegment.Next))
            {
                return(null);
            }

            if (!string.Equals(nextSegment.Next, _externalReviewOptions.ContentPreviewUrl, StringComparison.CurrentCultureIgnoreCase))
            {
                return(null);
            }

            nextSegment = segmentContext.GetNextValue(nextSegment.Remaining);
            var token = nextSegment.Next;

            var externalReviewLink = _externalReviewLinksRepository.GetContentByToken(token);

            if (!externalReviewLink.IsPreviewableLink())
            {
                return(null);
            }

            var contentReference = externalReviewLink.ContentLink;

            if (externalReviewLink.ProjectId.HasValue)
            {
                var contentContentLink = PreviewUrlResolver.IsGenerated(segmentContext.QueryString) ? content.ContentLink : contentReference;
                contentReference         = _projectContentResolver.GetProjectReference(contentContentLink, externalReviewLink.ProjectId.Value);
                ExternalReview.ProjectId = externalReviewLink.ProjectId;
            }

            try
            {
                var page = _contentLoader.Get <IContent>(contentReference);

                // PIN code security check, if user is not authenticated, then redirect to login page
                if (!_externalLinkPinCodeSecurityHandler.UserHasAccessToLink(externalReviewLink))
                {
                    _externalLinkPinCodeSecurityHandler.RedirectToLoginPage(externalReviewLink);
                    return(null);
                }
                segmentContext.RemainingPath = nextSegment.Remaining;

                // set ContentLink in DataTokens to make IPageRouteHelper working
                segmentContext.RouteData.DataTokens[RoutingConstants.NodeKey] = page.ContentLink;
                ExternalReview.Token = token;

                return(page);
            }
            catch (ContentNotFoundException)
            {
                return(null);
            }
        }
    private static IEnumerable<PageData> NavigationPath(
      ContentReference contentLink,
      IContentLoader contentLoader,
      ContentReference fromLink = null)
    {
      fromLink = fromLink ?? ContentReference.RootPage;

      //Find all pages between the current and the 
      //"from" page, in top-down order.
      var path = contentLoader.GetAncestors(contentLink)
          .Reverse()
          .SkipWhile(x =>
            ContentReference.IsNullOrEmpty(x.ParentLink)
            || !x.ParentLink.CompareToIgnoreWorkID(fromLink))
          .OfType<PageData>()
          .ToList();

      //In theory the current content may not be a page.
      //We check that and, if it is, add it to the end of
      //the content tree path.
      var currentPage = contentLoader
        .Get<IContent>(contentLink) as PageData;
      if (currentPage != null)
      {
        path.Add(currentPage);
      }
      return path;
    }
 /// <summary>
 /// Loads content
 /// </summary>
 /// <param name="contentLink"></param>
 /// <returns></returns>
 public virtual IContent GetContent(ContentReference contentLink)
 {
     return(_contentLoader.Get <IContent>(contentLink));
 }
        protected virtual HeaderViewModel CreateViewModel(IContent currentContent, HomePage homePage)
        {
            var menuItems      = new List <MenuItemViewModel>();
            var homeLanguage   = homePage.Language.DisplayName;
            var layoutSettings = _settingsService.GetSiteSettings <LayoutSettings>();
            var filter         = new FilterContentForVisitor();

            menuItems = layoutSettings?.MainMenu?.FilteredItems.Where(x =>
            {
                var _menuItem = _contentLoader.Get <IContent>(x.ContentLink);
                MenuItemBlock _menuItemBlock;
                if (_menuItem is MenuItemBlock)
                {
                    _menuItemBlock = _menuItem as MenuItemBlock;
                    if (_menuItemBlock.Link == null)
                    {
                        return(true);
                    }
                    var linkedItem = UrlResolver.Current.Route(new UrlBuilder(_menuItemBlock.Link));
                    if (filter.ShouldFilter(linkedItem))
                    {
                        return(false);
                    }
                    return(true);
                }
                return(true);
            }).Select(x =>
            {
                var content = _contentLoader.Get <IContent>(x.ContentLink);
                MenuItemBlock _;
                MenuItemViewModel menuItem;
                if (content is MenuItemBlock)
                {
                    _        = content as MenuItemBlock;
                    menuItem = new MenuItemViewModel
                    {
                        Name       = _.Name,
                        ButtonText = _.ButtonText,
                        //TeaserText = _.TeaserText,
                        Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                        {
                            ContextMode = ContextMode.Default
                        }),
                        ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                        ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                        ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                    };
                }
                else
                {
                    menuItem = new MenuItemViewModel
                    {
                        Name = content.Name,
                        Uri  = _urlResolver.GetUrl(content.ContentLink),
                        //ChildLinks = new List<GroupLinkCollection>()
                    };
                }

                if (!_contextModeResolver.CurrentMode.EditOrPreview())
                {
                    var keyDependency = new List <string>
                    {
                        _contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink), // If The HomePage updates menu (remove MenuItems)
                        _contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink)
                    };
                }

                return(menuItem);
            }).ToList();

            return(new HeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly,
                MenuItems = menuItems ?? new List <MenuItemViewModel>(),
                IsInEditMode = _contextModeResolver.CurrentMode.EditOrPreview()
            });
        }
示例#11
0
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            var cart = _orderRepository.LoadCart <ICart>(GetContactId(), DefaultCart);

            var isAutenticated = PrincipalInfo.CurrentPrincipal.Identity.IsAuthenticated;

            var orderAddress = AddAddressToOrder(cart);

            AdjustFirstShipmentInOrder(cart, orderAddress, model.SelectedShippingId);

            AddPaymentToOrder(cart, model.SelectedPaymentId);

            var validationMessages = ValidateCart(cart);

            if (!string.IsNullOrEmpty(validationMessages))
            {
                model.Warnings = validationMessages;
            }

            // Adding this for test
            var cartReference = _orderRepository.Save(cart);

            IPurchaseOrder purchaseOrder;
            OrderReference orderReference;

            using (var scope = new TransactionScope())
            {
                var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.InProgress, (item, issue) => validationIssues.Add(item, issue));

                if (validationIssues.Count >= 1)
                {
                    throw new Exception("Not possible right now");
                }

                try
                {
                    cart.ProcessPayments();
                }
                catch (Exception e)
                {
                    foreach (
                        var p in cart.GetFirstForm().Payments.Where(p => p.Status != PaymentStatus.Processed.ToString()))
                    {
                        cart
                    }
                    _orderRepository.Save(cart);
                    throw new Exception("Payment failed");
                }

                var totalProcessedAmount = cart.GetFirstForm().Payments.Where
                                               (x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

                var cartTotal = cart.GetTotal();

                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                        , OrderStatus.Cancelled, (item, issue) => validationIssues.Add(item, issue));


                    throw new InvalidOperationException("Wrong amount"); // maybe change approach
                }


                // ...could do this here
                cart.GetFirstShipment().OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

                // decrement inventory and let it go
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.Completed, (item, issue) => validationIssues.Add(item, issue));

                orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
                purchaseOrder  = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);
                _orderRepository.Delete(cart.OrderLink);

                scope.Complete();
            }

            var note = _orderGroupFactory.CreateOrderNote(purchaseOrder);

            note.CustomerId = GetContactId();
            note.Title      = "Order Created";
            note.Detail     = "Order Created by Commerce Training Fundamentals";
            note.Type       = OrderNoteTypes.Custom.ToString();

            purchaseOrder.Notes.Add(note);

            _orderRepository.Save(purchaseOrder);

            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            // the below is a dummy, change to "PO".OrderNumber when done
            string passingValue = purchaseOrder.OrderNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
示例#12
0
        public ActionResult Index(TagPage currentPage)
        {
            var model = new TagsViewModel(currentPage)
            {
                Continent = ControllerContext.RequestContext.GetCustomRouteData <string>("Continent")
            };

            var addcat = ControllerContext.RequestContext.GetCustomRouteData <string>("Category");

            if (addcat != null)
            {
                model.AdditionalCategories = addcat.Split(',');
            }

            var query = SearchClient.Instance.Search <LocationItemPage.LocationItemPage>()
                        .Filter(f => f.TagString().Match(currentPage.Name));

            if (model.AdditionalCategories != null)
            {
                query = model.AdditionalCategories.Aggregate(query, (current, c) => current.Filter(f => f.TagString().Match(c)));
            }
            if (model.Continent != null)
            {
                query = query.Filter(dp => dp.Continent.MatchCaseInsensitive(model.Continent));
            }
            model.Locations = query.StaticallyCacheFor(new System.TimeSpan(0, 1, 0)).GetContentResult().ToList();

            //Add theme images from results
            var carousel = new TagsCarouselViewModel
            {
                Items = new List <TagsCarouselItem>()
            };

            foreach (var location in model.Locations)
            {
                if (location.Image != null)
                {
                    carousel.Items.Add(new TagsCarouselItem
                    {
                        Image       = location.Image,
                        Heading     = location.Name,
                        Description = location.MainIntro,
                        ItemURL     = location.ContentLink
                    });
                }
            }
            if (carousel.Items.All(item => item.Image == null) || currentPage.Images != null)
            {
                if (currentPage.Images != null && currentPage.Images.FilteredItems != null)
                {
                    foreach (var image in currentPage.Images.FilteredItems.Select(ci => ci.ContentLink))
                    {
                        var title = _contentLoader.Get <ImageMediaData>(image).Title;
                        carousel.Items.Add(new TagsCarouselItem {
                            Image = image, Heading = title
                        });
                    }
                }
            }
            model.Carousel = carousel;

            return(View(model));
        }
        /// <summary>
        /// Executes a catalog search using EPiServer Find. This search works
        /// from the Catalog UI, the global search and
        /// </summary>
        /// <remarks>
        /// This implementation is not generic, since it knows all about
        /// the catalog model, and how the products are indexed. Because
        /// of this, we can create a good product search for editors.
        /// </remarks>
        /// <param name="query">The query to execute</param>
        /// <returns>
        /// A list of search results. If the search fails with an exception, it will
        /// be logged, and the user will be notified that no content could be found.
        /// </returns>
        public virtual IEnumerable <SearchResult> Search(Query query)
        {
            query.MaxResults = 20;
            string keyword = query.SearchQuery;

            _log.Debug("Searching for: {0} using MaxResults: {1}", keyword, query.MaxResults);

            CultureInfo currentCulture = ContentLanguage.PreferredCulture;

            ITypeSearch <FindProduct> search = SearchClient.Instance.Search <FindProduct>();

            search = search.For(keyword)
                     // Search with stemming on name and code
                     .InField(p => p.DisplayName)
                     .InField(p => p.Code)
                     .InAllField() // Also search in _all field (without stemming)
                     .Filter(p => p.Language.Match(currentCulture.Name))
                     .Take(query.MaxResults);

            SearchResults <FindProduct> results = search.GetResult();

            _log.Debug("Find Search: {0} hits", results.TotalMatching);

            List <SearchResult> entryResults = new List <SearchResult>();

            foreach (FindProduct product in results)
            {
                // Get Content
                ContentReference contentLink = _referenceConverter.GetContentLink(product.Id, CatalogContentType.CatalogEntry, 0);
                EntryContentBase content     = _contentLoader.Get <EntryContentBase>(contentLink);
                if (content != null)
                {
                    string url     = GetEditUrl(content.ContentLink);
                    string preview = ""; // TextIndexer.StripHtml(product.Description.ToString(), 50);

                    _log.Debug("Found: {0} - {1}", product.DisplayName, url);
                    SearchResult result = new SearchResult(url, string.Format("{0} ({1})", product.DisplayName, content.Code), preview);
                    result.IconCssClass = "epi-resourceIcon epi-resourceIcon-page";
                    result.Language     = content.Language.Name;
                    result.ToolTipElements.Add(new ToolTipElement()
                    {
                        Label = "Category", Value = product.CategoryName
                    });
                    result.ToolTipElements.Add(new ToolTipElement()
                    {
                        Label = "Main Category", Value = product.MainCategoryName
                    });
                    if (product.Color != null)
                    {
                        foreach (string color in product.Color)
                        {
                            result.ToolTipElements.Add(new ToolTipElement()
                            {
                                Label = "Color", Value = color
                            });
                        }
                    }
                    if (product.Variants != null)
                    {
                        result.ToolTipElements.Add(new ToolTipElement()
                        {
                            Label = "# of Variations", Value = product.Variants.Count().ToString()
                        });
                    }

                    result.Metadata.Add("parentId", content.ParentLink.ToString());
                    result.Metadata.Add("parentType", CatalogContentType.CatalogNode.ToString());
                    result.Metadata.Add("id", contentLink.ToString());
                    result.Metadata.Add("code", content.Code);
                    result.Metadata.Add("languageBranch", content.Language.Name);

                    entryResults.Add(result);
                }
                else
                {
                    _log.Debug("Cannot load: {0}", contentLink);
                }
            }
            return(entryResults);
        }
        public IEnumerable <T> GetChildrenWithReviews <T>(
            ContentReference contentLink, LoaderOptions loaderOptions, int startIndex, int maxRows) where T : IContentData
        {
            if (ContentReference.IsNullOrEmpty(contentLink))
            {
                throw new ArgumentNullException(nameof(contentLink), "Parameter has no value set");
            }

            if (!ExternalReview.IsInExternalReviewContext)
            {
                return(_contentLoader.GetChildren <T>(contentLink));
            }

            ContentReference referenceWithoutVersion = contentLink.ToReferenceWithoutVersion();

            if (referenceWithoutVersion == ContentReference.WasteBasket)
            {
                return(_contentLoader.GetChildren <T>(contentLink));
            }

            var provider = _contentProviderManager.ProviderMap.GetProvider(referenceWithoutVersion);

            var parentContent      = _contentLoader.Get <IContent>(referenceWithoutVersion, loaderOptions);
            var localizable        = parentContent as ILocalizable;
            var languageID         = localizable != null ? localizable.Language.Name : (string)null;
            var childrenReferences =
                provider.GetChildrenReferences <T>(referenceWithoutVersion, languageID, startIndex, maxRows);

            var result = new List <ContentReference>();

            foreach (var childReference in childrenReferences)
            {
                var referenceToLoad = LoadUnpublishedVersion(childReference.ContentLink);
                if (referenceToLoad == null)
                {
                    result.Add(childReference.ContentLink);
                }
                else
                {
                    var content = _contentLoader.Get <T>(referenceToLoad);
                    if (HasExpired(content as IVersionable))
                    {
                        continue;
                    }

                    if ((content as IContent).IsPublished())
                    {
                        // for published version return the original method result
                        result.Add(childReference.ContentLink);
                        continue;
                    }

                    result.Add((content as IContent).ContentLink);
                }
            }

            var childrenWithReviews = result.Select(_contentLoader.Get <T>).ToList();


            if (childrenWithReviews.Count > 0)
            {
                var pageData = parentContent as PageData;
                if (pageData != null && pageData.ChildSortOrder == FilterSortOrder.Alphabetical && (startIndex == -1 && maxRows == -1 ||
                                                                                                    childrenWithReviews.Count < maxRows && startIndex == 0))
                {
                    var collection = _childrenSorter.Sort((IEnumerable <IContent>)childrenWithReviews);
                    childrenWithReviews = collection.Cast <T>().ToList();
                }
            }

            return(childrenWithReviews);
        }
    public static void RenderBreadcrumb(
      this HtmlHelper html,
      ContentReference contentLink = null,
      IContentLoader contentLoader = null)
    {
      contentLink = contentLink ??
        html.ViewContext.RequestContext.GetContentLink();
      contentLoader = contentLoader ??
        ServiceLocator.Current.GetInstance<IContentLoader>();

      var pagePath = NavigationPath(contentLink, contentLoader);
      var path = FilterForVisitor.Filter(pagePath)
        .OfType<PageData>()
        .Select(x => x.PageLink);
      if (!path.Any())
      {
        //Nothing to render, no need to output an empty list.
        return;
      }

      var writer = html.ViewContext.Writer;

      writer.WriteLine("<ol class=\"breadcrumb\">");

      foreach (var part in path)
      {
        if (part.CompareToIgnoreWorkID(contentLink))
        {
          writer.WriteLine("<li class=\"active\">");

          //For the current page there's no point in outputting a link.
          //Instead output just the (encoded) page name.
          var currentPage = contentLoader.Get<PageData>(contentLink);
          writer.WriteLine(html.Encode(currentPage.PageName));
        }
        else
        {
          writer.WriteLine("<li>");
          writer.WriteLine(html.PageLink(part));
        }

        writer.WriteLine("</li>");
      }

      writer.WriteLine("</ol>");
    }
示例#16
0
        public IEnumerable <RecommendedProductTileViewModel> GetRecommendedProductTileViewModels(IEnumerable <Recommendation> recommendations)
        {
            var language = _languageService.GetCurrentLanguage();

            return(recommendations.Select(x =>
                                          new RecommendedProductTileViewModel(
                                              x.RecommendationId,
                                              _productService.GetProductTileViewModel(_contentLoader.Get <EntryContentBase>(x.ContentLink, language))
                                              )
                                          ));
        }
示例#17
0
        public virtual TViewModel Create <TProduct, TVariant, TViewModel>(TProduct currentContent, string variationCode)
            where TProduct : ProductContent
            where TVariant : VariationContent
            where TViewModel : ProductViewModelBase <TProduct, TVariant>, new()
        {
            var variants = GetVariants <TVariant, TProduct>(currentContent)
                           .Where(v => v.Prices().Any(x => x.MarketId == _currentMarket.GetCurrentMarket().MarketId))
                           .ToList();

            if (!TryGetVariant(variants, variationCode, out var variant))
            {
                return(new TViewModel
                {
                    Product = currentContent,
                    CurrentContent = currentContent,
                    Images = currentContent.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                    Colors = new List <SelectListItem>(),
                    Sizes = new List <SelectListItem>(),
                    StaticAssociations = new List <ProductTileViewModel>(),
                    Variants = new List <VariantViewModel>()
                });
            }

            var market            = _currentMarket.GetCurrentMarket();
            var currency          = _currencyservice.GetCurrentCurrency();
            var defaultPrice      = PriceCalculationService.GetSalePrice(variant.Code, market.MarketId, currency);
            var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(variant.Code, market.MarketId, currency);
            var discountedPrice   = GetDiscountPrice(defaultPrice, market, currency);
            var currentStore      = _storeService.GetCurrentStoreViewModel();
            var relatedProducts   = currentContent.GetRelatedEntries().ToList();
            var associations      = relatedProducts.Any() ?
                                    _productService.GetProductTileViewModels(relatedProducts) :
                                    new List <ProductTileViewModel>();
            var contact                = PrincipalInfo.CurrentPrincipal.GetCustomerContact();
            var baseVariant            = variant as GenericVariant;
            var productRecommendations = currentContent as IProductRecommendations;
            var isSalesRep             = PrincipalInfo.CurrentPrincipal.IsInRole("SalesRep");

            return(new TViewModel
            {
                CurrentContent = currentContent,
                Product = currentContent,
                Variant = variant,
                ListingPrice = defaultPrice?.UnitPrice ?? new Money(0, currency),
                DiscountedPrice = discountedPrice,
                SubscriptionPrice = subscriptionPrice?.UnitPrice ?? new Money(0, currency),
                Colors = variants.OfType <GenericVariant>()
                         .Where(x => x.Color != null)
                         .GroupBy(x => x.Color)
                         .Select(g => new SelectListItem
                {
                    Selected = false,
                    Text = g.Key,
                    Value = g.Key
                }).ToList(),
                Sizes = variants.OfType <GenericVariant>()
                        .Where(x => (x.Color == null || x.Color.Equals(baseVariant?.Color, StringComparison.OrdinalIgnoreCase)) && x.Size != null)
                        .Select(x => new SelectListItem
                {
                    Selected = false,
                    Text = x.Size,
                    Value = x.Size
                }).ToList(),
                Color = baseVariant?.Color,
                Size = baseVariant?.Size,
                Images = variant.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                IsAvailable = defaultPrice != null,
                Stores = new StoreViewModel
                {
                    Stores = _storeService.GetEntryStoresViewModels(variant.Code),
                    SelectedStore = currentStore != null ? currentStore.Code : "",
                    SelectedStoreName = currentStore != null ? currentStore.Name : ""
                },
                StaticAssociations = associations,
                Variants = variants.Select(x =>
                {
                    var variantImage = x.GetAssets <IContentImage>(_contentLoader, _urlResolver).FirstOrDefault();
                    var variantDefaultPrice = GetDefaultPrice(x.Code, market, currency);
                    return new VariantViewModel
                    {
                        Sku = x.Code,
                        Size = x is GenericVariant ? $"{(x as GenericVariant).Color} {(x as GenericVariant).Size}" : "",
                        ImageUrl = string.IsNullOrEmpty(variantImage) ? "http://placehold.it/54x54/" : variantImage,
                        DiscountedPrice = GetDiscountPrice(variantDefaultPrice, market, currency),
                        ListingPrice = variantDefaultPrice?.UnitPrice ?? new Money(0, currency),
                        StockQuantity = _quickOrderService.GetTotalInventoryByEntry(x.Code)
                    };
                }).ToList(),
                HasOrganization = contact?.OwnerId != null,
                ShowRecommendations = productRecommendations?.ShowRecommendations ?? true,
                IsSalesRep = isSalesRep,
                SalesMaterials = isSalesRep ? currentContent.CommerceMediaCollection.Where(x => !string.IsNullOrEmpty(x.GroupName) && x.GroupName.Equals("sales"))
                                 .Select(x => _contentLoader.Get <MediaData>(x.AssetLink)).ToList() : new List <MediaData>(),
                Documents = currentContent.CommerceMediaCollection.Where(o => o.AssetType.Equals(typeof(PDFFile).FullName.ToLowerInvariant()))
                            .Select(x => _contentLoader.Get <MediaData>(x.AssetLink)).ToList()
            });
        }
示例#18
0
        private SyndicationItem CreateItemFromReference(ContentReference contentReference)
        {
            var content = ContentLoader.Get <IContent>(contentReference);

            return(CreateSyndicationItem(content));
        }
示例#19
0
 public virtual T Get <T>(ContentReference contentLink) where T : CatalogContentBase
 {
     return(_contentLoader.Get <T>(contentLink, _languageService.GetCurrentLanguage()));
 }
示例#20
0
        public ActionResult Index(BaseProduct currentContent, string variationCode = "", bool quickview = false)
        {
            var variations = GetVariations(currentContent).ToList();

            if (_isInEditMode && !variations.Any())
            {
                var productWithoutVariation = new BaseProductViewModel
                {
                    Product         = currentContent,
                    Images          = currentContent.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                    CategoryPage    = _contentLoader.Get <NodeContent>(_contentLoader.Get <NodeContent>(currentContent.ParentLink).ParentLink),
                    SubcategoryPage = _contentLoader.Get <NodeContent>(currentContent.ParentLink)
                };
                return(Request.IsAjaxRequest() ? PartialView("ProductWithoutVariation", productWithoutVariation) : (ActionResult)View("ProductWithoutVariation", productWithoutVariation));
            }

            BaseVariant variation;

            if (!TryGetVariant(variations, variationCode, out variation))
            {
                return(HttpNotFound());
            }

            var market   = _currentMarket.GetCurrentMarket();
            var currency = _currencyservice.GetCurrentCurrency();

            var defaultPrice    = GetDefaultPrice(variation, market, currency);
            var discountedPrice = GetDiscountPrice(defaultPrice, market, currency);

            var viewModel = new BaseProductViewModel
            {
                Product         = currentContent,
                Variation       = variation,
                ListingPrice    = defaultPrice != null ? defaultPrice.UnitPrice : new Money(0, currency),
                DiscountedPrice = discountedPrice,
                Colors          = variations
                                  .Where(x => x.Size != null)
                                  .GroupBy(x => x.Color)
                                  .Select(g => new SelectListItem
                {
                    Selected = false,
                    Text     = g.First().Color,
                    Value    = g.First().Color
                })
                                  .ToList(),
                Sizes = variations
                        .Where(x => x.Color != null && x.Color.Equals(variation.Color, StringComparison.OrdinalIgnoreCase))
                        .Select(x => new SelectListItem
                {
                    Selected = false,
                    Text     = x.Size,
                    Value    = x.Size
                })
                        .ToList(),
                Color       = variation.Color,
                Size        = variation.Size,
                Images      = variation.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                IsAvailable = defaultPrice != null,
                Variants    = variations.Select(variant =>
                {
                    var variantImage        = variant.GetAssets <IContentImage>(_contentLoader, _urlResolver).FirstOrDefault();
                    var variantDefaultPrice = GetDefaultPrice(variant, market, currency);
                    return(new VariantViewModel
                    {
                        Sku = variant.Code,
                        Size = $"{variant.Color} {variant.Size}",
                        ImageUrl = string.IsNullOrEmpty(variantImage) ? "http://placehold.it/54x54/" : variantImage,
                        DiscountedPrice = GetDiscountPrice(variantDefaultPrice, market, currency),
                        ListingPrice = variantDefaultPrice?.UnitPrice ?? new Money(0, currency),
                        StockQuantity = _quickOrderService.GetTotalInventoryByEntry(variant.Code)
                    });
                }).ToList(),
                CategoryPage    = _contentLoader.Get <NodeContent>(_contentLoader.Get <NodeContent>(currentContent.ParentLink).ParentLink),
                SubcategoryPage = _contentLoader.Get <NodeContent>(currentContent.ParentLink)
            };

            if (Session[Constants.ErrorMesages] != null)
            {
                var messages = Session[Constants.ErrorMesages] as List <string>;
                viewModel.ReturnedMessages      = messages;
                Session[Constants.ErrorMesages] = "";
            }

            if (quickview)
            {
                return(PartialView("Quickview", viewModel));
            }

            return(Request.IsAjaxRequest() ? PartialView(viewModel) : (ActionResult)View(viewModel));
        }
示例#21
0
        private bool IsValid(PromotionData promotion, IMarket market)
        {
            var campaign = _contentLoader.Get <SalesCampaign>(promotion.ParentLink);

            return(IsActive(promotion, campaign) && IsValidMarket(campaign, market));
        }
        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);
        }
示例#23
0
        public void GetContentFamily_ValidRootId_ReturnsContentTreeRootItem()
        {
            // Arrange
            const int    rootId          = 1;
            const string rootName        = "root";
            var          rootReference   = new ContentReference(rootId);
            const int    childId1        = 2;
            const string childName1      = "child";
            var          childReference1 = new ContentReference(childId1);
            const int    childId2        = 3;
            const string childName2      = "child";
            var          childReference2 = new ContentReference(childId2);
            var          rootPage        = new PageData
            {
                Property =
                {
                    new PropertyString           {
                        Name = "PageName", Value = rootName
                    },
                    new PropertyContentReference {
                        Name = "PageLink", Value = rootReference
                    }
                }
            };
            var childPage1 = new PageData
            {
                Property =
                {
                    new PropertyString           {
                        Name = "PageName", Value = childName1
                    },
                    new PropertyContentReference {
                        Name = "PageLink", Value = childReference1
                    }
                }
            };
            var childPage2 = new PageData
            {
                Property =
                {
                    new PropertyString           {
                        Name = "PageName", Value = childName2
                    },
                    new PropertyContentReference {
                        Name = "PageLink", Value = childReference2
                    }
                }
            };
            const string testLanguageCode = "en";
            var          testLanguage     = CultureInfo.GetCultureInfo(testLanguageCode);

            _stubContentLoader.Get <PageData>(rootReference, testLanguage).Returns(rootPage);
            _stubContentLoader.GetChildren <PageData>(rootReference, testLanguage).Returns(new List <PageData> {
                childPage1, childPage2
            });
            _stubContentLoader.GetChildren <PageData>(childReference1, testLanguage).Returns(new List <PageData> {
                new PageData()
            });
            _stubContentLoader.GetChildren <PageData>(childReference2, testLanguage).Returns(Enumerable.Empty <PageData>());

            // Act
            var result = _contentTreeService.GetContentFamily(rootId, testLanguageCode);

            // Assert
            Assert.AreEqual(rootId, result.Id);
            Assert.AreEqual(rootName, result.Text);
            Assert.AreEqual(2, result.Children.Count());
            Assert.AreEqual(childId1, result.Children.First().Id);
            Assert.AreEqual(childName1, result.Children.First().Text);
            Assert.IsTrue(result.Children.First().Children);
            Assert.AreEqual(childId2, result.Children.Last().Id);
            Assert.AreEqual(childName1, result.Children.Last().Text);
            Assert.IsFalse(result.Children.Last().Children);
        }
示例#24
0
        public static void RenderSubNavigation(this HtmlHelper html, ContentReference contentLink = null,
            IContentLoader contentLoader = null)
        {
            contentLink = contentLink ?? html.ViewContext.RequestContext.GetContentLink();
            contentLoader = contentLoader ?? ServiceLocator.Current.GetInstance<IContentLoader>();

            //hitta alla sidor mellan nuvarande sida och start, uppifrån ner

            var path =
                NavigationPath(contentLink, contentLoader, ContentReference.StartPage).Select(x => x.PageLink).ToList();

            //

            var currentPage = contentLoader.Get<IContent>(contentLink) as PageData;

            if (currentPage != null)
            {
                path.Add(currentPage.PageLink);
            }

            var root = path.FirstOrDefault();
            if (root == null)
            {
                return;
            }

            RenderSubNavigationLevel(html, root, path, contentLoader);
        }
        public ActionResult MyAccountMenu(MyAccountPageType id)
        {
            var startPage = _contentLoader.Get <DemoHomePage>(ContentReference.StartPage);

            if (startPage == null)
            {
                return(new EmptyResult());
            }

            var selectedSubNav        = _cookieService.Get(Constant.Fields.SelectedNavSuborganization);
            var organization          = _organizationService.GetCurrentFoundationOrganization();
            var canSeeOrganizationNav = _customerService.CanSeeOrganizationNav();

            var model = new MyAccountNavigationViewModel
            {
                Organization        = canSeeOrganizationNav ? _organizationService.GetOrganizationModel(organization) : null,
                CurrentOrganization = canSeeOrganizationNav ? !string.IsNullOrEmpty(selectedSubNav) ?
                                      _organizationService.GetOrganizationModel(_organizationService.GetSubFoundationOrganizationById(selectedSubNav)) :
                                      _organizationService.GetOrganizationModel(organization) : null,
                CurrentPageType     = id,
                OrganizationPage    = startPage.OrganizationMainPage,
                SubOrganizationPage = startPage.SubOrganizationPage,
                MenuItemCollection  = new LinkItemCollection()
            };

            var menuItems = startPage.ShowCommerceHeaderComponents ? startPage.MyAccountCommerceMenu : startPage.MyAccountCmsMenu;

            if (menuItems == null)
            {
                return(PartialView("_ProfileSidebar", model));
            }
            var wishlist = _contentLoader.Get <WishListPage>(startPage.WishlistPage);

            menuItems = menuItems.CreateWritableClone();

            if (model.Organization != null)
            {
                if (wishlist != null)
                {
                    var url  = wishlist.LinkURL.Contains("?") ? wishlist.LinkURL.Split('?').First() : wishlist.LinkURL;
                    var item = menuItems.FirstOrDefault(x => x.Href.Substring(1).Equals(url));
                    if (item != null)
                    {
                        menuItems.Remove(item);
                    }
                }
                menuItems.Add(new LinkItem
                {
                    Href = _urlResolver.GetUrl(startPage.QuickOrderPage),
                    Text = _localizationService.GetString("/Dashboard/Labels/QuickOrder", "Quick Order")
                });
            }
            else if (organization != null)
            {
                if (wishlist != null)
                {
                    var url  = wishlist.LinkURL.Contains("?") ? wishlist.LinkURL.Split('?').First() : wishlist.LinkURL;
                    var item = menuItems.FirstOrDefault(x => x.Href.Substring(1).Equals(url));
                    if (item != null)
                    {
                        item.Text = _localizationService.GetString("/Dashboard/Labels/OrderPad", "Order Pad");
                    }
                }
            }

            model.MenuItemCollection.AddRange(menuItems);

            if (id == MyAccountPageType.Organization)
            {
                return(PartialView("_ProfileSidebar", model));
            }

            var currentContent = _pageRouteHelper.Page;

            foreach (var menuItem in menuItems)
            {
                if (menuItem.Href != null)
                {
                    var content = UrlResolver.Current.Route(new UrlBuilder(menuItem.Href));
                    if (content == null)
                    {
                        continue;
                    }
                    if (currentContent.ContentLink == content.ContentLink)
                    {
                        model.CurrentPageText = menuItem.Text;
                    }
                }
            }

            return(PartialView("_ProfileSidebar", model));
        }
示例#26
0
        private static IEnumerable<PageData> NavigationPath(ContentReference contentLink, IContentLoader contentLoader,
            ContentReference fromLink = null)
        {
            fromLink = fromLink ?? ContentReference.RootPage;
            var path =
                contentLoader.GetAncestors(contentLink)
                    .Reverse()
                    .SkipWhile(x => ContentReference.IsNullOrEmpty(x.ParentLink) ||
                                    !x.ParentLink.CompareToIgnoreWorkID(ContentReference.StartPage))
                    .OfType<PageData>()
                    .ToList();

            var currentPage = contentLoader.Get<IContent>(contentLink) as PageData;

            if (currentPage != null)
            {
                path.Add(currentPage);
            }
            return path;
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return(null);
            }

            var validationMessage = string.Empty;
            var stringBuilder     = new StringBuilder();
            var allowedTypes      = this.AllowedTypes;
            var restrictedTypes   = this.RestrictedTypes;
            var contentReferences = new List <ContentReference>();

            if (value is ContentArea)
            {
                var contentArea = value as ContentArea;
                contentReferences = contentArea.Items.Select(x => x.ContentLink).ToList();
            }
            else if (value is IEnumerable <ContentReference> )
            {
                var references = value as IEnumerable <ContentReference>;
                contentReferences = references.ToList();
            }
            else if (value is ContentReference)
            {
                var contentReference = value as ContentReference;
                contentReferences.Add(contentReference);
            }

            foreach (var contentReference in contentReferences)
            {
                var content    = _contentLoader.Get <IContent>(contentReference);
                var type       = content.GetOriginalType();
                var interfaces = type.GetInterfaces();

                var injectedAllowedTypesAttribute = InjectedAllowedTypes.GetInjectedAllowedTypesAttribute(validationContext.ObjectInstance.GetOriginalType(),
                                                                                                          validationContext.MemberName);

                if (injectedAllowedTypesAttribute != null)
                {
                    allowedTypes =
                        allowedTypes.Concat(injectedAllowedTypesAttribute.AllowedTypes).Distinct().ToArray();
                    restrictedTypes =
                        restrictedTypes.Concat(injectedAllowedTypesAttribute.RestrictedTypes).Distinct().ToArray();
                }

                if (restrictedTypes.Contains(type) || restrictedTypes.Any(x => interfaces.Any(i => i == x)))
                {
                    var message =
                        string.Format(
                            LocalizationService.Current.GetString("/injectedallowedtypes/errormessages/notallowed"), type.Name, validationContext.MemberName);
                    validationMessage = stringBuilder.Append(message).AppendLine(".").ToString();
                }

                if (!allowedTypes.Contains(type) && !allowedTypes.Any(x => interfaces.Any(i => i == x)))
                {
                    var message =
                        string.Format(
                            LocalizationService.Current.GetString("/injectedallowedtypes/errormessages/notallowed"), type.Name, validationContext.MemberName);
                    validationMessage = stringBuilder.Append(message).AppendLine(".").ToString();
                }
            }

            if (string.IsNullOrEmpty(validationMessage))
            {
                return(null);
            }

            var validationResult = new ValidationResult(validationMessage);

            return(validationResult);
        }
        public async Task <RedirectResult> Index(string orderId, string contactId, string marketId, string cartName)
        {
            var result = await _vippsPaymentService.ProcessAuthorizationAsync(Guid.Parse(contactId), marketId, cartName, orderId);

            //If ProcessAuthorization fails user needs to be redirected back to checkout or product page
            if (!result.Processed)
            {
                //Example method for dealing with different error types and what error message to show
                var errorMessage = GetErrorMessage(result);

                if (result.PaymentType == VippsPaymentType.CHECKOUT)
                {
                    //Redirect to checkout (preferably with error message)
                    return(new RedirectResult("/en/checkout"));
                }

                //Redirect back to product if express checkout (preferably with error message)
                if (result.PaymentType == VippsPaymentType.PRODUCTEXPRESS)
                {
                    var cart            = _vippsService.GetCartByContactId(contactId, marketId, cartName);
                    var item            = cart.GetFirstForm().GetAllLineItems().FirstOrDefault();
                    var itemContentLink = _referenceConverter.GetContentLink(item?.Code);
                    var entryContent    = _contentLoader.Get <EntryContentBase>(itemContentLink);
                    return(new RedirectResult(entryContent.GetUrl()));
                }

                //Redirect to cart page if your website has one
                if (result.PaymentType == VippsPaymentType.CARTEXPRESS)
                {
                    return(new RedirectResult("/"));
                }

                if (result.PaymentType == VippsPaymentType.WISHLISTEXPRESS)
                {
                    return(new RedirectResult("/en/my-pages/wish-list/"));
                }

                if (result.PaymentType == VippsPaymentType.UNKNOWN)
                {
                    return(new RedirectResult("/"));
                }
            }


            //If wishlist payment, delete wishlist as well
            if (result.PaymentType == VippsPaymentType.WISHLISTEXPRESS)
            {
                var wishList = _cartService.LoadCart(_cartService.DefaultWishListName);

                if (wishList != null)
                {
                    _orderRepository.Delete(wishList.OrderLink);
                }
            }

            var queryCollection = new NameValueCollection
            {
                { "contactId", _customerContext.CurrentContactId.ToString() },
                { "orderNumber", result.PurchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.InvariantCulture) }
            };

            return(new RedirectResult(new UrlBuilder("/en/checkout/order-confirmation/")
            {
                QueryCollection = queryCollection
            }.ToString()));
        }
示例#29
0
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: Load the cart
            var cart = _orderRepository.LoadCart <ICart>(GetContactId(), DefaultCart);

            if (cart == null)
            {
                throw new InvalidOperationException("There is no cart exception.");
            }

            // ToDo: Add an OrderAddress
            IOrderAddress theAddress = AddAddressToOrder(cart);

            // ToDo: Define/update Shipping
            AdjustFirstShipmentInOrder(cart, theAddress, model.SelectedShipId);

            // ToDo: Add a Payment to the Order
            AddPaymentToOrder(cart, model.SelectedPayId);

            // ToDo: Add a transaction scope and convert the cart to PO
            IPurchaseOrder purchaseOrder;
            OrderReference orderReference;

            using (var scope = new TransactionScope())
            {
                var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

                // Added - sets a lock on inventory... could come earlier (outside tran) depending on TypeOf-"store"
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.InProgress, (item, issue) => validationIssues.Add(item, issue));

                if (validationIssues.Count >= 1)
                {
                    throw new Exception("Not possible right now"); // ...change approach and fork
                }

                // ECF 10 - void back
                cart.ProcessPayments();
                // ECF 11
                //IEnumerable<PaymentProcessingResult> PaymentProcessingResult = cart.ProcessPayments();
                //var xyz = PaymentProcessingResult.First().IsSuccessful;

                // just looking around - (nice extension methods)
                var cartTotal    = cart.GetTotal();
                var handling     = cart.GetHandlingTotal(); // OG-Calculator... aggregate on "all forms"
                var form         = cart.GetFirstForm();     //
                var formHandling = form.HandlingTotal;      // "handling" sits here on OF

                /* orderGroupCalculator does:
                 * - Catches up with the "IOrderFormCalculator"
                 * - GetSubTotal - Form-Calculator does
                 * - GetHandlingTotal - Form-Calc does
                 * - GetShippingCost - Form-Calc. does with ShippingCalc. - "processes" the shipment
                 * - GetTaxTotal - FormCalc. does with Tax-Calc.
                 */

                var totalProcessedAmount = cart.GetFirstForm().Payments.Where
                                               (x => x.Status.Equals(PaymentStatus.Processed.ToString())).Sum(x => x.Amount);

                // could do more than this, but we just processed payment(s)
                if (totalProcessedAmount != cart.GetTotal(_orderGroupCalculator).Amount)
                {
                    // ...we're not happy, put back the reserved request
                    _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                        , OrderStatus.Cancelled, (item, issue) => validationIssues.Add(item, issue));

                    #region OldSchool Inventory check
                    //List<InventoryRequestItem> requestItems = new List<InventoryRequestItem>(); // holds the "items"
                    //InventoryRequestItem requestItem = new InventoryRequestItem();

                    //// calls for some logic
                    //requestItem.RequestType = InventoryRequestType.Cancel; // as a demo
                    //requestItem.OperationKey = reqKey;

                    //requestItems.Add(requestItem);

                    //InventoryRequest inventoryRequest = new InventoryRequest(DateTime.UtcNow, requestItems, null);
                    //InventoryResponse inventoryResponse = _invService.Service.Request(inventoryRequest);
                    //InventoryRecord rec4 = _invService.Service.Get(LI.Code, wh.Code);
                    #endregion OldSchool

                    throw new InvalidOperationException("Wrong amount"); // maybe change approach
                }

                // we're happy
                // ...could do this here - look at dhe different statuses
                cart.GetFirstShipment().OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

                // decrement inventory and let it go
                _inventoryProcessor.AdjustInventoryOrRemoveLineItem(cart.GetFirstShipment()
                                                                    , OrderStatus.Completed, (item, issue) => validationIssues.Add(item, issue));

                #region OldSchool Inventory check
                //List<InventoryRequestItem> requestItems1 = new List<InventoryRequestItem>(); // holds the "items"
                //InventoryRequestItem requestItem1 = new InventoryRequestItem();

                //// calls for some logic
                //requestItem1.RequestType = InventoryRequestType.Complete; // as a demo
                //requestItem1.OperationKey = reqKey;

                //requestItems1.Add(requestItem1);

                //InventoryRequest inventoryRequest1 = new InventoryRequest(DateTime.UtcNow, requestItems1, null);
                //InventoryResponse inventoryResponse1 = _invService.Service.Request(inventoryRequest1);
                #endregion OldSchool

                // we're even happier
                orderReference = _orderRepository.SaveAsPurchaseOrder(cart);
                _orderRepository.Delete(cart.OrderLink);

                scope.Complete();
            } // End TransactionScope

            // ToDo: Housekeeping (Statuses for Shipping and PO, OrderNotes and save the order)
            purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId);
            //_orderRepository.Load<IPurchaseOrder>()

            // check the below
            var theType  = purchaseOrder.OrderLink.OrderType;
            var toString = purchaseOrder.OrderLink.ToString(); // Gets ID and Type ... combined

            #region ThisAndThat
            // should/could do some with OrderStatusManager, slightly old-school
            // OrderStatusManager.

            OrderStatus poStatus;
            poStatus = purchaseOrder.OrderStatus;
            //purchaseOrder.OrderStatus = OrderStatus.InProgress;

            //var info = OrderStatusManager.GetPurchaseOrderStatus(PO); // old-school
            //PO.Status = OrderStatus.InProgress.ToString();

            var shipment = purchaseOrder.GetFirstShipment();
            var status   = shipment.OrderShipmentStatus;

            //shipment. ... no that much to do
            //shipment.OrderShipmentStatus = OrderShipmentStatus.InventoryAssigned;

            // Don't use OrderNoteManager ... it doesn't see the "new" stuff
            var notes = purchaseOrder.Notes;                               // IOrderNote is 0

            Mediachase.Commerce.Orders.OrderNote otherNote = new OrderNote //IOrderNote
            {
                // Created = DateTime.Now, // do we need to set this ?? Nope .ctor does
                CustomerId = new Guid(), // can set this - regarded
                Detail     = "Order ToString(): " + toString + " - Shipment tracking number: " + shipment.ShipmentTrackingNumber,
                LineItemId = purchaseOrder.GetAllLineItems().First().LineItemId,
                // OrderGroupId = 12, R/O - error
                // OrderNoteId = 12, // can define it, but it's disregarded - no error
                Title = "Some title",
                Type  = OrderNoteTypes.Custom.ToString()
            };

            // not intended to be used, as it's "Internal"
            //IOrderNote theNote = new EPiServer.Commerce.Order.Internal.SerializableNote();

            purchaseOrder.Notes.Add(otherNote); // void back
            purchaseOrder.ExpirationDate = DateTime.Now.AddMonths(1);

            // ...need to come after adding notes
            _orderRepository.Save(purchaseOrder);

            #endregion

            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            // the below is a dummy, change to "PO".OrderNumber when done
            //string passingValue = String.Empty;
            string passingValue = purchaseOrder.OrderNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
示例#30
0
 private void ContentSecuritySaved(object sender, ContentSecurityEventArg e)
 {
     _htmlCache.ContentChanged(e.ContentLink);
     _htmlCache.ChildrenListingChanged(_contentLoader.Get <IContent>(e.ContentLink).ParentLink);
 }
        public THeaderViewModel CreateHeaderViewModel <THeaderViewModel>(IContent currentContent, CmsHomePage homePage)
            where THeaderViewModel : HeaderViewModel, new()
        {
            var menuItems = new List <MenuItemViewModel>();

            menuItems = homePage.MainMenu?.FilteredItems.Select(x =>
            {
                var itemCached = CacheManager.Get(x.ContentLink.ID + MenuCacheKey) as MenuItemViewModel;
                if (itemCached != null && !PageEditing.PageIsInEditMode)
                {
                    return(itemCached);
                }
                else
                {
                    var content = _contentLoader.Get <IContent>(x.ContentLink);
                    MenuItemBlock _;
                    MenuItemViewModel menuItem;
                    if (content is MenuItemBlock)
                    {
                        _        = content as MenuItemBlock;
                        menuItem = new MenuItemViewModel
                        {
                            Name       = _.Name,
                            ButtonText = _.ButtonText,
                            TeaserText = _.TeaserText,
                            Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                            {
                                ContextMode = ContextMode.Default
                            }),
                            ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                            ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                            ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                        };
                    }
                    else
                    {
                        menuItem = new MenuItemViewModel
                        {
                            Name       = content.Name,
                            Uri        = _urlResolver.GetUrl(content.ContentLink),
                            ChildLinks = new List <GroupLinkCollection>()
                        };
                    }

                    if (!PageEditing.PageIsInEditMode)
                    {
                        var keyDependency = new List <string>();
                        keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems)
                        keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink));

                        var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                        CacheManager.Insert(x.ContentLink.ID + MenuCacheKey, menuItem, eviction);
                    }
                    return(menuItem);
                }
            }).ToList();


            return(new THeaderViewModel
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = PrincipalInfo.Current.Name,
                MenuItems = menuItems,
                MobileNavigation = homePage.MobileNavigationPages,
            });
        }
示例#32
0
        public async Task <ActionResult> Index(Cms.Pages.TagPage currentPage)
        {
            await _trackingService.PageViewed(HttpContext, currentPage);

            var model = new TagsViewModel(currentPage)
            {
                Continent = ControllerContext.RequestContext.GetCustomRouteData <string>("Continent")
            };

            var addcat = ControllerContext.RequestContext.GetCustomRouteData <string>("Category");

            if (addcat != null)
            {
                model.AdditionalCategories = addcat.Split(',');
            }

            var carousel = new CarouselViewModel
            {
                Items = new List <CarouselItemBlock>()
            };


            if (currentPage.Images != null)
            {
                foreach (var img in currentPage.Images.FilteredItems.Select(ci => ci.ContentLink))
                {
                    var t = _contentLoader.Get <ImageMediaData>(img).Title;
                    carousel.Items.Add(new CarouselItemBlock {
                        Image = img, Heading = t
                    });
                }
            }
            var q = SearchClient.Instance.Search <Find.Cms.Models.Pages.LocationItemPage>()
                    .Filter(f => f.TagString().Match(currentPage.Name));

            if (model.AdditionalCategories != null)
            {
                q = model.AdditionalCategories.Aggregate(q, (current, c) => current.Filter(f => f.TagString().Match(c)));
            }
            if (model.Continent != null)
            {
                q = q.Filter(dp => dp.Continent.MatchCaseInsensitive(model.Continent));
            }
            var res = q.StaticallyCacheFor(new System.TimeSpan(0, 1, 0)).GetContentResult();

            model.Locations = res.ToList();

            //Add theme images from results
            foreach (var d in model.Locations)
            {
                carousel.Items.Add(new CarouselItemBlock
                {
                    Image   = d.Image,
                    Heading = d.Name,
                });
            }

            model.Carousel = carousel;

            return(View(model));
        }
示例#33
0
        private void InitializeLoginViewModel(InternalLoginViewModel viewModel)
        {
            StartPage startPage = _contentLoader.Get <StartPage>(ContentReference.StartPage);

            viewModel.ResetPasswordPage = startPage.ResetPasswordPage;
        }
        public async Task <ActionResult> AddToCart(RequestParamsToCart param)
        {
            var warningMessage = string.Empty;

            ModelState.Clear();

            if (CartWithValidationIssues.Cart == null)
            {
                _cart = new CartWithValidationIssues
                {
                    Cart             = _cartService.LoadOrCreateCart(_cartService.DefaultCartName),
                    ValidationIssues = new Dictionary <ILineItem, List <ValidationIssue> >()
                };
            }

            var result = _cartService.AddToCart(CartWithValidationIssues.Cart, param.Code, param.Quantity, param.Store, param.SelectedStore);

            if (result.EntriesAddedToCart)
            {
                _orderRepository.Save(CartWithValidationIssues.Cart);
                await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

                if (string.Equals(param.RequestFrom, "axios", StringComparison.OrdinalIgnoreCase))
                {
                    var product   = "";
                    var entryLink = _referenceConverter.GetContentLink(param.Code);
                    var entry     = _contentLoader.Get <EntryContentBase>(entryLink);
                    if (entry is BundleContent || entry is PackageContent)
                    {
                        product = entry.DisplayName;
                    }
                    else
                    {
                        var parentProduct = _contentLoader.Get <EntryContentBase>(entry.GetParentProducts().FirstOrDefault());
                        product = parentProduct?.DisplayName;
                    }

                    if (result.ValidationMessages.Count > 0)
                    {
                        return(Json(new ChangeCartJsonResult
                        {
                            StatusCode = 1,
                            CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                            Message = product + " is added to the cart successfully.\n" + result.GetComposedValidationMessage(),
                            SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
                        }));
                    }

                    return(Json(new ChangeCartJsonResult
                    {
                        StatusCode = 1,
                        CountItems = (int)CartWithValidationIssues.Cart.GetAllLineItems().Sum(x => x.Quantity),
                        Message = product + " is added to the cart successfully.",
                        SubTotal = CartWithValidationIssues.Cart.GetSubTotal()
                    }));
                }

                return(MiniCartDetails());
            }

            return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
        }
示例#35
0
        protected virtual T CreateViewModel <T>(IContent currentContent, CommerceHomePage homePage, Customer.FoundationContact contact, bool isBookmarked)
            where T : CommerceHeaderViewModel, new()
        {
            var menuItems    = new List <MenuItemViewModel>();
            var homeLanguage = homePage.Language.DisplayName;

            menuItems = homePage.MainMenu?.FilteredItems.Select(x =>
            {
                var itemCached = CacheManager.Get(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems) as MenuItemViewModel;
                if (itemCached != null && !PageEditing.PageIsInEditMode)
                {
                    return(itemCached);
                }
                else
                {
                    var content = _contentLoader.Get <IContent>(x.ContentLink);
                    MenuItemBlock _;
                    MenuItemViewModel menuItem;
                    if (content is MenuItemBlock)
                    {
                        _        = content as MenuItemBlock;
                        menuItem = new MenuItemViewModel
                        {
                            Name       = _.Name,
                            ButtonText = _.ButtonText,
                            TeaserText = _.TeaserText,
                            Uri        = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments()
                            {
                                ContextMode = ContextMode.Default
                            }),
                            ImageUrl   = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "",
                            ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery,
                            ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>()
                        };
                    }
                    else
                    {
                        menuItem = new MenuItemViewModel
                        {
                            Name       = content.Name,
                            Uri        = _urlResolver.GetUrl(content.ContentLink),
                            ChildLinks = new List <GroupLinkCollection>()
                        };
                    }

                    if (!PageEditing.PageIsInEditMode)
                    {
                        var keyDependency = new List <string>();
                        keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems)
                        keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink));

                        var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency);
                        CacheManager.Insert(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems, menuItem, eviction);
                    }

                    return(menuItem);
                }
            }).ToList();

            return(new T
            {
                HomePage = homePage,
                CurrentContentLink = currentContent?.ContentLink,
                CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty,
                UserLinks = new LinkItemCollection(),
                Name = contact?.FirstName ?? "",
                IsBookmarked = isBookmarked,
                IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly,
                MenuItems = menuItems ?? new List <MenuItemViewModel>(),
                LoginViewModel = new LoginViewModel
                {
                    ResetPasswordPage = homePage.ResetPasswordPage
                },
                RegisterAccountViewModel = new RegisterAccountViewModel
                {
                    Address = new AddressModel()
                },
            });
        }
示例#36
0
 private static void SetAdditionalContextValuesForContent(this UrlHelper urlHelper, PageReference pageLink, RouteValueDictionary values, IContentLoader contentQueryable, IPermanentLinkMapper permanentLinkMapper, LanguageSelectorFactory languageSelectorFactory)
 {
     bool IdKeep = HttpContext.Current.Request.QueryString["idkeep"] != null;
     contentQueryable = contentQueryable ?? ServiceLocator.Current.GetInstance<IContentLoader>();
     permanentLinkMapper = permanentLinkMapper ?? ServiceLocator.Current.GetInstance<IPermanentLinkMapper>();
     languageSelectorFactory = languageSelectorFactory ?? ServiceLocator.Current.GetInstance<LanguageSelectorFactory>();
     IContent content = contentQueryable.Get<IContent>(pageLink, languageSelectorFactory.Fallback(values[RoutingConstants.LanguageKey] as string ?? ContentLanguage.PreferredCulture.Name, true));
     if (content == null)
         return;
     if (IdKeep)
         values["id"] = (object)content.ContentLink.ToString();
     UrlExtensions.SetAdditionalContextValuesForPage(values, IdKeep, content);
 }