コード例 #1
0
        public new void SetUp()
        {
            _workContext = null;

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

            _discountService = MockRepository.GenerateMock<IDiscountService>();
            _categoryService = MockRepository.GenerateMock<ICategoryService>();
            _productService = MockRepository.GenerateMock<IProductService>();


            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();

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

            _cacheManager = new NopNullCache();

            _priceCalcService = new PriceCalculationService(_workContext,
                _storeContext, 
                _discountService,
                _categoryService,
                _productAttributeParser,
                _productService,
                _cacheManager,
                _shoppingCartSettings, 
                _catalogSettings);
        }
コード例 #2
0
        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",
                DefaultLanguageId = 1,
                DisplayOrder = 2,
                CompanyName = "company name",
                CompanyAddress = "some address",
                CompanyPhoneNumber = "123456789",
                CompanyVat = "some vat",
            };

            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.DefaultLanguageId.ShouldEqual(1);
            fromDb.DisplayOrder.ShouldEqual(2);
            fromDb.CompanyName.ShouldEqual("company name");
            fromDb.CompanyAddress.ShouldEqual("some address");
            fromDb.CompanyPhoneNumber.ShouldEqual("123456789");
            fromDb.CompanyVat.ShouldEqual("some vat");
        }
コード例 #3
0
 protected virtual void UpdateAttributeLocales(Store store, StoreModel model)
 {
     foreach (var localized in model.Locales)
     {
         _localizedEntityService.SaveLocalizedValue(store,
             x => x.Name,
             localized.Name,
             localized.LanguageId);
     }
 }
コード例 #4
0
        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");
        }
コード例 #5
0
        public static void setStore(this Vendor vendor, Store store)
        {
            var _vendorStoreRepository = EngineContext.Current.Resolve<IRepository<VendorStore>>();
            var _storeRepository = EngineContext.Current.Resolve<IRepository<Store>>();

            var vendorStore = new VendorStore
            {
                StoreId = store.Id,
                VendorId = vendor.Id
            };

            _vendorStoreRepository.Insert(vendorStore);
        }
コード例 #6
0
        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);
        }
コード例 #7
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);
        }
コード例 #8
0
ファイル: ShippingServiceTests.cs プロジェクト: nvolpe/raver
        public new void SetUp()
        {
            _shippingSettings = new ShippingSettings();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames = new List<string>();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");

            _shippingMethodRepository = MockRepository.GenerateMock<IRepository<ShippingMethod>>();
            _deliveryDateRepository = MockRepository.GenerateMock<IRepository<DeliveryDate>>();
            _warehouseRepository = MockRepository.GenerateMock<IRepository<Warehouse>>();
            _logger = new NullLogger();
            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
            _checkoutAttributeParser = MockRepository.GenerateMock<ICheckoutAttributeParser>();

            var cacheManager = new NopNullCache();

            var pluginFinder = new PluginFinder();
            _productService = MockRepository.GenerateMock<IProductService>();

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

            _localizationService = MockRepository.GenerateMock<ILocalizationService>();
            _addressService = MockRepository.GenerateMock<IAddressService>();
            _genericAttributeService = MockRepository.GenerateMock<IGenericAttributeService>();

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

            _shoppingCartSettings = new ShoppingCartSettings();
            _shippingService = new ShippingService(_shippingMethodRepository,
                _deliveryDateRepository,
                _warehouseRepository,
                _logger,
                _productService,
                _productAttributeParser,
                _checkoutAttributeParser,
                _genericAttributeService,
                _localizationService,
                _addressService,
                _shippingSettings, 
                pluginFinder,
                _storeContext,
                _eventPublisher,
                _shoppingCartSettings,
                cacheManager);
        }
コード例 #9
0
        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",
                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.DisplayOrder.ShouldEqual(1);
        }
コード例 #10
0
ファイル: DateTimeHelperTests.cs プロジェクト: nvolpe/raver
        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);
        }
コード例 #11
0
 public void DeleteStore(Store store) {
     throw new NotImplementedException();
 }
コード例 #12
0
 public void InsertStore(Store store) {
     throw new NotImplementedException();
 }
コード例 #13
0
        public virtual void AddStoreTokens(IList<Token> tokens, Store store, EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            tokens.Add(new Token("Store.Name", store.GetLocalized(x => x.Name)));
            tokens.Add(new Token("Store.URL", store.Url, true));
            tokens.Add(new Token("Store.Email", emailAccount.Email));
            tokens.Add(new Token("Store.CompanyName", store.CompanyName));
            tokens.Add(new Token("Store.CompanyAddress", store.CompanyAddress));
            tokens.Add(new Token("Store.CompanyPhoneNumber", store.CompanyPhoneNumber));
            tokens.Add(new Token("Store.CompanyVat", store.CompanyVat));

            //event notification
            _eventPublisher.EntityTokensAdded(store, tokens);
        }
コード例 #14
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);
        }
コード例 #15
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.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
     if (defaultEmailAccount == null)
         defaultEmailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
     tokens.Add(new Token("Store.Email", defaultEmailAccount.Email));
 }
        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();
            var cacheManager = new NopNullCache();

            //price calculation service
            _discountService = MockRepository.GenerateMock<IDiscountService>();
            _categoryService = MockRepository.GenerateMock<ICategoryService>();
            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();

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

            _priceCalcService = new PriceCalculationService(_workContext, _discountService,
                _categoryService, _productAttributeParser, _shoppingCartSettings, _catalogSettings);

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

            _localizationService = MockRepository.GenerateMock<ILocalizationService>();

            //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,
                _checkoutAttributeParser,
                _genericAttributeService,
                _localizationService,
                _shippingSettings, pluginFinder,
                _eventPublisher, _shoppingCartSettings);

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

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

            //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, pluginFinder);

            _rewardPointsSettings = new RewardPointsSettings();

            _orderTotalCalcService = new OrderTotalCalculationService(_workContext, _storeContext,
                _priceCalcService, _taxService, _shippingService, _paymentService,
                _checkoutAttributeParser, _discountService, _giftCardService, _genericAttributeService,
                _taxSettings, _rewardPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);
        }
コード例 #17
0
        public ActionResult Register(VendorRegisterViewModel vrmodel, string returnUrl, bool captchaValid, FormCollection form)
        {
            if (vrmodel.CountryId == 0)
            {
                ModelState.AddModelError("CountryId", "This is a required field");
                if (vrmodel.StateProvinceId == 0)
                {
                    ModelState.AddModelError("StateProvinceId", "This is a required field");
                }                
                PrepareVendorRegisterModel(vrmodel);
                return View(vrmodel);
            }

            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();
            var context = new VendorMembershipContext(dataProviderSettings.DataConnectionString);
            using (var transaction = context.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        if (ValidateVendorModel(vrmodel))
                        {
                            Vendor vendor = new Vendor();
                            vendor.Name = vrmodel.AttentionTo;
                            vendor.Email = vrmodel.Email;
                            vendor.Active = true;
                            var vendorServiceCore = EngineContext.Current.Resolve<IVendorService>();
                            vendorServiceCore.InsertVendor(vendor);

                            var store = new Store
                            {
                                Name = vrmodel.ShopName,
                                Url = "http://" + vrmodel.ShopName + ".tameiontestsite.com/",
                                Hosts = vrmodel.ShopName + ".tameiontestsite.com,www." + vrmodel.ShopName + ".yourstore.com",
                                CompanyName = vrmodel.ShopName
                            };
                            _storeService.InsertStore(store);
                            vendor.setStore(store);

                            Address address = new Address
                            {
                                City = vrmodel.City,
                                CountryId = vrmodel.CountryId,
                                StateProvinceId = vrmodel.StateProvinceId,
                                PhoneNumber = vrmodel.PhoneNumber,
                                CreatedOnUtc = DateTime.UtcNow,
                                Email = vrmodel.Email,
                                ZipPostalCode = vrmodel.ZipPostalCode,
                                Address1 = vrmodel.Address1,
                                Address2 = vrmodel.Address2
                            };
                            _addressService.InsertAddress(address);
                            _vendorAddressService.InsertVendorAddress(new VendorAddress
                            {
                                VendorId = vendor.Id,
                                AddressId = address.Id,
                                AddressType = AddressType.Address
                            });

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.ShopName,
                                vrmodel.ShopName);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.Password,
                                vrmodel.Password);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.EnableGoogleAnalytics,
                                vrmodel.EnableGoogleAnalytics);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.GoogleAnalyticsAccountNumber,
                                vrmodel.GoogleAnalyticsAccountNumber);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.LogoImage,
                                vrmodel.LogoImage);

                            //_genericAttributeService.SaveAttribute(
                            //    vendor,
                            //    Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.PreferredShippingCarrier,
                            //    model.PreferredShippingCarrier);

                            _genericAttributeService.SaveAttribute(
                                vendor,
                                Nop.Plugin.Misc.VendorMembership.Domain.VendorAttributes.PreferredSubdomainName,
                                vrmodel.PreferredSubdomainName);

                            var productServiceCore = EngineContext.Current.Resolve<Nop.Services.Catalog.IProductService>();

                            foreach (var BusinessTypeId in vrmodel.BusinessTypeIds)
                            {
                                var vb = new VendorBusinessType();
                                //var vendorServiceExt = new VendorService(_vendorBusinessTypeRepository);
                                vb.VendorId = vendor.Id;
                                vb.BusinessTypeId = BusinessTypeId;
                                //vendorServiceExt.InsertVendorBusinessType(vb);
                            }

                            // create groupdeals
                            for (int i = 0; i < 10; i++)
                            {
                                int groupDealProductId = _groupDealService.CreateGroupDealProduct(vrmodel.ShopName + " register", 25m);
                                foreach (var categoryId in vrmodel.BusinessTypeIds)
                                {
                                    var productCategory = new ProductCategory
                                    {
                                        ProductId = groupDealProductId,
                                        CategoryId = categoryId,
                                        IsFeaturedProduct = false,
                                        DisplayOrder = 0
                                    };
                                    _categoryService.InsertProductCategory(productCategory);
                                }
                            }
                            vendor.SetHasPaidGroupDeals(true);

                            var model = new RegisterModel();
                            PrepareCustomerRegisterModel(model, false);
                            //enable newsletter by default
                            model.Newsletter = _customerSettings.NewsletterTickedByDefault;
                            model = vrmodel.ToRegisterModel(model);

                            // core code starts
                            //check whether registration is allowed
                            if (_customerSettings.UserRegistrationType == UserRegistrationType.Disabled)
                                return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled });

                            if (_workContext.CurrentCustomer.IsRegistered())
                            {
                                //Already registered customer. 
                                _authenticationService.SignOut();

                                //Save a new record
                                _workContext.CurrentCustomer = _customerService.InsertGuestCustomer();
                            }
                            var customer = _workContext.CurrentCustomer;

                            //add to 'Vendors' role
                            var vendorRole = _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Vendors);
                            if (vendorRole == null)
                                throw new NopException("'Vendors' role could not be loaded");
                            customer.CustomerRoles.Add(vendorRole);
                            customer.VendorId = vendor.Id;

                            //custom customer attributes
                            var customerAttributesXml = ParseCustomCustomerAttributes(form);
                            var customerAttributeWarnings = _customerAttributeParser.GetAttributeWarnings(customerAttributesXml);
                            foreach (var error in customerAttributeWarnings)
                            {
                                ModelState.AddModelError("", error);
                            }

                            //validate CAPTCHA
                            if (_captchaSettings.Enabled && _captchaSettings.ShowOnRegistrationPage && !captchaValid)
                            {
                                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
                            }


                            if (_customerSettings.UsernamesEnabled && model.Username != null)
                            {
                                model.Username = model.Username.Trim();
                            }

                            bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
                            var registrationRequest = new CustomerRegistrationRequest(customer, 
                                model.Email,
                                _customerSettings.UsernamesEnabled ? model.Username : model.Email, 
                                model.Password, 
                                _customerSettings.DefaultPasswordFormat, 
                                _storeContext.CurrentStore.Id,
                                isApproved);
                            var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
                            if (registrationResult.Success)
                            {
                                //properties
                                if (_dateTimeSettings.AllowCustomersToSetTimeZone)
                                {
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.TimeZoneId, model.TimeZoneId);
                                }
                                //VAT number
                                if (_taxSettings.EuVatEnabled)
                                {
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.VatNumber, model.VatNumber);

                                    string vatName;
                                    string vatAddress;
                                    var vatNumberStatus = _taxService.GetVatNumberStatus(model.VatNumber, out vatName, out vatAddress);
                                    _genericAttributeService.SaveAttribute(customer,
                                        SystemCustomerAttributeNames.VatNumberStatusId,
                                        (int)vatNumberStatus);
                                    //send VAT number admin notification
                                    if (!String.IsNullOrEmpty(model.VatNumber) && _taxSettings.EuVatEmailAdminWhenNewVatSubmitted)
                                        _workflowMessageService.SendNewVatSubmittedStoreOwnerNotification(customer, model.VatNumber, vatAddress, _localizationSettings.DefaultAdminLanguageId);

                                }

                                //form fields
                                if (_customerSettings.GenderEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Gender, model.Gender);
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.FirstName, model.FirstName);
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.LastName, model.LastName);
                                if (_customerSettings.DateOfBirthEnabled)
                                {
                                    DateTime? dateOfBirth = model.ParseDateOfBirth();
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.DateOfBirth, dateOfBirth);
                                }
                                if (_customerSettings.CompanyEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Company, model.Company);
                                if (_customerSettings.StreetAddressEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress, model.StreetAddress);
                                if (_customerSettings.StreetAddress2Enabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StreetAddress2, model.StreetAddress2);
                                if (_customerSettings.ZipPostalCodeEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.ZipPostalCode, model.ZipPostalCode);
                                if (_customerSettings.CityEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.City, model.City);
                                if (_customerSettings.CountryEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CountryId, model.CountryId);
                                if (_customerSettings.CountryEnabled && _customerSettings.StateProvinceEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.StateProvinceId, model.StateProvinceId);
                                if (_customerSettings.PhoneEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Phone, model.Phone);
                                if (_customerSettings.FaxEnabled)
                                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.Fax, model.Fax);

                                //newsletter
                                if (_customerSettings.NewsletterEnabled)
                                {
                                    //save newsletter value
                                    var newsletter = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(model.Email, _storeContext.CurrentStore.Id);
                                    if (newsletter != null)
                                    {
                                        if (model.Newsletter)
                                        {
                                            newsletter.Active = true;
                                            _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsletter);
                                        }
                                        //else
                                        //{
                                        //When registering, not checking the newsletter check box should not take an existing email address off of the subscription list.
                                        //_newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsletter);
                                        //}
                                    }
                                    else
                                    {
                                        if (model.Newsletter)
                                        {
                                            _newsLetterSubscriptionService.InsertNewsLetterSubscription(new NewsLetterSubscription
                                            {
                                                NewsLetterSubscriptionGuid = Guid.NewGuid(),
                                                Email = model.Email,
                                                Active = true,
                                                StoreId = _storeContext.CurrentStore.Id,
                                                CreatedOnUtc = DateTime.UtcNow
                                            });
                                        }
                                    }
                                }

                                //save customer attributes
                                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CustomCustomerAttributes, customerAttributesXml);

                                //login customer now
                                if (isApproved)
                                    _authenticationService.SignIn(customer, true);

                                //associated with external account (if possible)
                                TryAssociateAccountWithExternalAccount(customer);

                                //insert default address (if possible)
                                var defaultAddress = new Address
                                {
                                    FirstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName),
                                    LastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName),
                                    Email = customer.Email,
                                    Company = customer.GetAttribute<string>(SystemCustomerAttributeNames.Company),
                                    CountryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) > 0 ?
                                        (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId) : null,
                                    StateProvinceId = customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) > 0 ?
                                        (int?)customer.GetAttribute<int>(SystemCustomerAttributeNames.StateProvinceId) : null,
                                    City = customer.GetAttribute<string>(SystemCustomerAttributeNames.City),
                                    Address1 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress),
                                    Address2 = customer.GetAttribute<string>(SystemCustomerAttributeNames.StreetAddress2),
                                    ZipPostalCode = customer.GetAttribute<string>(SystemCustomerAttributeNames.ZipPostalCode),
                                    PhoneNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Phone),
                                    FaxNumber = customer.GetAttribute<string>(SystemCustomerAttributeNames.Fax),
                                    CreatedOnUtc = customer.CreatedOnUtc
                                };
                                if (this._addressService.IsAddressValid(defaultAddress))
                                {
                                    //some validation
                                    if (defaultAddress.CountryId == 0)
                                        defaultAddress.CountryId = null;
                                    if (defaultAddress.StateProvinceId == 0)
                                        defaultAddress.StateProvinceId = null;
                                    //set default address
                                    customer.Addresses.Add(defaultAddress);
                                    customer.BillingAddress = defaultAddress;
                                    customer.ShippingAddress = defaultAddress;
                                    _customerService.UpdateCustomer(customer);
                                }

                                //notifications
                                if (_customerSettings.NotifyNewCustomerRegistration)
                                    _workflowMessageService.SendCustomerRegisteredNotificationMessage(customer, _localizationSettings.DefaultAdminLanguageId);

                                switch (_customerSettings.UserRegistrationType)
                                {
                                    case UserRegistrationType.EmailValidation:
                                        {
                                            //email validation message
                                            _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
                                            _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                                            //result
                                            //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation });
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    case UserRegistrationType.AdminApproval:
                                        {
                                            //return RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval });
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    case UserRegistrationType.Standard:
                                        {
                                            //send customer welcome message
                                            _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                                            var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                                            if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                                                redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                                            //return Redirect(redirectUrl);
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                    default:
                                        {
                                            return RedirectToAction("Index", "Orders", new { area = "Vendor" });
                                        }
                                }
                            }

                            //errors
                            foreach (var error in registrationResult.Errors)
                                ModelState.AddModelError("", error);
                        }
                    }
                    transaction.Commit();

                    //If we got this far, something failed, redisplay form
                    PrepareVendorRegisterModel(vrmodel);
                    return View(vrmodel);
                }
                catch(Exception e)
                {
                    transaction.Rollback();
                    ModelState.AddModelError("", e.Message);
                    PrepareVendorRegisterModel(vrmodel);
                    return View(vrmodel);
                }
            }
        }
コード例 #18
0
        public virtual void AddStoreTokens(IList<Token> tokens, Store store, EmailAccount emailAccount)
        {
            if (emailAccount == null)
                throw new ArgumentNullException("emailAccount");

            tokens.Add(new Token("Store.Name", store.GetLocalized(x => x.Name)));
            tokens.Add(new Token("Store.URL", store.Url, true));
            tokens.Add(new Token("Store.Email", emailAccount.Email));
            tokens.Add(new Token("Store.CompanyName", store.CompanyName));
            tokens.Add(new Token("Store.CompanyAddress", store.CompanyAddress));
            tokens.Add(new Token("Store.CompanyPhoneNumber", store.CompanyPhoneNumber));
            tokens.Add(new Token("Store.CompanyVat", store.CompanyVat));
            tokens.Add(new Token("Twitter.URL", _storeInformationSettings.TwitterLink));
            tokens.Add(new Token("Facebook.URL", _storeInformationSettings.FacebookLink));
            tokens.Add(new Token("YouTube.URL", _storeInformationSettings.YoutubeLink));
            tokens.Add(new Token("GooglePlus.URL", _storeInformationSettings.GooglePlusLink));

            //event notification
            _eventPublisher.EntityTokensAdded(store, tokens);
        }
コード例 #19
0
        /// <summary>
        /// Generate a feed
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="store">Store</param>
        /// <returns>Generated feed</returns>
        public void GenerateFeed(Stream stream, Store store)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            if (store == null)
                throw new ArgumentNullException("store");

            const string googleBaseNamespace = "http://base.google.com/ns/1.0";

            var settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8
            };
            using (var writer = XmlWriter.Create(stream, settings))
            {
                //Generate feed according to the following specs: http://www.google.com/support/merchants/bin/answer.py?answer=188494&expand=GB
                writer.WriteStartDocument();
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns", "g", null, googleBaseNamespace);
                writer.WriteStartElement("channel");
                writer.WriteElementString("title", "Google Base feed");
                writer.WriteElementString("link", "http://base.google.com/base/");
                writer.WriteElementString("description", "Information about products");

                var products = _productService.SearchProducts(storeId: store.Id);
                foreach (var product in products)
                {
                    var productVariants = _productService.GetProductVariantsByProductId(product.Id);

                    foreach (var productVariant in productVariants)
                    {
                        writer.WriteStartElement("item");

                        #region Basic Product Information

                        //id [id]- An identifier of the item
                        writer.WriteElementString("g", "id", googleBaseNamespace, productVariant.Id.ToString());

                        //title [title] - Title of the item
                        writer.WriteStartElement("title");
                        var title = productVariant.FullProductName;
                        //title should be not longer than 70 characters
                        if (title.Length > 70)
                            title = title.Substring(0, 70);
                        writer.WriteCData(title);
                        writer.WriteEndElement(); // title

                        //description [description] - Description of the item
                        writer.WriteStartElement("description");
                        string description = productVariant.Description;
                        if (String.IsNullOrEmpty(description))
                            description = product.FullDescription;
                        if (String.IsNullOrEmpty(description))
                            description = product.ShortDescription;
                        if (String.IsNullOrEmpty(description))
                            description = product.Name;
                        if (String.IsNullOrEmpty(description))
                            description = productVariant.FullProductName; //description is required
                        //resolving character encoding issues in your data feed
                        description = StripInvalidChars(description, true);
                        writer.WriteCData(description);
                        writer.WriteEndElement(); // description

                        //google product category [google_product_category] - Google's category of the item
                        //the category of the product according to Google’s product taxonomy. http://www.google.com/support/merchants/bin/answer.py?answer=160081
                        string googleProductCategory = "";
                        var googleProduct = _googleService.GetByProductVariantId(productVariant.Id);
                        if (googleProduct != null)
                            googleProductCategory = googleProduct.Taxonomy;
                        if (String.IsNullOrEmpty(googleProductCategory))
                            googleProductCategory = _froogleSettings.DefaultGoogleCategory;
                        if (String.IsNullOrEmpty(googleProductCategory))
                            throw new NopException("Default Google category is not set");
                        writer.WriteElementString("g", "google_product_category", googleBaseNamespace,
                                                  HttpUtility.HtmlEncode(googleProductCategory));

                        //product type [product_type] - Your category of the item
                        var defaultProductCategory = _categoryService.GetProductCategoriesByProductId(product.Id).FirstOrDefault();
                        if (defaultProductCategory != null)
                        {
                            var categoryBreadCrumb = GetCategoryBreadCrumb(defaultProductCategory.Category);
                            string yourProductCategory = "";
                            for (int i = 0; i < categoryBreadCrumb.Count; i++)
                            {
                                var cat = categoryBreadCrumb[i];
                                yourProductCategory = yourProductCategory + cat.Name;
                                if (i != categoryBreadCrumb.Count - 1)
                                    yourProductCategory = yourProductCategory + " > ";
                            }
                            if (!String.IsNullOrEmpty((yourProductCategory)))
                                writer.WriteElementString("g", "product_type", googleBaseNamespace,
                                                          HttpUtility.HtmlEncode(yourProductCategory));
                        }

                        //link [link] - URL directly linking to your item's page on your website
                        var productUrl = string.Format("{0}{1}", store.Url, product.GetSeName(_workContext.WorkingLanguage.Id));
                        writer.WriteElementString("link", productUrl);

                        //image link [image_link] - URL of an image of the item
                        string imageUrl;
                        var picture = _pictureService.GetPictureById(productVariant.PictureId);
                        if (picture == null)
                            picture = _pictureService.GetPicturesByProductId(product.Id, 1).FirstOrDefault();

                        if (picture != null)
                            imageUrl = _pictureService.GetPictureUrl(picture, _froogleSettings.ProductPictureSize, storeLocation: store.Url);
                        else
                            imageUrl = _pictureService.GetDefaultPictureUrl(_froogleSettings.ProductPictureSize, storeLocation: store.Url);

                        writer.WriteElementString("g", "image_link", googleBaseNamespace, imageUrl);

                        //condition [condition] - Condition or state of the item
                        writer.WriteElementString("g", "condition", googleBaseNamespace, "new");

                        #endregion

                        #region Availability & Price

                        //availability [availability] - Availability status of the item
                        string availability = "in stock"; //in stock by default
                        if (productVariant.ManageInventoryMethod == ManageInventoryMethod.ManageStock
                            && productVariant.StockQuantity <= 0)
                        {
                            switch (productVariant.BackorderMode)
                            {
                                case BackorderMode.NoBackorders:
                                    {
                                        availability = "out of stock";
                                    }
                                    break;
                                case BackorderMode.AllowQtyBelow0:
                                case BackorderMode.AllowQtyBelow0AndNotifyCustomer:
                                    {
                                        availability = "available for order";
                                        //availability = "preorder";
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        writer.WriteElementString("g", "availability", googleBaseNamespace, availability);

                        //price [price] - Price of the item
                        var currency = GetUsedCurrency();
                        decimal price = _currencyService.ConvertFromPrimaryStoreCurrency(productVariant.Price, currency);
                        writer.WriteElementString("g", "price", googleBaseNamespace,
                                                  price.ToString(new CultureInfo("en-US", false).NumberFormat) + " " +
                                                  currency.CurrencyCode);

                        #endregion

                        #region Unique Product Identifiers

                        /* Unique product identifiers such as UPC, EAN, JAN or ISBN allow us to show your listing on the appropriate product page. If you don't provide the required unique product identifiers, your store may not appear on product pages, and all your items may be removed from Product Search.
                         * We require unique product identifiers for all products - except for custom made goods. For apparel, you must submit the 'brand' attribute. For media (such as books, movies, music and video games), you must submit the 'gtin' attribute. In all cases, we recommend you submit all three attributes.
                         * You need to submit at least two attributes of 'brand', 'gtin' and 'mpn', but we recommend that you submit all three if available. For media (such as books, movies, music and video games), you must submit the 'gtin' attribute, but we recommend that you include 'brand' and 'mpn' if available.
                        */

                        //GTIN [gtin] - GTIN
                        var gtin = productVariant.Gtin;
                        if (!String.IsNullOrEmpty(gtin))
                        {
                            writer.WriteStartElement("g", "gtin", googleBaseNamespace);
                            writer.WriteCData(gtin);
                            writer.WriteFullEndElement(); // g:gtin
                        }

                        //brand [brand] - Brand of the item
                        var defaultManufacturer =
                            _manufacturerService.GetProductManufacturersByProductId((product.Id)).FirstOrDefault();
                        if (defaultManufacturer != null)
                        {
                            writer.WriteStartElement("g", "brand", googleBaseNamespace);
                            writer.WriteCData(defaultManufacturer.Manufacturer.Name);
                            writer.WriteFullEndElement(); // g:brand
                        }

                        //mpn [mpn] - Manufacturer Part Number (MPN) of the item
                        var mpn = productVariant.ManufacturerPartNumber;
                        if (!String.IsNullOrEmpty(mpn))
                        {
                            writer.WriteStartElement("g", "mpn", googleBaseNamespace);
                            writer.WriteCData(mpn);
                            writer.WriteFullEndElement(); // g:mpn
                        }

                        #endregion

                        #region Apparel Products

                        /* Apparel includes all products that fall under 'Apparel & Accessories' (including all sub-categories)
                         * in Google’s product taxonomy.
                        */

                        //gender [gender] - Gender of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Gender))
                        {
                            writer.WriteStartElement("g", "gender", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Gender);
                            writer.WriteFullEndElement(); // g:gender
                        }

                        //age group [age_group] - Target age group of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.AgeGroup))
                        {
                            writer.WriteStartElement("g", "age_group", googleBaseNamespace);
                            writer.WriteCData(googleProduct.AgeGroup);
                            writer.WriteFullEndElement(); // g:age_group
                        }

                        //color [color] - Color of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Color))
                        {
                            writer.WriteStartElement("g", "color", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Color);
                            writer.WriteFullEndElement(); // g:color
                        }

                        //size [size] - Size of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Size))
                        {
                            writer.WriteStartElement("g", "size", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Size);
                            writer.WriteFullEndElement(); // g:size
                        }

                        #endregion

                        #region Tax & Shipping

                        //tax [tax]
                        //The tax attribute is an item-level override for merchant-level tax settings as defined in your Google Merchant Center account. This attribute is only accepted in the US, if your feed targets a country outside of the US, please do not use this attribute.
                        //IMPORTANT NOTE: Set tax in your Google Merchant Center account settings

                        //IMPORTANT NOTE: Set shipping in your Google Merchant Center account settings

                        //shipping weight [shipping_weight] - Weight of the item for shipping
                        //We accept only the following units of weight: lb, oz, g, kg.
                        if (_froogleSettings.PassShippingInfo)
                        {
                            var weightName = "kg";
                            var shippingWeight = productVariant.Weight;
                            switch (_measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword)
                            {
                                case "ounce":
                                    weightName = "oz";
                                    break;
                                case "lb":
                                    weightName = "lb";
                                    break;
                                case "grams":
                                    weightName = "g";
                                    break;
                                case "kg":
                                    weightName = "kg";
                                    break;
                                default:
                                    //unknown weight
                                    weightName = "kg";
                                    break;
                            }
                            writer.WriteElementString("g", "shipping_weight", googleBaseNamespace, string.Format(CultureInfo.InvariantCulture, "{0} {1}", shippingWeight.ToString(new CultureInfo("en-US", false).NumberFormat), weightName));
                        }

                        #endregion

                        writer.WriteElementString("g", "expiration_date", googleBaseNamespace, DateTime.Now.AddDays(28).ToString("yyyy-MM-dd"));

                        writer.WriteEndElement(); // item
                    }
                }

                writer.WriteEndElement(); // channel
                writer.WriteEndElement(); // rss
                writer.WriteEndDocument();
            }
        }
コード例 #20
0
 /// <summary>
 /// Generate a static file for froogle
 /// </summary>
 /// <param name="store">Store</param>
 public virtual void GenerateStaticFile(Store store)
 {
     if (store == null)
         throw new ArgumentNullException("store");
     string filePath = System.IO.Path.Combine(HttpRuntime.AppDomainAppPath, "content\\files\\exportimport", store.Id + "-" + _froogleSettings.StaticFileName);
     using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
     {
         GenerateFeed(fs, store);
     }
 }
コード例 #21
0
 public static Store ToEntity(this StoreModel model, Store destination)
 {
     return Mapper.Map(model, destination);
 }
コード例 #22
0
        /// <summary>
        /// Generate a feed
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="store">Store</param>
        /// <returns>Generated feed</returns>
        public void GenerateFeed(Stream stream, Store store)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            if (store == null)
                throw new ArgumentNullException("store");

            const string googleBaseNamespace = "http://base.google.com/ns/1.0";

            var settings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8
            };
            
            //language
            var languageId = 0;
            var languages = _languageService.GetAllLanguages(storeId: store.Id);
            //if we have only one language, let's use it
            if (languages.Count == 1)
            {
                //let's use the first one
                var language = languages.FirstOrDefault();
                languageId = language != null ? language.Id : 0;
            }
            //otherwise, use the current one
            if (languageId == 0)
                languageId = _workContext.WorkingLanguage.Id;

            //we load all google products here using one SQL request (performance optimization)
            var allGoogleProducts = _googleService.GetAll();

            using (var writer = XmlWriter.Create(stream, settings))
            {
                //Generate feed according to the following specs: http://www.google.com/support/merchants/bin/answer.py?answer=188494&expand=GB
                writer.WriteStartDocument();
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                writer.WriteAttributeString("xmlns", "g", null, googleBaseNamespace);
                writer.WriteStartElement("channel");
                writer.WriteElementString("title", "Google Base feed");
                writer.WriteElementString("link", "http://base.google.com/base/");
                writer.WriteElementString("description", "Information about products");


                var products1 = _productService.SearchProducts(storeId: store.Id, visibleIndividuallyOnly: true);
                foreach (var product1 in products1)
                {
                    var productsToProcess = new List<Product>();
                    switch (product1.ProductType)
                    {
                        case ProductType.SimpleProduct:
                            {
                                //simple product doesn't have child products
                                productsToProcess.Add(product1);
                            }
                            break;
                        case ProductType.GroupedProduct:
                            {
                                //grouped products could have several child products
                                var associatedProducts = _productService.GetAssociatedProducts(product1.Id, store.Id);
                                productsToProcess.AddRange(associatedProducts);
                            }
                            break;
                        default:
                            continue;
                    }
                    foreach (var product in productsToProcess)
                    {
                        writer.WriteStartElement("item");

                        #region Basic Product Information

                        //id [id]- An identifier of the item
                        writer.WriteElementString("g", "id", googleBaseNamespace, product.Id.ToString());

                        //title [title] - Title of the item
                        writer.WriteStartElement("title");
                        var title = product.GetLocalized(x => x.Name, languageId);
                        //title should be not longer than 70 characters
                        if (title.Length > 70)
                            title = title.Substring(0, 70);
                        writer.WriteCData(title);
                        writer.WriteEndElement(); // title

                        //description [description] - Description of the item
                        writer.WriteStartElement("description");
                        string description = product.GetLocalized(x => x.FullDescription, languageId);
                        if (String.IsNullOrEmpty(description))
                            description = product.GetLocalized(x => x.ShortDescription, languageId);
                        if (String.IsNullOrEmpty(description))
                            description = product.GetLocalized(x => x.Name, languageId); //description is required
                        //resolving character encoding issues in your data feed
                        description = StripInvalidChars(description, true);
                        writer.WriteCData(description);
                        writer.WriteEndElement(); // description



                        //google product category [google_product_category] - Google's category of the item
                        //the category of the product according to Google’s product taxonomy. http://www.google.com/support/merchants/bin/answer.py?answer=160081
                        string googleProductCategory = "";
                        //var googleProduct = _googleService.GetByProductId(product.Id);
                        var googleProduct = allGoogleProducts.FirstOrDefault(x => x.ProductId == product.Id);
                        if (googleProduct != null)
                            googleProductCategory = googleProduct.Taxonomy;
                        if (String.IsNullOrEmpty(googleProductCategory))
                            googleProductCategory = _froogleSettings.DefaultGoogleCategory;
                        if (String.IsNullOrEmpty(googleProductCategory))
                            throw new NopException("Default Google category is not set");
                        writer.WriteStartElement("g", "google_product_category", googleBaseNamespace);
                        writer.WriteCData(googleProductCategory);
                        writer.WriteFullEndElement(); // g:google_product_category

                        //product type [product_type] - Your category of the item
                        var defaultProductCategory = _categoryService
                            .GetProductCategoriesByProductId(product.Id, store.Id)
                            .FirstOrDefault();
                        if (defaultProductCategory != null)
                        {
                            //TODO localize categories
                            var category = defaultProductCategory.Category
                                .GetFormattedBreadCrumb(_categoryService, separator: ">", languageId: languageId);
                            if (!String.IsNullOrEmpty((category)))
                            {
                                writer.WriteStartElement("g", "product_type", googleBaseNamespace);
                                writer.WriteCData(category);
                                writer.WriteFullEndElement(); // g:product_type
                            }
                        }

                        //link [link] - URL directly linking to your item's page on your website
                        var productUrl = string.Format("{0}{1}", store.Url, product.GetSeName(languageId));
                        writer.WriteElementString("link", productUrl);

                        //image link [image_link] - URL of an image of the item
                        //additional images [additional_image_link]
                        //up to 10 pictures
                        const int maximumPictures = 10;
                        var pictures = _pictureService.GetPicturesByProductId(product.Id, maximumPictures);
                        for (int i = 0; i < pictures.Count; i++)
                        {
                            var picture = pictures[i];
                            var imageUrl = _pictureService.GetPictureUrl(picture,
                                _froogleSettings.ProductPictureSize,
                                storeLocation: store.Url);

                            if (i == 0)
                            {
                                //default image
                                writer.WriteElementString("g", "image_link", googleBaseNamespace, imageUrl);
                            }
                            else
                            {
                                //additional image
                                writer.WriteElementString("g", "additional_image_link", googleBaseNamespace, imageUrl);
                            }
                        }
                        if (pictures.Count == 0)
                        {
                            //no picture? submit a default one
                            var imageUrl = _pictureService.GetDefaultPictureUrl(_froogleSettings.ProductPictureSize, storeLocation: store.Url);
                            writer.WriteElementString("g", "image_link", googleBaseNamespace, imageUrl);
                        }

                        //condition [condition] - Condition or state of the item
                        writer.WriteElementString("g", "condition", googleBaseNamespace, "new");

                        writer.WriteElementString("g", "expiration_date", googleBaseNamespace, DateTime.Now.AddDays(_froogleSettings.ExpirationNumberOfDays).ToString("yyyy-MM-dd"));

                        #endregion

                        #region Availability & Price

                        //availability [availability] - Availability status of the item
                        string availability = "in stock"; //in stock by default
                        if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock
                            && product.BackorderMode == BackorderMode.NoBackorders
                            && product.GetTotalStockQuantity() <= 0)
                        {
                            availability = "out of stock";
                        }
                        //uncomment th code below in order to support "preorder" value for "availability"
                        //if (product.AvailableForPreOrder &&
                        //    (!product.PreOrderAvailabilityStartDateTimeUtc.HasValue || 
                        //    product.PreOrderAvailabilityStartDateTimeUtc.Value >= DateTime.UtcNow))
                        //{
                        //    availability = "preorder";
                        //}
                        writer.WriteElementString("g", "availability", googleBaseNamespace, availability);

                        //price [price] - Price of the item
                        var currency = GetUsedCurrency();
                        decimal finalPriceBase;
                        if (_froogleSettings.PricesConsiderPromotions)
                        {
                            //calculate for the maximum quantity (in case if we have tier prices)
                            decimal minPossiblePrice = _priceCalculationService.GetFinalPrice(product,
                                _workContext.CurrentCustomer, decimal.Zero, true, int.MaxValue);
                            decimal taxRate;
                            finalPriceBase = _taxService.GetProductPrice(product, minPossiblePrice, out taxRate);

                        }
                        else
                        {
                            finalPriceBase = product.Price;
                        }
                        decimal price = _currencyService.ConvertFromPrimaryStoreCurrency(finalPriceBase, currency);
                        writer.WriteElementString("g", "price", googleBaseNamespace,
                                                  price.ToString(new CultureInfo("en-US", false).NumberFormat) + " " +
                                                  currency.CurrencyCode);

                        #endregion

                        #region Unique Product Identifiers

                        /* Unique product identifiers such as UPC, EAN, JAN or ISBN allow us to show your listing on the appropriate product page. If you don't provide the required unique product identifiers, your store may not appear on product pages, and all your items may be removed from Product Search.
                         * We require unique product identifiers for all products - except for custom made goods. For apparel, you must submit the 'brand' attribute. For media (such as books, movies, music and video games), you must submit the 'gtin' attribute. In all cases, we recommend you submit all three attributes.
                         * You need to submit at least two attributes of 'brand', 'gtin' and 'mpn', but we recommend that you submit all three if available. For media (such as books, movies, music and video games), you must submit the 'gtin' attribute, but we recommend that you include 'brand' and 'mpn' if available.
                        */

                        //GTIN [gtin] - GTIN
                        var gtin = product.Gtin;
                        if (!String.IsNullOrEmpty(gtin))
                        {
                            writer.WriteStartElement("g", "gtin", googleBaseNamespace);
                            writer.WriteCData(gtin);
                            writer.WriteFullEndElement(); // g:gtin
                        }

                        //brand [brand] - Brand of the item
                        var defaultManufacturer =
                            _manufacturerService.GetProductManufacturersByProductId((product.Id)).FirstOrDefault();
                        if (defaultManufacturer != null)
                        {
                            writer.WriteStartElement("g", "brand", googleBaseNamespace);
                            writer.WriteCData(defaultManufacturer.Manufacturer.Name);
                            writer.WriteFullEndElement(); // g:brand
                        }


                        //mpn [mpn] - Manufacturer Part Number (MPN) of the item
                        var mpn = product.ManufacturerPartNumber;
                        if (!String.IsNullOrEmpty(mpn))
                        {
                            writer.WriteStartElement("g", "mpn", googleBaseNamespace);
                            writer.WriteCData(mpn);
                            writer.WriteFullEndElement(); // g:mpn
                        }

                        //identifier exists [identifier_exists] - Submit custom goods
                        if (googleProduct != null && googleProduct.CustomGoods)
                        {
                            writer.WriteElementString("g", "identifier_exists", googleBaseNamespace, "FALSE");
                        }

                        #endregion

                        #region Apparel Products

                        /* Apparel includes all products that fall under 'Apparel & Accessories' (including all sub-categories)
                         * in Google’s product taxonomy.
                        */

                        //gender [gender] - Gender of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Gender))
                        {
                            writer.WriteStartElement("g", "gender", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Gender);
                            writer.WriteFullEndElement(); // g:gender
                        }

                        //age group [age_group] - Target age group of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.AgeGroup))
                        {
                            writer.WriteStartElement("g", "age_group", googleBaseNamespace);
                            writer.WriteCData(googleProduct.AgeGroup);
                            writer.WriteFullEndElement(); // g:age_group
                        }

                        //color [color] - Color of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Color))
                        {
                            writer.WriteStartElement("g", "color", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Color);
                            writer.WriteFullEndElement(); // g:color
                        }

                        //size [size] - Size of the item
                        if (googleProduct != null && !String.IsNullOrEmpty(googleProduct.Size))
                        {
                            writer.WriteStartElement("g", "size", googleBaseNamespace);
                            writer.WriteCData(googleProduct.Size);
                            writer.WriteFullEndElement(); // g:size
                        }

                        #endregion

                        #region Tax & Shipping

                        //tax [tax]
                        //The tax attribute is an item-level override for merchant-level tax settings as defined in your Google Merchant Center account. This attribute is only accepted in the US, if your feed targets a country outside of the US, please do not use this attribute.
                        //IMPORTANT NOTE: Set tax in your Google Merchant Center account settings

                        //IMPORTANT NOTE: Set shipping in your Google Merchant Center account settings

                        //shipping weight [shipping_weight] - Weight of the item for shipping
                        //We accept only the following units of weight: lb, oz, g, kg.
                        if (_froogleSettings.PassShippingInfoWeight)
                        {
                            string weightName;
                            var shippingWeight = product.Weight;
                            var weightSystemName = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword;
                            switch (weightSystemName)
                            {
                                case "ounce":
                                    weightName = "oz";
                                    break;
                                case "lb":
                                    weightName = "lb";
                                    break;
                                case "grams":
                                    weightName = "g";
                                    break;
                                case "kg":
                                    weightName = "kg";
                                    break;
                                default:
                                    //unknown weight 
                                    throw new Exception("Not supported weight. Google accepts the following units: lb, oz, g, kg.");
                            }
                            writer.WriteElementString("g", "shipping_weight", googleBaseNamespace, string.Format(CultureInfo.InvariantCulture, "{0} {1}", shippingWeight.ToString(new CultureInfo("en-US", false).NumberFormat), weightName));
                        }

                        //shipping length [shipping_length] - Length of the item for shipping
                        //shipping width [shipping_width] - Width of the item for shipping
                        //shipping height [shipping_height] - Height of the item for shipping
                        //We accept only the following units of length: in, cm
                        if (_froogleSettings.PassShippingInfoDimensions)
                        {
                            string dimensionName;
                            var length = product.Length;
                            var width = product.Width;
                            var height = product.Height;
                            var dimensionSystemName = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId).SystemKeyword;
                            switch (dimensionSystemName)
                            {
                                case "inches":
                                    dimensionName = "in";
                                    break;
                                    //TODO support other dimensions (convert to cm)
                                default:
                                    //unknown dimension 
                                    throw new Exception("Not supported dimension. Google accepts the following units: in, cm.");
                            }
                            writer.WriteElementString("g", "shipping_length", googleBaseNamespace, string.Format(CultureInfo.InvariantCulture, "{0} {1}", length.ToString(new CultureInfo("en-US", false).NumberFormat), dimensionName));
                            writer.WriteElementString("g", "shipping_width", googleBaseNamespace, string.Format(CultureInfo.InvariantCulture, "{0} {1}", width.ToString(new CultureInfo("en-US", false).NumberFormat), dimensionName));
                            writer.WriteElementString("g", "shipping_height", googleBaseNamespace, string.Format(CultureInfo.InvariantCulture, "{0} {1}", height.ToString(new CultureInfo("en-US", false).NumberFormat), dimensionName));
                        }

                        #endregion

                        writer.WriteEndElement(); // item
                    }
                }

                writer.WriteEndElement(); // channel
                writer.WriteEndElement(); // rss
                writer.WriteEndDocument();
            }
        }
コード例 #23
0
        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();

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

            var cacheManager = new NopNullCache();

            _productService = MockRepository.GenerateMock<IProductService>();

            //price calculation service
            _discountService = MockRepository.GenerateMock<IDiscountService>();
            _categoryService = MockRepository.GenerateMock<ICategoryService>();
            _productAttributeParser = MockRepository.GenerateMock<IProductAttributeParser>();
            _priceCalcService = new PriceCalculationService(_workContext, _storeContext,
                _discountService, _categoryService,
                _productAttributeParser, _productService,
                cacheManager, _shoppingCartSettings, _catalogSettings);

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

            _localizationService = MockRepository.GenerateMock<ILocalizationService>();

            //shipping
            _shippingSettings = new ShippingSettings();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames = new List<string>();
            _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add("FixedRateTestShippingRateComputationMethod");
            _shippingMethodRepository = MockRepository.GenerateMock<IRepository<ShippingMethod>>();
            _deliveryDateRepository = MockRepository.GenerateMock<IRepository<DeliveryDate>>();
            _warehouseRepository = MockRepository.GenerateMock<IRepository<Warehouse>>();
            _logger = new NullLogger();
            _shippingService = new ShippingService(_shippingMethodRepository,
                _deliveryDateRepository,
                _warehouseRepository,
                _logger,
                _productService,
                _productAttributeParser,
                _checkoutAttributeParser,
                _genericAttributeService,
                _localizationService,
                _addressService,
                _shippingSettings,
                pluginFinder,
                _storeContext,
                _eventPublisher,
                _shoppingCartSettings,
                cacheManager);
            _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, pluginFinder);

            _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>();
            _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>();
            _vendorService = MockRepository.GenerateMock<IVendorService>();
            _pdfService = MockRepository.GenerateMock<IPdfService>();

            _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,
                _workflowMessageService, _vendorService,
                _customerActivityService, _currencyService, _affiliateService,
                _eventPublisher,_pdfService, _paymentSettings, _rewardPointsSettings,
                _orderSettings, _taxSettings, _localizationSettings,
                _currencySettings);
        }
コード例 #24
0
 protected virtual List<LocalizedProperty> UpdateAttributeLocales(Store store, StoreModel model)
 {
     List<LocalizedProperty> localized = new List<LocalizedProperty>();
     foreach (var local in model.Locales)
     {
         localized.Add(new LocalizedProperty()
         {
             LanguageId = local.LanguageId,
             LocaleKey = "Name",
             LocaleValue = local.Name
         });
     }
     return localized;
 }
コード例 #25
0
        public virtual void AddStoreTokens(IList<Token> tokens, Store store)
        {
            tokens.Add(new Token("Store.Name", store.GetLocalized(x => x.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.Email", defaultEmailAccount.Email));

            //event notification
            _eventPublisher.EntityTokensAdded(store, tokens);
        }