private Dictionary <ILineItem, List <ValidationIssue> > UpdateLineItemSku(ICart cart, int shipmentId, string oldCode, string newCode, decimal quantity)
        {
            RemoveLineItem(cart, shipmentId, oldCode);

            //merge same sku's
            var newLineItem = GetFirstLineItem(cart, newCode);

            if (newLineItem != null)
            {
                var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId || shipmentId == 0);
                cart.UpdateLineItemQuantity(shipment, newLineItem, newLineItem.Quantity + quantity);
            }
            else
            {
                newLineItem          = cart.CreateLineItem(newCode, _orderGroupFactory);
                newLineItem.Quantity = quantity;
                cart.AddLineItem(newLineItem, _orderGroupFactory);

                var price = PriceCalculationService.GetSalePrice(newCode, cart.MarketId, _currentMarket.GetCurrentMarket().DefaultCurrency);
                if (price != null)
                {
                    newLineItem.PlacedPrice = price.UnitPrice.Amount;
                }
            }

            return(ValidateCart(cart));
        }
Пример #2
0
        /// <summary>
        /// Get variants state of the product (is available or not)
        /// </summary>
        /// <typeparam name="TVariant">inherited VariationContent</typeparam>
        /// <param name="variants">List variants of the product</param>
        /// <param name="market">the market.</param>
        /// <returns>Dictionary with Key is the Variant Code and Value is IsAvailable or not</returns>
        private Dictionary <string, bool> GetVarantsState <TVariant>(List <TVariant> variants, IMarket market) where TVariant : VariationContent
        {
            var results = new Dictionary <string, bool>();

            foreach (var v in variants)
            {
                var available = _databaseMode.DatabaseMode != DatabaseMode.ReadOnly;
                if (!available)
                {
                    results.Add(v.Code, available);
                    continue;
                }

                var price = PriceCalculationService.GetSalePrice(v.Code, market.MarketId, market.DefaultCurrency);
                if (price == null)
                {
                    results.Add(v.Code, false);
                    continue;
                }

                if (!v.TrackInventory)
                {
                    results.Add(v.Code, true);
                    continue;
                }

                var currentWarehouse = _warehouseRepository.GetDefaultWarehouse();
                var inventoryRecord  = _inventoryService.Get(v.Code, currentWarehouse.Code);
                var inventory        = new Inventory(inventoryRecord);
                available = inventory.IsTracked && inventory.InStockQuantity == 0 ? false : true;
                results.Add(v.Code, available);
            }

            return(results);
        }
        public async Task GetAll_VegetableControllerTesting()
        {
            //Arrange
            var mockMapper = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });
            IMapper mapper                  = mockMapper.CreateMapper();
            var     discountService         = new DiscountService();
            var     priceCalculationService = new PriceCalculationService(discountService, mapper);
            var     repository              = new Mock <IGenericRepository <Vegetable> >();

            repository.Setup(r => r.GetAll()).ReturnsAsync(new List <Vegetable>()
            {
                new Vegetable()
                {
                    Price = 4M
                }
            });
            var serviceBuyItem       = new BuyItemService <Vegetable>(mapper, repository.Object, priceCalculationService);
            var vegetablesController = new VegetablesController(mapper, repository.Object, serviceBuyItem);

            //Act
            var result = vegetablesController.GetAll();

            //Assert
            result.Should().NotBeNull();
        }
Пример #4
0
 public RequestGroupController(
     TolkDbContext dbContext,
     IAuthorizationService authorizationService,
     RequestService requestService,
     ISwedishClock clock,
     ILogger <OrderController> logger,
     IOptions <TolkOptions> options,
     InterpreterService interpreterService,
     PriceCalculationService priceCalculationService,
     OrderService orderService,
     ListToModelService listToModelService,
     CacheService cacheService)
 {
     _dbContext            = dbContext;
     _authorizationService = authorizationService;
     _requestService       = requestService;
     _clock                   = clock;
     _logger                  = logger;
     _options                 = options.Value;
     _interpreterService      = interpreterService;
     _priceCalculationService = priceCalculationService;
     _cacheService            = cacheService;
     _orderService            = orderService;
     _listToModelService      = listToModelService;
 }
Пример #5
0
        public TestServiceProvider()
        {
            LocalizationService = new Mock<ILocalizationService>();
            GenericAttributeService = new Mock<IGenericAttributeService>();
            WorkContext = new Mock<IWorkContext>();
            
            PriceCalculationService = new PriceCalculationService(new CatalogSettings(), new CurrencySettings(), 
                new Mock<ICategoryService>().Object, new Mock<ICurrencyService>().Object, new Mock<IDiscountService>().Object,
                new Mock<IManufacturerService>().Object, new Mock<IProductAttributeParser>().Object,
                new Mock<IProductService>().Object, new MemoryCacheManager(new Mock<IMemoryCache>().Object), new Mock<IStoreContext>().Object, WorkContext.Object, new ShoppingCartSettings());

            LocalizationService.Setup(l => l.GetResource(It.IsAny<string>())).Returns("Invalid");
            WorkContext.Setup(p => p.WorkingLanguage).Returns(new Language {Id = 1});
            WorkContext.Setup(w => w.WorkingCurrency).Returns(new Currency { RoundingType = RoundingType.Rounding001 });

            CurrencyService = new Mock<ICurrencyService>();
            CurrencyService.Setup(x => x.GetCurrencyById(1, true)).Returns(new Currency {Id = 1, RoundingTypeId = 0});

            GenericAttributeService.Setup(p => p.GetAttribute<bool>(It.IsAny<Customer>(), "product-advanced-mode", It.IsAny<int>()))
                .Returns(true);

            GenericAttributeService.Setup(p => p.GetAttribute<bool>(It.IsAny<Customer>(), "manufacturer-advanced-mode", It.IsAny<int>()))
                .Returns(true);

            GenericAttributeService.Setup(p => p.GetAttribute<bool>(It.IsAny<Customer>(), "category-advanced-mode", It.IsAny<int>()))
                .Returns(true);
        }
Пример #6
0
        public async Task <ActionResult> Subscription(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);

            if (result.EntriesAddedToCart)
            {
                var item = CartWithValidationIssues.Cart.GetAllLineItems().FirstOrDefault(x => x.Code.Equals(param.Code));
                var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(param.Code, CartWithValidationIssues.Cart.MarketId, CartWithValidationIssues.Cart.Currency);
                if (subscriptionPrice != null)
                {
                    item.Properties["SubscriptionPrice"] = subscriptionPrice.UnitPrice.Amount;
                    item.PlacedPrice = subscriptionPrice.UnitPrice.Amount;
                }

                _orderRepository.Save(CartWithValidationIssues.Cart);
                await _recommendationService.TrackCart(HttpContext, CartWithValidationIssues.Cart);

                return(MiniCartDetails());
            }

            return(new HttpStatusCodeResult(500, result.GetComposedValidationMessage()));
        }
 public RetailCalculatorService(
     PriceCalculationService calculator,
     DiscountCalculationService discountCalculator,
     TaxCalculationService taxCalculator)
 {
     Calculator         = calculator;
     DiscountCalculator = discountCalculator;
     TaxCalculator      = taxCalculator;
 }
 public ConfigurationController(PriceCalculationService priceCalculationService, UpdateService updateService, OrderService orderService, KonfiguratorDbContext dbContext,
                                EmailService emailService, ViewModelService viewModelService)
 {
     _viewModelService        = viewModelService;
     _emailService            = emailService;
     _priceCalculationService = priceCalculationService;
     _dbContext     = dbContext;
     _orderService  = orderService;
     _updateService = updateService;
 }
Пример #9
0
 private PriceInformationModel GetPriceinformationOrderToDisplay(Request request, List <CompetenceAndSpecialistLevel> requestedCompetenceLevels)
 {
     return(new PriceInformationModel
     {
         MealBreakIsNotDetucted = request.Order.MealBreakIncluded ?? false,
         PriceInformationToDisplay = PriceCalculationService.GetPriceInformationToDisplay(
             _priceCalculationService.GetPrices(request, OrderService.SelectCompetenceLevelForPriceEstimation(requestedCompetenceLevels), null).PriceRows),
         Header = "Beräknat pris enligt bokningsförfrågan",
         UseDisplayHideInfo = true
     });
 }
Пример #10
0
        public void CalculatePrice()
        {
            var expected = 4f;
            var sut      = new PriceCalculationService();
            var purchase = new PurchaseEntity
            {
                Count = 2,
                Price = 2
            };

            Assert.Equal(expected, sut.CalculcateTotal(purchase));
        }
        public virtual TViewModel CreateVariant <TVariant, TViewModel>(TVariant currentContent)
            where TVariant : VariationContent
            where TViewModel : EntryViewModelBase <TVariant>, new()
        {
            var market            = _currentMarket.GetCurrentMarket();
            var currency          = _currencyservice.GetCurrentCurrency();
            var defaultPrice      = PriceCalculationService.GetSalePrice(currentContent.Code, market.MarketId, currency);
            var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(currentContent.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 productRecommendations = currentContent as IProductRecommendations;
            var isSalesRep             = PrincipalInfo.CurrentPrincipal.IsInRole("SalesRep");
            var currentWarehouse       = _warehouseRepository.GetDefaultWarehouse();

            var isInstock = true;

            if (currentContent.TrackInventory)
            {
                var inventoryRecord = _inventoryService.Get(currentContent.Code, currentWarehouse.Code);
                var inventory       = new Inventory(inventoryRecord);
                isInstock = inventory.IsTracked && inventory.InStockQuantity == 0 ? false : isInstock;
            }

            return(new TViewModel
            {
                CurrentContent = currentContent,
                ListingPrice = defaultPrice?.UnitPrice ?? new Money(0, currency),
                DiscountedPrice = discountedPrice,
                SubscriptionPrice = subscriptionPrice?.UnitPrice ?? new Money(0, currency),
                Images = currentContent.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                Media = currentContent.GetAssetsWithType(_contentLoader, _urlResolver),
                IsAvailable = _databaseMode.DatabaseMode != DatabaseMode.ReadOnly && defaultPrice != null && isInstock,
                Stores = new StoreViewModel
                {
                    Stores = _storeService.GetEntryStoresViewModels(currentContent.Code),
                    SelectedStore = currentStore != null ? currentStore.Code : "",
                    SelectedStoreName = currentStore != null ? currentStore.Name : ""
                },
                StaticAssociations = associations,
                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>(),
                MinQuantity = (int)defaultPrice.MinQuantity,
                HasSaleCode = defaultPrice != null ? !string.IsNullOrEmpty(defaultPrice.CustomerPricing.PriceCode) : false
            });
        }
Пример #12
0
        public virtual TViewModel CreatePackage <TPackage, TVariant, TViewModel>(TPackage currentContent)
            where TPackage : PackageContent
            where TVariant : VariationContent
            where TViewModel : PackageViewModelBase <TPackage>, new()
        {
            var viewModel         = new TViewModel();
            var variants          = GetVariants <TVariant, TPackage>(currentContent).Where(x => x.Prices().Where(p => p.UnitPrice > 0).Any()).ToList();
            var entries           = GetEntriesRelation(currentContent);
            var market            = _currentMarket.GetCurrentMarket();
            var currency          = _currencyservice.GetCurrentCurrency();
            var defaultPrice      = PriceCalculationService.GetSalePrice(currentContent.Code, market.MarketId, currency);
            var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(currentContent.Code, market.MarketId, 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 productRecommendations = currentContent as IProductRecommendations;
            var isSalesRep             = PrincipalInfo.CurrentPrincipal.IsInRole("SalesRep");
            var currentWarehouse       = _warehouseRepository.GetDefaultWarehouse();
            var inStockQuantity        = GetAvailableStockQuantity(currentContent, currentWarehouse);
            var isInstock = inStockQuantity > 0;

            viewModel.InStockQuantity   = inStockQuantity;
            viewModel.CurrentContent    = currentContent;
            viewModel.Package           = currentContent;
            viewModel.ListingPrice      = defaultPrice?.UnitPrice ?? new Money(0, currency);
            viewModel.DiscountedPrice   = GetDiscountPrice(defaultPrice, market, currency);
            viewModel.SubscriptionPrice = subscriptionPrice?.UnitPrice ?? new Money(0, currency);
            viewModel.Images            = currentContent.GetAssets <IContentImage>(_contentLoader, _urlResolver);
            viewModel.Media             = currentContent.GetAssetsWithType(_contentLoader, _urlResolver);
            viewModel.IsAvailable       = _databaseMode.DatabaseMode != DatabaseMode.ReadOnly && defaultPrice != null && isInstock;
            viewModel.Entries           = variants;
            viewModel.EntriesRelation   = entries;
            //Reviews = GetReviews(currentContent.Code);
            viewModel.Stores = new StoreViewModel
            {
                Stores            = _storeService.GetEntryStoresViewModels(currentContent.Code),
                SelectedStore     = currentStore != null ? currentStore.Code : "",
                SelectedStoreName = currentStore != null ? currentStore.Name : ""
            };
            viewModel.StaticAssociations  = associations;
            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.MinQuantity = defaultPrice != null ? (int)defaultPrice.MinQuantity : 0;
            viewModel.HasSaleCode = defaultPrice != null ? !string.IsNullOrEmpty(defaultPrice.CustomerPricing.PriceCode) : false;

            return(viewModel);
        }
Пример #13
0
        public decimal GetProductPrice(Product product, Currency currency)
        {
            decimal priceBase = PriceCalculationService.GetPreselectedPrice(product);

            if (BaseSettings.ConvertNetToGrossPrices)
            {
                decimal taxRate;
                priceBase = TaxService.GetProductPrice(product, priceBase, true, WorkContext.CurrentCustomer, out taxRate);
            }

            decimal price = ConvertFromStoreCurrency(priceBase, currency);

            return(price);
        }
Пример #14
0
 public ApiOrderService(
     TolkDbContext dbContext,
     ApiUserService apiUserService,
     ISwedishClock timeService,
     ILogger <ApiOrderService> logger,
     CacheService cacheService,
     PriceCalculationService priceCalculationService
     )
 {
     _dbContext               = dbContext;
     _apiUserService          = apiUserService;
     _timeService             = timeService;
     _logger                  = logger;
     _cacheService            = cacheService;
     _priceCalculationService = priceCalculationService;
 }
        public void SetCartCurrency(ICart cart, Currency currency)
        {
            if (currency.IsEmpty || currency == cart.Currency)
            {
                return;
            }

            cart.Currency = currency;
            foreach (var lineItem in cart.GetAllLineItems())
            {
                // If there is an item which has no price in the new currency, a NullReference exception will be thrown.
                // Mixing currencies in cart is not allowed.
                // It's up to site's managers to ensure that all items have prices in allowed currency.
                lineItem.PlacedPrice = PriceCalculationService.GetSalePrice(lineItem.Code, cart.MarketId, currency).UnitPrice.Amount;
            }

            ValidateCart(cart);
        }
Пример #16
0
        public virtual TViewModel CreatePackage <TPackage, TVariant, TViewModel>(TPackage currentContent)
            where TPackage : PackageContent
            where TVariant : VariationContent
            where TViewModel : PackageViewModelBase <TPackage>, new()
        {
            var variants          = GetVariants <TVariant, TPackage>(currentContent).ToList();
            var market            = _currentMarket.GetCurrentMarket();
            var currency          = _currencyservice.GetCurrentCurrency();
            var defaultPrice      = PriceCalculationService.GetSalePrice(currentContent.Code, market.MarketId, currency);
            var subscriptionPrice = PriceCalculationService.GetSubscriptionPrice(currentContent.Code, market.MarketId, 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 productRecommendations = currentContent as IProductRecommendations;
            var isSalesRep             = PrincipalInfo.CurrentPrincipal.IsInRole("SalesRep");

            return(new TViewModel
            {
                CurrentContent = currentContent,
                Package = currentContent,
                ListingPrice = defaultPrice?.UnitPrice ?? new Money(0, currency),
                DiscountedPrice = GetDiscountPrice(defaultPrice, market, currency),
                SubscriptionPrice = subscriptionPrice?.UnitPrice ?? new Money(0, currency),
                Images = currentContent.GetAssets <IContentImage>(_contentLoader, _urlResolver),
                IsAvailable = defaultPrice != null,
                Entries = variants,
                //Reviews = GetReviews(currentContent.Code),
                Stores = new StoreViewModel
                {
                    Stores = _storeService.GetEntryStoresViewModels(currentContent.Code),
                    SelectedStore = currentStore != null ? currentStore.Code : "",
                    SelectedStoreName = currentStore != null ? currentStore.Name : ""
                },
                StaticAssociations = associations,
                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>()
            });
        }
        public TestServiceProvider()
        {
            LocalizationService     = new Mock <ILocalizationService>();
            GenericAttributeService = new Mock <IGenericAttributeService>();
            WorkContext             = new Mock <IWorkContext>();

            DiscountCategoryMappingRepository     = new Mock <IRepository <DiscountCategoryMapping> >();
            DiscountManufacturerMappingRepository = new Mock <IRepository <DiscountManufacturerMapping> >();
            DiscountProductMappingRepository      = new Mock <IRepository <DiscountProductMapping> >();

            PriceCalculationService = new PriceCalculationService(new CatalogSettings(), new CurrencySettings(),
                                                                  new Mock <ICacheKeyService>().Object, new Mock <ICategoryService>().Object,
                                                                  new Mock <ICurrencyService>().Object, new Mock <ICustomerService>().Object,
                                                                  new Mock <IDiscountService>().Object, new Mock <IManufacturerService>().Object,
                                                                  new Mock <IProductAttributeParser>().Object, new Mock <IProductService>().Object,
                                                                  new TestCacheManager(), new Mock <IStoreContext>().Object, WorkContext.Object);

            LocalizationService.Setup(l => l.GetResource(It.IsAny <string>())).Returns("Invalid");
            WorkContext.Setup(p => p.WorkingLanguage).Returns(new Language {
                Id = 1
            });
            WorkContext.Setup(w => w.WorkingCurrency).Returns(new Currency {
                RoundingType = RoundingType.Rounding001
            });

            CurrencyService = new Mock <ICurrencyService>();
            CurrencyService.Setup(x => x.GetCurrencyById(1)).Returns(new Currency {
                Id = 1, RoundingTypeId = 0
            });

            GenericAttributeService.Setup(p => p.GetAttribute(It.IsAny <Customer>(), "product-advanced-mode", It.IsAny <int>(), false))
            .Returns(true);

            GenericAttributeService.Setup(p => p.GetAttribute(It.IsAny <Customer>(), "manufacturer-advanced-mode", It.IsAny <int>(), false))
            .Returns(true);

            GenericAttributeService.Setup(p => p.GetAttribute(It.IsAny <Customer>(), "category-advanced-mode", It.IsAny <int>(), false))
            .Returns(true);

            GenericAttributeService.Setup(x => x.GetAttribute <string>(It.IsAny <Customer>(), NopCustomerDefaults.SelectedPaymentMethodAttribute, It.IsAny <int>(), null))
            .Returns("test1");
        }
        private ProductTileViewModel CreateProductViewModelForEntry(EntryContentBase entry)
        {
            var   market        = _currentMarketService.GetCurrentMarket();
            var   currency      = _currencyService.GetCurrentCurrency();
            var   originalPrice = PriceCalculationService.GetSalePrice(entry.Code, market.MarketId, market.DefaultCurrency);
            Money?discountedPrice;

            if (originalPrice?.UnitPrice == null || originalPrice.UnitPrice.Amount == 0)
            {
                originalPrice = new PriceValue()
                {
                    UnitPrice = new Money(0, market.DefaultCurrency)
                };
                discountedPrice = null;
            }
            else
            {
                discountedPrice = GetDiscountPrice(entry, market, currency, originalPrice.UnitPrice);
            }

            var image        = entry.GetAssets <IContentImage>(_contentLoader, _urlResolver).FirstOrDefault() ?? "";
            var currentStore = _storeService.GetCurrentStoreViewModel();

            return(new ProductTileViewModel
            {
                Code = entry.Code,
                DisplayName = entry.DisplayName,
                PlacedPrice = originalPrice.UnitPrice,
                DiscountedPrice = discountedPrice,
                ImageUrl = image,
                Url = entry.GetUrl(),
                IsAvailable = originalPrice.UnitPrice != null && originalPrice.UnitPrice.Amount > 0,
                Stores = new StoreViewModel
                {
                    Stores = _storeService.GetEntryStoresViewModels(entry.Code),
                    SelectedStore = currentStore != null ? currentStore.Code : "",
                    SelectedStoreName = currentStore != null ? currentStore.Name : ""
                }
            });
        }
        public override IOrderGroup CreateInMemoryOrderGroup(
            ContentReference entryLink,
            IMarket market,
            Currency marketCurrency)
        {
            InMemoryOrderGroup memoryOrderGroup = new InMemoryOrderGroup(market, marketCurrency);

            memoryOrderGroup.CustomerId = PrincipalInfo.CurrentPrincipal.GetContactId();
            string      code  = _referenceConverter.GetCode(entryLink);
            IPriceValue price = PriceCalculationService.GetSalePrice(code, market.MarketId, marketCurrency);

            if (price != null && price.UnitPrice != null)
            {
                decimal priceAmount = price.UnitPrice.Amount;
                memoryOrderGroup.Forms.First().Shipments.First().LineItems.Add(new InMemoryLineItem()
                {
                    Quantity    = 1M,
                    Code        = code,
                    PlacedPrice = priceAmount
                });
            }

            return(memoryOrderGroup);
        }
 public ShoppingBasket()
 {
     _productService          = new ProductService();
     _priceCalculationService = new PriceCalculationService();
     _logService = new LogService();
 }
Пример #21
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);
        }
Пример #22
0
        public static ProductTileViewModel GetProductTileViewModel(this EntryContentBase entry, IMarket market, Currency currency, bool isFeaturedProduct = false)
        {
            var entryRecommendations = entry as IProductRecommendations;
            var product   = entry;
            var entryUrl  = "";
            var firstCode = "";
            var type      = typeof(GenericProduct);

            if (entry is GenericProduct)
            {
                var variants = GetProductVariants(entry);
                if (variants != null && variants.Any())
                {
                    firstCode = variants.First().Code;
                }
                entryUrl = UrlResolver.Value.GetUrl(entry.ContentLink);
            }

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

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

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

            IPriceValue price = PriceCalculationService.GetSalePrice(firstCode, market.MarketId, currency);

            if (price == null)
            {
                price = GetEmptyPrice(entry, market, currency);
            }
            IPriceValue discountPrice = price;

            if (price.UnitPrice.Amount > 0 && !string.IsNullOrEmpty(firstCode))
            {
                discountPrice = PromotionService.Value.GetDiscountPrice(new CatalogKey(firstCode), market.MarketId, currency);
            }

            bool isAvailable = price.UnitPrice.Amount > 0;

            return(new ProductTileViewModel
            {
                ProductId = product.ContentLink.ID,
                Brand = entry.Property.Keys.Contains("Brand") ? entry.Property["Brand"]?.Value?.ToString() ?? "" : "",
                Code = product.Code,
                DisplayName = entry.DisplayName,
                Description = entry.Property.Keys.Contains("Description") ? entry.Property["Description"]?.Value != null ? ((XhtmlString)entry.Property["Description"].Value).ToHtmlString() : "" : "",
                LongDescription = ShortenLongDescription(entry.Property.Keys.Contains("LongDescription") ? entry.Property["LongDescription"]?.Value != null ? ((XhtmlString)entry.Property["LongDescription"].Value).ToHtmlString() : "" : ""),
                PlacedPrice = price.UnitPrice,
                DiscountedPrice = discountPrice.UnitPrice,
                FirstVariationCode = firstCode,
                ImageUrl = AssetUrlResolver.Value.GetAssetUrl <IContentImage>(entry),
                VideoAssetUrl = AssetUrlResolver.Value.GetAssetUrl <IContentVideo>(entry),
                Url = entryUrl,
                IsAvailable = isAvailable,
                OnSale = entry.Property.Keys.Contains("OnSale") && ((bool?)entry.Property["OnSale"]?.Value ?? false),
                NewArrival = entry.Property.Keys.Contains("NewArrival") && ((bool?)entry.Property["NewArrival"]?.Value ?? false),
                ShowRecommendations = entryRecommendations != null ? entryRecommendations.ShowRecommendations : true,
                EntryType = type,
                ProductStatus = entry.Property.Keys.Contains("ProductStatus") ? entry.Property["ProductStatus"]?.Value?.ToString() ?? "Active" : "Active",
                Created = entry.Created,
                IsFeaturedProduct = isFeaturedProduct
            });
        }
Пример #23
0
        public new void SetUp()
        {
            _productService           = new Mock <IProductService>();
            _storeContext             = new Mock <IStoreContext>();
            _discountService          = new Mock <IDiscountService>();
            _categoryService          = new Mock <ICategoryService>();
            _manufacturerService      = new Mock <IManufacturerService>();
            _productAttributeParser   = new Mock <IProductAttributeParser>();
            _eventPublisher           = new Mock <IEventPublisher>();
            _localizationService      = new Mock <ILocalizationService>();
            _shippingMethodRepository = new Mock <IRepository <ShippingMethod> >();
            _warehouseRepository      = new Mock <IRepository <Warehouse> >();
            _shipmentService          = new Mock <IShipmentService>();
            _paymentService           = new Mock <IPaymentService>();
            _checkoutAttributeParser  = new Mock <ICheckoutAttributeParser>();
            _giftCardService          = new Mock <IGiftCardService>();
            _genericAttributeService  = new Mock <IGenericAttributeService>();
            _geoLookupService         = new Mock <IGeoLookupService>();
            _countryService           = new Mock <ICountryService>();
            _stateProvinceService     = new Mock <IStateProvinceService>();
            _eventPublisher           = new Mock <IEventPublisher>();
            _addressService           = new Mock <IAddressService>();
            _rewardPointService       = new Mock <IRewardPointService>();
            _orderService             = new Mock <IOrderService>();
            _webHelper                  = new Mock <IWebHelper>();
            _languageService            = new Mock <ILanguageService>();
            _priceFormatter             = new Mock <IPriceFormatter>();
            _productAttributeFormatter  = new Mock <IProductAttributeFormatter>();
            _shoppingCartService        = new Mock <IShoppingCartService>();
            _checkoutAttributeFormatter = new Mock <ICheckoutAttributeFormatter>();
            _customerService            = new Mock <ICustomerService>();
            _encryptionService          = new Mock <IEncryptionService>();
            _workflowMessageService     = new Mock <IWorkflowMessageService>();
            _customerActivityService    = new Mock <ICustomerActivityService>();
            _currencyService            = new Mock <ICurrencyService>();
            _affiliateService           = new Mock <IAffiliateService>();
            _vendorService              = new Mock <IVendorService>();
            _pdfService                 = new Mock <IPdfService>();
            _customNumberFormatter      = new Mock <ICustomNumberFormatter>();
            _rewardPointService         = new Mock <IRewardPointService>();

            _workContext = null;

            _store = new Store {
                Id = 1
            };

            _storeContext.Setup(x => x.CurrentStore).Returns(_store);

            _shoppingCartSettings = new ShoppingCartSettings();
            _catalogSettings      = new CatalogSettings();

            var cacheManager = new NopNullCache();

            //price calculation service
            _priceCalcService = new PriceCalculationService(_workContext, _storeContext.Object,
                                                            _discountService.Object, _categoryService.Object, _manufacturerService.Object,
                                                            _productAttributeParser.Object, _productService.Object,
                                                            cacheManager, _shoppingCartSettings, _catalogSettings);

            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            var pluginFinder = new PluginFinder(_eventPublisher.Object);

            //shipping
            _shippingSettings = new ShippingSettings
            {
                ActiveShippingRateComputationMethodSystemNames = new List <string>()
            };
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");

            _logger           = new NullLogger();
            _customerSettings = new CustomerSettings();
            _addressSettings  = new AddressSettings();

            _shippingService = new ShippingService(_shippingMethodRepository.Object,
                                                   _warehouseRepository.Object,
                                                   _logger,
                                                   _productService.Object,
                                                   _productAttributeParser.Object,
                                                   _checkoutAttributeParser.Object,
                                                   _genericAttributeService.Object,
                                                   _localizationService.Object,
                                                   _addressService.Object,
                                                   _shippingSettings,
                                                   pluginFinder,
                                                   _storeContext.Object,
                                                   _eventPublisher.Object,
                                                   _shoppingCartSettings,
                                                   cacheManager);

            //tax
            _taxSettings = new TaxSettings
            {
                ShippingIsTaxable = true,
                PaymentMethodAdditionalFeeIsTaxable = true,
                DefaultTaxAddressId = 10
            };

            _addressService.Setup(x => x.GetAddressById(_taxSettings.DefaultTaxAddressId)).Returns(new Address {
                Id = _taxSettings.DefaultTaxAddressId
            });
            _taxService = new TaxService(_addressService.Object, _workContext, _storeContext.Object, _taxSettings,
                                         pluginFinder, _geoLookupService.Object, _countryService.Object, _stateProvinceService.Object, _logger, _webHelper.Object,
                                         _customerSettings, _shippingSettings, _addressSettings);


            _rewardPointsSettings = new RewardPointsSettings();

            _orderTotalCalcService = new OrderTotalCalculationService(_workContext, _storeContext.Object,
                                                                      _priceCalcService, _productService.Object, _productAttributeParser.Object, _taxService, _shippingService, _paymentService.Object,
                                                                      _checkoutAttributeParser.Object, _discountService.Object, _giftCardService.Object,
                                                                      _genericAttributeService.Object, _rewardPointService.Object,
                                                                      _taxSettings, _rewardPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);

            _paymentSettings = new PaymentSettings
            {
                ActivePaymentMethodSystemNames = new List <string>
                {
                    "Payments.TestMethod"
                }
            };
            _orderSettings = new OrderSettings();

            _localizationSettings = new LocalizationSettings();

            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            _currencySettings = new CurrencySettings();

            _orderProcessingService = new OrderProcessingService(_orderService.Object, _webHelper.Object,
                                                                 _localizationService.Object, _languageService.Object,
                                                                 _productService.Object, _paymentService.Object, _logger,
                                                                 _orderTotalCalcService, _priceCalcService, _priceFormatter.Object,
                                                                 _productAttributeParser.Object, _productAttributeFormatter.Object,
                                                                 _giftCardService.Object, _shoppingCartService.Object, _checkoutAttributeFormatter.Object,
                                                                 _shippingService, _shipmentService.Object, _taxService,
                                                                 _customerService.Object, _discountService.Object,
                                                                 _encryptionService.Object, _workContext,
                                                                 _workflowMessageService.Object, _vendorService.Object,
                                                                 _customerActivityService.Object, _currencyService.Object, _affiliateService.Object,
                                                                 _eventPublisher.Object, _pdfService.Object, _rewardPointService.Object,
                                                                 _genericAttributeService.Object,
                                                                 _countryService.Object, _stateProvinceService.Object,
                                                                 _shippingSettings, _paymentSettings, _rewardPointsSettings,
                                                                 _orderSettings, _taxSettings, _localizationSettings,
                                                                 _currencySettings, _customNumberFormatter.Object);
        }
 public void Setup()
 {
     _service = new PriceCalculationService();
 }