Exemplo n.º 1
0
        public ActionResult AddToCart(ShirtVariation currentContent, decimal Quantity, string Monogram)
        {
            // LoadOrCreateCart - in EPiServer.Commerce.Order.IOrderRepositoryExtensions
            var cart = _orderRepository.LoadOrCreateCart <ICart>(
                PrincipalInfo.CurrentPrincipal.GetContactId(), "Default");

            //cart.  // ...have a look at all the extension methods

            string code = currentContent.Code;

            // Manually checking - could have a look at the InventoryRecord - properties
            // ...could be part of an optional lab in Fund
            IWarehouse      wh  = _whRep.GetDefaultWarehouse();
            InventoryRecord rec = _invService.Get(code, wh.Code);


            // ... can get: Sequence contains more than one matching element...
            // ...when we have two different lineitems for the same SKU
            // Use when the cart is empty/one LI for SKU with Qty --> no crash
            var lineItem = cart.GetAllLineItems().SingleOrDefault(x => x.Code == code);

            //currentContent.IsAvailableInCurrentMarket();

            // Below works for the same SKU on different LineItems... Changing back for the Fund
            //var lineItem = cart.GetAllLineItems().First(x => x.Code == code); // Changed to this for multiple LI with the same code - crash if no cart

            // ECF 12 changes - market.MarketId
            IMarket market = _currentMarket.GetCurrentMarket();

            if (lineItem == null)
            {
                lineItem          = _orderFactory.CreateLineItem(code, cart);
                lineItem.Quantity = Quantity; // gets this as an argument for the method

                // ECF 12 changes - market.MarketId
                _placedPriceProcessor.UpdatePlacedPrice
                    (lineItem, GetContact(), market.MarketId, cart.Currency,
                    (lineItemToValidate, validation) => { }); // does not take care of the messages here

                cart.AddLineItem(lineItem);
            }
            else
            {
                // Qty increases ... no new LineItem ...
                // original for Fund.
                lineItem.Quantity += Quantity; // need an update
                // maybe do price validation here too
            }

            // Validations
            var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

            // ECF 12 changes - market.MarketId
            // RoCe - This needs to be updated to get the message out + Lab-steps added...
            var validLineItem = _lineItemValidator.Validate(lineItem, market.MarketId, (item, issue) => { });

            cart.ValidateOrRemoveLineItems((item, issue) => validationIssues.Add(item, issue), _lineItemValidator);
            //var someIssue = validationIssues.First().Value;

            if (validLineItem) // We're happy
            {
                // If MDP - error when adding, may need to reset IIS as the model has changed
                //    when adding/removing the MetaField in CM
                lineItem.Properties["Monogram"] = Monogram;

                _orderRepository.Save(cart);
            }

            ContentReference cartRef     = _contentLoader.Get <StartPage>(ContentReference.StartPage).Settings.CartPage;
            ContentReference cartPageRef = EPiServer.Web.SiteDefinition.Current.StartPage;
            CartPage         cartPage    = _contentLoader.Get <CartPage>(cartRef);
            var name = cartPage.Name;
            var lang = ContentLanguage.PreferredCulture;

            string passingValue = cart.Name; // if something is needed

            //return RedirectToAction("Index", new { node = theRef, passedAlong = passingValue }); // Doesn't work
            return(RedirectToAction("Index", lang + "/" + name, new { passedAlong = passingValue })); // Works
        }
Exemplo n.º 2
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 viewModel = new TViewModel();
            var market    = _currentMarket.GetCurrentMarket();
            var currency  = _currencyservice.GetCurrentCurrency();
            var variants  = GetVariants <TVariant, TProduct>(currentContent)
                            .Where(v => v.Prices().Any(x => x.MarketId == _currentMarket.GetCurrentMarket().MarketId))
                            .ToList();
            var variantsState = GetVarantsState(variants, market);

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

            variationCode = string.IsNullOrEmpty(variationCode) ? variants.FirstOrDefault()?.Code : variationCode;
            var isInstock        = true;
            var currentWarehouse = _warehouseRepository.GetDefaultWarehouse();

            if (!string.IsNullOrEmpty(variationCode))
            {
                var inStockQuantity = GetAvailableStockQuantity(variant, currentWarehouse);
                isInstock = inStockQuantity > 0;
                viewModel.InStockQuantity = inStockQuantity;
            }

            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");

            viewModel.CurrentContent    = currentContent;
            viewModel.Product           = currentContent;
            viewModel.Variant           = variant;
            viewModel.ListingPrice      = defaultPrice?.UnitPrice ?? new Money(0, currency);
            viewModel.DiscountedPrice   = discountedPrice;
            viewModel.SubscriptionPrice = subscriptionPrice?.UnitPrice ?? new Money(0, currency);
            viewModel.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();
            viewModel.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,
                Disabled = !variantsState.FirstOrDefault(v => v.Key == x.Code).Value
            }).ToList();
            viewModel.Color       = baseVariant?.Color;
            viewModel.Size        = baseVariant?.Size;
            viewModel.Images      = variant.GetAssets <IContentImage>(_contentLoader, _urlResolver);
            viewModel.Media       = variant.GetAssetsWithType(_contentLoader, _urlResolver);
            viewModel.IsAvailable = _databaseMode.DatabaseMode != DatabaseMode.ReadOnly && defaultPrice != null && isInstock;
            viewModel.Stores      = new StoreViewModel
            {
                Stores            = _storeService.GetEntryStoresViewModels(variant.Code),
                SelectedStore     = currentStore != null ? currentStore.Code : "",
                SelectedStoreName = currentStore != null ? currentStore.Name : ""
            };
            viewModel.StaticAssociations = associations;
            viewModel.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,
                    Name = x.Name,
                    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();
            viewModel.HasOrganization     = contact?.OwnerId != null;
            viewModel.ShowRecommendations = productRecommendations?.ShowRecommendations ?? true;
            viewModel.IsSalesRep          = isSalesRep;
            viewModel.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>();
            viewModel.Documents = currentContent.CommerceMediaCollection
                                  .Where(o => o.AssetType.Equals(typeof(PdfFile).FullName.ToLowerInvariant()) || o.AssetType.Equals(typeof(StandardFile).FullName.ToLowerInvariant()))
                                  .Select(x => _contentLoader.Get <MediaData>(x.AssetLink)).ToList();
            viewModel.MinQuantity = (int)defaultPrice.MinQuantity;
            viewModel.HasSaleCode = defaultPrice != null ? !string.IsNullOrEmpty(defaultPrice.CustomerPricing.PriceCode) : false;

            return(viewModel);
        }
 public InventoryRecord GetForDefaultWarehouse(string code)
 {
     return(_inventoryService.Get(code, _warehouseRepository.GetDefaultWarehouse().Code));
 }