Exemplo n.º 1
0
        public static Store GetTestStore()
        {
            var currency = new Currency
            {
                Name = "US Dollar",
                CurrencyCode = "USD",
                Rate = 1.1M,
                DisplayLocale = "en-US",
                CustomFormatting = "CustomFormatting 1",
                LimitedToStores = true,
                Published = true,
                DisplayOrder = 2,
                CreatedOnUtc = new DateTime(2010, 01, 01),
                UpdatedOnUtc = new DateTime(2010, 01, 02),
            };

            var store = new Store
            {
                Name = "Computer store",
                Url = "http://www.yourStore.com",
                Hosts = "yourStore.com,www.yourStore.com",
                LogoPictureId = 0,
                DisplayOrder = 1,
                PrimaryStoreCurrency = currency,
                PrimaryExchangeRateCurrency = currency
            };

            return store;
        }
        public new void SetUp()
        {
			_store = new Store() { Id = 1 };
			_storeContext = MockRepository.GenerateMock<IStoreContext>();
			_storeContext.Expect(x => x.CurrentStore).Return(_store);

            _discountService = MockRepository.GenerateMock<IDiscountService>();

            _categoryService = MockRepository.GenerateMock<ICategoryService>();

            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
			_productService = MockRepository.GenerateMock<IProductService>();
			_productAttributeService = MockRepository.GenerateMock<IProductAttributeService>();

			_downloadService = MockRepository.GenerateMock<IDownloadService>();
			_commonServices = MockRepository.GenerateMock<ICommonServices>();
			_commonServices.Expect(x => x.StoreContext).Return(_storeContext);
			_httpRequestBase = MockRepository.GenerateMock<HttpRequestBase>();
			_taxService = MockRepository.GenerateMock<ITaxService>();

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

			_priceCalcService = new PriceCalculationService(_discountService, _categoryService, _productAttributeParser, _productService, _shoppingCartSettings, _catalogSettings,
				_productAttributeService, _downloadService, _commonServices, _httpRequestBase, _taxService);
        }
		public void SetPreviewStore(int? storeId)
		{
			try
			{
				_httpContext.SetPreviewModeValue(OverriddenStoreIdKey, storeId.HasValue ? storeId.Value.ToString() : null);
				_currentStore = null;
			}
			catch { }
		}
		public void Can_parse_host_values()
		{
			var store = new Store()
			{
				Hosts = "yourstore.com, www.yourstore.com, "
			};

			var hosts = store.ParseHostValues();
			hosts.Length.ShouldEqual(2);
			hosts[0].ShouldEqual("yourstore.com");
			hosts[1].ShouldEqual("www.yourstore.com");
		}
		public void Can_find_host_value()
		{
			var store = new Store()
			{
				Hosts = "yourstore.com, www.yourstore.com, "
			};

			store.ContainsHostValue(null).ShouldEqual(false);
			store.ContainsHostValue("").ShouldEqual(false);
			store.ContainsHostValue("store.com").ShouldEqual(false);
			store.ContainsHostValue("yourstore.com").ShouldEqual(true);
			store.ContainsHostValue("yoursTore.com").ShouldEqual(true);
			store.ContainsHostValue("www.yourstore.com").ShouldEqual(true);
		}
Exemplo n.º 6
0
		/// <summary>
		/// Deletes a store
		/// </summary>
		/// <param name="store">Store</param>
		public virtual void DeleteStore(Store store)
		{
			if (store == null)
				throw new ArgumentNullException("store");

			var allStores = GetAllStores();
			if (allStores.Count == 1)
				throw new Exception("You cannot delete the only configured store.");

			_storeRepository.Delete(store);

			_cacheManager.RemoveByPattern(STORES_PATTERN_KEY);

			//event notification
			_eventPublisher.EntityDeleted(store);
		}
		public void SetRequestStore(int? storeId)
		{
			try
			{
				var dataTokens = _httpContext.Request.RequestContext.RouteData.DataTokens;
				if (storeId.GetValueOrDefault() > 0)
				{
					dataTokens[OverriddenStoreIdKey] = storeId.Value;
				}
				else if (dataTokens.ContainsKey(OverriddenStoreIdKey))
				{
					dataTokens.Remove(OverriddenStoreIdKey);
				}

				_currentStore = null;
			}
			catch { }
		}
		public void Can_save_and_load_store()
		{
			var store = new Store
			{
				Name = "Computer store",
				Url = "http://www.yourStore.com",
				Hosts = "yourStore.com,www.yourStore.com",
				LogoPictureId = 0,
				DisplayOrder = 1
			};

			var fromDb = SaveAndLoadEntity(store);
			fromDb.ShouldNotBeNull();
			fromDb.Name.ShouldEqual("Computer store");
			fromDb.Url.ShouldEqual("http://www.yourStore.com");
			fromDb.Hosts.ShouldEqual("yourStore.com,www.yourStore.com");
			fromDb.LogoPictureId.ShouldEqual(0);
			fromDb.DisplayOrder.ShouldEqual(1);
		}
 public string ProductDetailUrl(Store store, Product product)
 {
     return "{0}{1}".FormatWith(store.Url, product.GetSeName(Language.Id));
 }
Exemplo n.º 10
0
        public string MainProductImageUrl(Store store, Product product)
        {
            string url;
            var pictureService = EngineContext.Current.Resolve<IPictureService>();
            var picture = product.GetDefaultProductPicture(pictureService);

            //always use HTTP when getting image URL
            if (picture != null)
                url = pictureService.GetPictureUrl(picture, BaseSettings.ProductPictureSize, storeLocation: store.Url);
            else
                url = pictureService.GetDefaultPictureUrl(BaseSettings.ProductPictureSize, storeLocation: store.Url);

            return url;
        }
Exemplo n.º 11
0
		/// <summary>
		/// Updates the store
		/// </summary>
		/// <param name="store">Store</param>
		public virtual void UpdateStore(Store store)
		{
			if (store == null)
				throw new ArgumentNullException("store");

			_storeRepository.Update(store);

			_cacheManager.RemoveByPattern(STORES_PATTERN_KEY);

			//event notification
			_eventPublisher.EntityUpdated(store);
		}
        public new void SetUp()
        {
            _workContext = null;

            _store = new Store() { Id = 1 };
            _storeContext = MockRepository.GenerateMock<IStoreContext>();
            _storeContext.Expect(x => x.CurrentStore).Return(_store);

            var pluginFinder = new PluginFinder();
            var cacheManager = new NullCache();

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

            //price calculation service
            _discountService = MockRepository.GenerateMock<IDiscountService>();
            _categoryService = MockRepository.GenerateMock<ICategoryService>();
            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
            _priceCalcService = new PriceCalculationService(_workContext, _storeContext,
                _discountService, _categoryService,	_productAttributeParser, _productService, _shoppingCartSettings, _catalogSettings);
            _eventPublisher = MockRepository.GenerateMock<IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg<object>.Is.Anything));

            _localizationService = MockRepository.GenerateMock<ILocalizationService>();
            _settingService = MockRepository.GenerateMock<ISettingService>();

            //shipping
            _shippingSettings = new ShippingSettings();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames = new List<string>();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");
            _shippingMethodRepository = MockRepository.GenerateMock<IRepository<ShippingMethod>>();
            _logger = new NullLogger();
            _shippingService = new ShippingService(cacheManager,
                _shippingMethodRepository,
                _logger,
                _productAttributeParser,
                _productService,
                _checkoutAttributeParser,
                _genericAttributeService,
                _localizationService,
                _shippingSettings, pluginFinder,
                _eventPublisher, _shoppingCartSettings,
                _settingService);
            _shipmentService = MockRepository.GenerateMock<IShipmentService>();

            _paymentService = MockRepository.GenerateMock<IPaymentService>();
            _checkoutAttributeParser = MockRepository.GenerateMock<ICheckoutAttributeParser>();
            _giftCardService = MockRepository.GenerateMock<IGiftCardService>();
            _genericAttributeService = MockRepository.GenerateMock<IGenericAttributeService>();

            //tax
            _taxSettings = new TaxSettings();
            _taxSettings.ShippingIsTaxable = true;
            _taxSettings.PaymentMethodAdditionalFeeIsTaxable = true;
            _taxSettings.DefaultTaxAddressId = 10;
            _addressService = MockRepository.GenerateMock<IAddressService>();
            _addressService.Expect(x => x.GetAddressById(_taxSettings.DefaultTaxAddressId)).Return(new Address() { Id = _taxSettings.DefaultTaxAddressId });
            _taxService = new TaxService(_addressService, _workContext, _taxSettings, _shoppingCartSettings, pluginFinder, _settingService);

            _rewardPointsSettings = new RewardPointsSettings();

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

            _orderService = MockRepository.GenerateMock<IOrderService>();
            _webHelper = MockRepository.GenerateMock<IWebHelper>();
            _languageService = MockRepository.GenerateMock<ILanguageService>();
            _productService = MockRepository.GenerateMock<IProductService>();
            _priceFormatter= MockRepository.GenerateMock<IPriceFormatter>();
            _productAttributeFormatter= MockRepository.GenerateMock<IProductAttributeFormatter>();
            _shoppingCartService= MockRepository.GenerateMock<IShoppingCartService>();
            _checkoutAttributeFormatter= MockRepository.GenerateMock<ICheckoutAttributeFormatter>();
            _customerService= MockRepository.GenerateMock<ICustomerService>();
            _encryptionService = MockRepository.GenerateMock<IEncryptionService>();
            _workflowMessageService = MockRepository.GenerateMock<IWorkflowMessageService>();
            _customerActivityService = MockRepository.GenerateMock<ICustomerActivityService>();
            _currencyService = MockRepository.GenerateMock<ICurrencyService>();
            _affiliateService = MockRepository.GenerateMock<IAffiliateService>();

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

            _localizationSettings = new LocalizationSettings();

            _eventPublisher = MockRepository.GenerateMock<IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg<object>.Is.Anything));

            _currencySettings = new CurrencySettings();

            _orderProcessingService = new OrderProcessingService(_orderService, _webHelper,
                _localizationService, _languageService,
                _productService, _paymentService, _logger,
                _orderTotalCalcService, _priceCalcService, _priceFormatter,
                _productAttributeParser, _productAttributeFormatter,
                _giftCardService, _shoppingCartService, _checkoutAttributeFormatter,
                _shippingService, _shipmentService, _taxService,
                _customerService, _discountService,
                _encryptionService, _workContext, _storeContext, _workflowMessageService,
                _customerActivityService, _currencyService, _affiliateService,
                _eventPublisher, _paymentSettings, _rewardPointsSettings,
                _orderSettings, _taxSettings, _localizationSettings,
                _currencySettings);
        }
Exemplo n.º 13
0
        private string WriteItem(XmlWriter writer, Store store, Product product, Currency currency, string measureWeightSystemKey)
        {
            var manu = _manufacturerService.GetProductManufacturersByProductId(product.Id).FirstOrDefault();
            var mainImageUrl = Helper.GetMainProductImageUrl(store, product);
            var googleProduct = GetGoogleProductRecord(product.Id);
            var category = ProductCategory(googleProduct);

            if (category.IsNullOrEmpty())
                return Helper.GetResource("MissingDefaultCategory");

            string manuName = (manu != null ? manu.Manufacturer.GetLocalized(x => x.Name, Settings.LanguageId, true, false) : null);
            string productName = product.GetLocalized(x => x.Name, Settings.LanguageId, true, false);
            string shortDescription = product.GetLocalized(x => x.ShortDescription, Settings.LanguageId, true, false);
            string fullDescription = product.GetLocalized(x => x.FullDescription, Settings.LanguageId, true, false);

            var brand = (manuName ?? Settings.Brand);
            var mpn = Helper.GetManufacturerPartNumber(product);

            bool identifierExists = product.Gtin.HasValue() || brand.HasValue() || mpn.HasValue();

            writer.WriteElementString("g", "id", _googleNamespace, product.Id.ToString());

            writer.WriteStartElement("title");
            writer.WriteCData(productName.Truncate(70));
            writer.WriteEndElement();

            var description = Helper.BuildProductDescription(productName, shortDescription, fullDescription, manuName, d =>
            {
                if (fullDescription.IsNullOrEmpty() && shortDescription.IsNullOrEmpty())
                {
                    var rnd = new Random();

                    switch (rnd.Next(1, 5))
                    {
                        case 1: return d.Grow(Settings.AppendDescriptionText1, " ");
                        case 2: return d.Grow(Settings.AppendDescriptionText2, " ");
                        case 3: return d.Grow(Settings.AppendDescriptionText3, " ");
                        case 4: return d.Grow(Settings.AppendDescriptionText4, " ");
                        case 5: return d.Grow(Settings.AppendDescriptionText5, " ");
                    }
                }
                return d;
            });

            writer.WriteStartElement("description");
            writer.WriteCData(description.RemoveInvalidXmlChars());
            writer.WriteEndElement();

            writer.WriteStartElement("g", "google_product_category", _googleNamespace);
            writer.WriteCData(category);
            writer.WriteFullEndElement();

            string productType = Helper.GetCategoryPath(product);
            if (productType.HasValue())
            {
                writer.WriteStartElement("g", "product_type", _googleNamespace);
                writer.WriteCData(productType);
                writer.WriteFullEndElement();
            }

            writer.WriteElementString("link", Helper.GetProductDetailUrl(store, product));
            writer.WriteElementString("g", "image_link", _googleNamespace, mainImageUrl);

            foreach (string additionalImageUrl in Helper.GetAdditionalProductImages(store, product, mainImageUrl))
            {
                writer.WriteElementString("g", "additional_image_link", _googleNamespace, additionalImageUrl);
            }

            writer.WriteElementString("g", "condition", _googleNamespace, Condition());
            writer.WriteElementString("g", "availability", _googleNamespace, Availability(product));

            decimal price = Helper.GetProductPrice(product, currency);
            string specialPriceDate;

            if (SpecialPrice(product, out specialPriceDate))
            {
                writer.WriteElementString("g", "sale_price", _googleNamespace, price.FormatInvariant() + " " + currency.CurrencyCode);
                writer.WriteElementString("g", "sale_price_effective_date", _googleNamespace, specialPriceDate);

                // get regular price ignoring any special price
                decimal specialPrice = product.SpecialPrice.Value;
                product.SpecialPrice = null;
                price = Helper.GetProductPrice(product, currency);
                product.SpecialPrice = specialPrice;

                _dbContext.SetToUnchanged<Product>(product);
            }

            writer.WriteElementString("g", "price", _googleNamespace, price.FormatInvariant() + " " + currency.CurrencyCode);

            writer.WriteCData("gtin", product.Gtin, "g", _googleNamespace);
            writer.WriteCData("brand", brand, "g", _googleNamespace);
            writer.WriteCData("mpn", mpn, "g", _googleNamespace);

            writer.WriteCData("gender", Gender(googleProduct), "g", _googleNamespace);
            writer.WriteCData("age_group", AgeGroup(googleProduct), "g", _googleNamespace);
            writer.WriteCData("color", Color(googleProduct), "g", _googleNamespace);
            writer.WriteCData("size", Size(googleProduct), "g", _googleNamespace);
            writer.WriteCData("material", Material(googleProduct), "g", _googleNamespace);
            writer.WriteCData("pattern", Pattern(googleProduct), "g", _googleNamespace);
            writer.WriteCData("item_group_id", ItemGroupId(googleProduct), "g", _googleNamespace);

            writer.WriteElementString("g", "online_only", _googleNamespace, Settings.OnlineOnly ? "y" : "n");
            writer.WriteElementString("g", "identifier_exists", _googleNamespace, identifierExists ? "TRUE" : "FALSE");

            if (Settings.ExpirationDays > 0)
            {
                writer.WriteElementString("g", "expiration_date", _googleNamespace, DateTime.UtcNow.AddDays(Settings.ExpirationDays).ToString("yyyy-MM-dd"));
            }

            if (Settings.ExportShipping)
            {
                string weightInfo, weight = product.Weight.FormatInvariant();

                if (measureWeightSystemKey.IsCaseInsensitiveEqual("gram"))
                    weightInfo = weight + " g";
                else if (measureWeightSystemKey.IsCaseInsensitiveEqual("lb"))
                    weightInfo = weight + " lb";
                else if (measureWeightSystemKey.IsCaseInsensitiveEqual("ounce"))
                    weightInfo = weight + " oz";
                else
                    weightInfo = weight + " kg";

                writer.WriteElementString("g", "shipping_weight", _googleNamespace, weightInfo);
            }

            if (Settings.ExportBasePrice && product.BasePriceHasValue)
            {
                string measureUnit = BasePriceUnits(product.BasePriceMeasureUnit);

                if (BasePriceSupported(product.BasePriceBaseAmount ?? 0, measureUnit))
                {
                    string basePriceMeasure = "{0} {1}".FormatWith((product.BasePriceAmount ?? decimal.Zero).FormatInvariant(), measureUnit);
                    string basePriceBaseMeasure = "{0} {1}".FormatWith(product.BasePriceBaseAmount, measureUnit);

                    writer.WriteElementString("g", "unit_pricing_measure", _googleNamespace, basePriceMeasure);
                    writer.WriteElementString("g", "unit_pricing_base_measure", _googleNamespace, basePriceBaseMeasure);
                }
            }

            return null;
        }
        /// <summary>
        /// Resolves the file name pattern for an export profile
        /// </summary>
        /// <param name="profile">Export profile</param>
        /// <param name="store">Store</param>
        /// <param name="fileIndex">One based file index</param>
        /// <param name="maxFileNameLength">The maximum length of the file name</param>
        /// <returns>Resolved file name pattern</returns>
        public static string ResolveFileNamePattern(this ExportProfile profile, Store store, int fileIndex, int maxFileNameLength)
        {
            var sb = new StringBuilder(profile.FileNamePattern);

            sb.Replace("%Profile.Id%", profile.Id.ToString());
            sb.Replace("%Profile.FolderName%", profile.FolderName);
            sb.Replace("%Store.Id%", store.Id.ToString());
            sb.Replace("%File.Index%", fileIndex.ToString("D4"));

            if (profile.FileNamePattern.Contains("%Profile.SeoName%"))
                sb.Replace("%Profile.SeoName%", SeoHelper.GetSeName(profile.Name, true, false).Replace("/", "").Replace("-", ""));

            if (profile.FileNamePattern.Contains("%Store.SeoName%"))
                sb.Replace("%Store.SeoName%", profile.PerStore ? SeoHelper.GetSeName(store.Name, true, false) : "allstores");

            if (profile.FileNamePattern.Contains("%Random.Number%"))
                sb.Replace("%Random.Number%", CommonHelper.GenerateRandomInteger().ToString());

            if (profile.FileNamePattern.Contains("%Timestamp%"))
                sb.Replace("%Timestamp%", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture));

            var result = sb.ToString()
                .ToValidFileName("")
                .Truncate(maxFileNameLength);

            return result;
        }
        /// <summary>
        /// Get url of the public folder and take filtering and projection into consideration
        /// </summary>
        /// <param name="deployment">Export deployment</param>
        /// <param name="services">Common services</param>
        /// <param name="store">Store entity</param>
        /// <returns>Absolute URL of the public folder (always ends with /) or <c>null</c></returns>
        public static string GetPublicFolderUrl(this ExportDeployment deployment, ICommonServices services, Store store = null)
        {
            if (deployment != null && deployment.DeploymentType == ExportDeploymentType.PublicFolder)
            {
                if (store == null)
                {
                    var filter = XmlHelper.Deserialize<ExportFilter>(deployment.Profile.Filtering);
                    var storeId = filter.StoreId;

                    if (storeId == 0)
                    {
                        var projection = XmlHelper.Deserialize<ExportProjection>(deployment.Profile.Projection);
                        storeId = (projection.StoreId ?? 0);
                    }

                    store = (storeId == 0 ? services.StoreContext.CurrentStore : services.StoreService.GetStoreById(storeId));
                }

                var url = string.Concat(
                    store.Url.EnsureEndsWith("/"),
                    DataExporter.PublicFolder.EnsureEndsWith("/"),
                    deployment.SubFolder.HasValue() ? deployment.SubFolder.EnsureEndsWith("/") : ""
                );

                return url;
            }

            return null;
        }
        public new void SetUp()
        {
            _genericAttributeService = MockRepository.GenerateMock<IGenericAttributeService>();
            _settingService = MockRepository.GenerateMock<ISettingService>();

            _workContext = MockRepository.GenerateMock<IWorkContext>();

            _store = new Store() { Id = 1 };
            _storeContext = MockRepository.GenerateMock<IStoreContext>();
            _storeContext.Expect(x => x.CurrentStore).Return(_store);

            _dateTimeSettings = new DateTimeSettings()
            {
                AllowCustomersToSetTimeZone = false,
                DefaultStoreTimeZoneId = ""
            };

            _dateTimeHelper = new DateTimeHelper(_workContext, _genericAttributeService,
                _settingService, _dateTimeSettings);
        }
        public new void SetUp()
        {
            _workContext = MockRepository.GenerateMock<IWorkContext>();

            _store = new Store { Id = 1 };
            _storeContext = MockRepository.GenerateMock<IStoreContext>();
            _storeContext.Expect(x => x.CurrentStore).Return(_store);

            var pluginFinder = new PluginFinder();

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

            //price calculation service
            _discountService = MockRepository.GenerateMock<IDiscountService>();
            _categoryService = MockRepository.GenerateMock<ICategoryService>();
            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
            _productService = MockRepository.GenerateMock<IProductService>();
            _productAttributeService = MockRepository.GenerateMock<IProductAttributeService>();
            _genericAttributeService = MockRepository.GenerateMock<IGenericAttributeService>();
            _eventPublisher = MockRepository.GenerateMock<IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg<object>.Is.Anything));

            _settingService = MockRepository.GenerateMock<ISettingService>();
            _typeFinder = MockRepository.GenerateMock<ITypeFinder>();

            //shipping
            _shippingSettings = new ShippingSettings();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames = new List<string>();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");
            _shippingMethodRepository = MockRepository.GenerateMock<IRepository<ShippingMethod>>();
            _logger = new NullLogger();

            _shippingService = new ShippingService(
                _shippingMethodRepository,
                _logger,
                _productAttributeParser,
                _productService,
                _checkoutAttributeParser,
                _genericAttributeService,
                _shippingSettings,
                _eventPublisher,
                _shoppingCartSettings,
                _settingService,
                this.ProviderManager,
                _typeFinder);

            _providerManager = MockRepository.GenerateMock<IProviderManager>();
            _checkoutAttributeParser = MockRepository.GenerateMock<ICheckoutAttributeParser>();
            _giftCardService = MockRepository.GenerateMock<IGiftCardService>();

            //tax
            _taxSettings = new TaxSettings();
            _taxSettings.ShippingIsTaxable = true;
            _taxSettings.PaymentMethodAdditionalFeeIsTaxable = true;
            _taxSettings.PricesIncludeTax = false;
            _taxSettings.TaxDisplayType = TaxDisplayType.IncludingTax;
            _taxSettings.DefaultTaxAddressId = 10;

            _addressService = MockRepository.GenerateMock<IAddressService>();
            _addressService.Expect(x => x.GetAddressById(_taxSettings.DefaultTaxAddressId)).Return(new Address { Id = _taxSettings.DefaultTaxAddressId });
            _downloadService = MockRepository.GenerateMock<IDownloadService>();
            _services = MockRepository.GenerateMock<ICommonServices>();
            _httpRequestBase = MockRepository.GenerateMock<HttpRequestBase>();
            _geoCountryLookup = MockRepository.GenerateMock<IGeoCountryLookup>();

            _taxService = new TaxService(_addressService, _workContext, _taxSettings, _shoppingCartSettings, pluginFinder, _geoCountryLookup, this.ProviderManager);

            _rewardPointsSettings = new RewardPointsSettings();

            _priceCalcService = new PriceCalculationService(_discountService, _categoryService, _productAttributeParser, _productService, _shoppingCartSettings, _catalogSettings,
                _productAttributeService, _downloadService, _services, _httpRequestBase, _taxService);

            _orderTotalCalcService = new OrderTotalCalculationService(_workContext, _storeContext,
                _priceCalcService, _taxService, _shippingService, _providerManager,
                _checkoutAttributeParser, _discountService, _giftCardService, _genericAttributeService, _productAttributeParser,
                _taxSettings, _rewardPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);
        }
Exemplo n.º 18
0
        public List<Product> QualifiedProductsByProduct(IProductService productService, Product product, Store store)
        {
            var lst = new List<Product>();

            if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct)
            {
                lst.Add(product);
            }
            else if (product.ProductType == ProductType.GroupedProduct)
            {
                var associatedSearchContext = new ProductSearchContext()
                {
                    OrderBy = ProductSortingEnum.CreatedOn,
                    PageSize = int.MaxValue,
                    StoreId = store.Id,
                    VisibleIndividuallyOnly = false,
                    ParentGroupedProductId = product.Id
                };

                lst.AddRange(productService.SearchProducts(associatedSearchContext));
            }
            return lst;
        }
Exemplo n.º 19
0
        public List<string> AdditionalProductImages(Store store, Product product, string mainImageUrl, int maxImages = 10)
        {
            var urls = new List<string>();

            if (BaseSettings.AdditionalImages)
            {
                var pictureService = EngineContext.Current.Resolve<IPictureService>();
                var pics = pictureService.GetPicturesByProductId(product.Id, 0);

                foreach (var pic in pics)
                {
                    if (pic != null)
                    {
                        string url = pictureService.GetPictureUrl(pic, BaseSettings.ProductPictureSize, storeLocation: store.Url);

                        if (url.HasValue() && (mainImageUrl.IsNullOrEmpty() || !mainImageUrl.IsCaseInsensitiveEqual(url)))
                        {
                            urls.Add(url);
                            if (urls.Count >= maxImages)
                                break;
                        }
                    }
                }
            }
            return urls;
        }
Exemplo n.º 20
0
        public FeedFileData GetFeedFileByStore(Store store, string secondFileName = null, string extension = null)
        {
            if (store == null)
                return null;

            string dirTemp = FileSystemHelper.TempDir();
            string ext = extension ?? BaseSettings.ExportFormat;
            string dir = Path.Combine(HttpRuntime.AppDomainAppPath, "Content\\files\\exportimport");
            string fileName = "{0}_{1}".FormatWith(store.Id, BaseSettings.StaticFileName);
            string logName = Path.GetFileNameWithoutExtension(fileName) + ".txt";

            if (ext.HasValue())
                fileName = Path.GetFileNameWithoutExtension(fileName) + (ext.StartsWith(".") ? "" : ".") + ext;

            string url = "{0}content/files/exportimport/".FormatWith(store.Url.EnsureEndsWith("/"));

            if (!(url.StartsWith("http://") || url.StartsWith("https://")))
                url = "http://" + url;

            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            var feedFile = new FeedFileData
            {
                StoreId = store.Id,
                StoreName = store.Name,
                FileTempPath = Path.Combine(dirTemp, fileName),
                FilePath = Path.Combine(dir, fileName),
                FileUrl = url + fileName,
                LogPath = Path.Combine(dir, logName),
                LogUrl = url + logName
            };

            try
            {
                feedFile.LastWriteTime = File.GetLastWriteTimeUtc(feedFile.FilePath).RelativeFormat(true, null);
            }
            catch (Exception)
            {
                feedFile.LastWriteTime = feedFile.LastWriteTime.NaIfEmpty();
            }

            if (secondFileName.HasValue())
            {
                string fname2 = store.Id + "_" + secondFileName;
                feedFile.CustomProperties.Add("SecondFileTempPath", Path.Combine(dirTemp, fname2));
                feedFile.CustomProperties.Add("SecondFilePath", Path.Combine(dir, fname2));
                feedFile.CustomProperties.Add("SecondFileUrl", url + fname2);
            }
            return feedFile;
        }
		public static Store ToEntity(this StoreModel model, Store destination)
		{
			return Mapper.Map(model, destination);
		}
Exemplo n.º 22
0
        public decimal? GetOldPrice(Product product, Currency currency, Store store)
        {
            if (!decimal.Equals(product.OldPrice, decimal.Zero) && !decimal.Equals(product.OldPrice, product.Price) &&
                !(product.ProductType == ProductType.BundledProduct && product.BundlePerItemPricing))
            {
                decimal price = product.OldPrice;

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

                return CurrencyService.ConvertFromPrimaryStoreCurrency(price, currency, store);
            }
            return null;
        }
Exemplo n.º 23
0
 public virtual void AddStoreTokens(IList<Token> tokens, Store store)
 {
     tokens.Add(new Token("Store.Name", store.Name));
     tokens.Add(new Token("Store.URL", store.Url, true));
     var defaultEmailAccount = _emailAccountService.GetDefaultEmailAccount();
     tokens.Add(new Token("Store.SupplierIdentification", GetSupplierIdentification(), true));
     tokens.Add(new Token("Store.Email", defaultEmailAccount.Email));
 }
 public virtual void AddStoreTokens(IList<Token> tokens, Store store)
 {
     tokens.Add(new Token("Store.Name", store.Name));
     tokens.Add(new Token("Store.URL", store.Url, true));
     var defaultEmailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
     if (defaultEmailAccount == null)
         defaultEmailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
     tokens.Add(new Token("Store.SupplierIdentification", GetSupplierIdentification(), true));
     tokens.Add(new Token("Store.Email", defaultEmailAccount.Email));
 }
Exemplo n.º 25
0
 public string GetProductDetailUrl(Store store, Product product)
 {
     return "{0}{1}".FormatWith(store.Url, product.GetSeName(Language.Id, UrlRecordService, LanguageService));
 }
Exemplo n.º 26
0
        /// <summary>
        /// Converts to primary store currency 
        /// </summary>
        /// <param name="amount">Amount</param>
        /// <param name="sourceCurrencyCode">Source currency code</param>
        /// <param name="store">Store to get the primary store currency from</param>
        /// <returns>Converted value</returns>
        public virtual decimal ConvertToPrimaryStoreCurrency(decimal amount, Currency sourceCurrencyCode, Store store = null)
        {
            decimal result = amount;
            var primaryStoreCurrency = (store == null ? _storeContext.CurrentStore.PrimaryStoreCurrency : store.PrimaryStoreCurrency);

            if (result != decimal.Zero && sourceCurrencyCode.Id != primaryStoreCurrency.Id)
            {
                decimal exchangeRate = sourceCurrencyCode.Rate;
                if (exchangeRate == decimal.Zero)
                    throw new SmartException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));
                result = result / exchangeRate;
            }
            return result;
        }
Exemplo n.º 27
0
 /// <summary>
 /// Converts from primary store currency
 /// </summary>
 /// <param name="amount">Amount</param>
 /// <param name="targetCurrencyCode">Target currency code</param>
 /// <returns>Converted value</returns>
 public virtual decimal ConvertFromPrimaryStoreCurrency(decimal amount, Currency targetCurrencyCode, Store store = null)
 {
     decimal result = amount;
     var primaryStoreCurrency = (store == null ? _storeContext.CurrentStore.PrimaryStoreCurrency : store.PrimaryStoreCurrency);
     result = ConvertCurrency(amount, primaryStoreCurrency, targetCurrencyCode, store);
     return result;
 }
Exemplo n.º 28
0
        public decimal GetProductPrice(Product product, Currency currency, Store store)
        {
            decimal priceBase = PriceCalculationService.GetPreselectedPrice(product, null);

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

            decimal price = CurrencyService.ConvertFromPrimaryStoreCurrency(priceBase, currency, store);
            return price;
        }
Exemplo n.º 29
0
 /// <summary>
 /// Converts currency
 /// </summary>
 /// <param name="amount">Amount</param>
 /// <param name="sourceCurrencyCode">Source currency code</param>
 /// <param name="targetCurrencyCode">Target currency code</param>
 /// <param name="store">Store to get the primary currencies from</param>
 /// <returns>Converted value</returns>
 public virtual decimal ConvertCurrency(decimal amount, Currency sourceCurrencyCode, Currency targetCurrencyCode, Store store = null)
 {
     decimal result = amount;
     if (sourceCurrencyCode.Id == targetCurrencyCode.Id)
         return result;
     if (result != decimal.Zero && sourceCurrencyCode.Id != targetCurrencyCode.Id)
     {
         result = ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode, store);
         result = ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode, store);
     }
     return result;
 }
Exemplo n.º 30
0
        public GeneratedFeedFile FeedFileByStore(Store store, string secondFileName = null, string extension = null)
        {
            if (store != null)
            {
                string ext = extension ?? BaseSettings.ExportFormat;
                string dir = Path.Combine(HttpRuntime.AppDomainAppPath, "Content\\files\\exportimport");
                string fname = "{0}_{1}".FormatWith(store.Id, BaseSettings.StaticFileName);

                if (ext.HasValue())
                    fname = Path.GetFileNameWithoutExtension(fname) + (ext.StartsWith(".") ? "" : ".") + ext;

                string url = "{0}content/files/exportimport/".FormatWith(store.Url.EnsureEndsWith("/"));

                if (!(url.StartsWith("http://") || url.StartsWith("https://")))
                    url = "http://" + url;

                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                var feedFile = new GeneratedFeedFile()
                {
                    StoreName = store.Name,
                    FilePath = Path.Combine(dir, fname),
                    FileUrl = url + fname
                };

                if (secondFileName.HasValue())
                {
                    string fname2 = store.Id + "_" + secondFileName;
                    feedFile.CustomProperties.Add("SecondFilePath", Path.Combine(dir, fname2));
                    feedFile.CustomProperties.Add("SecondFileUrl", url + fname2);
                }
                return feedFile;
            }
            return null;
        }