Example #1
0
        /// <summary>
        /// The add merchello data.
        /// </summary>
        /// <returns>
        /// The <see cref="IProduct"/>.
        /// </returns>
        private IProduct AddMerchelloData()
        {
            var merchelloServices = MerchelloContext.Current.Services;

            LogHelper.Info <BazaarDataInstaller>("Updating Default Warehouse Address");
            var warehouse = merchelloServices.WarehouseService.GetDefaultWarehouse();

            warehouse.Name        = "Merchello";
            warehouse.Address1    = "114 W. Magnolia St.";
            warehouse.Address2    = "Suite 300";
            warehouse.Locality    = "Bellingham";
            warehouse.Region      = "WA";
            warehouse.PostalCode  = "98225";
            warehouse.CountryCode = "US";
            merchelloServices.WarehouseService.Save(warehouse);

            LogHelper.Info <BazaarDataInstaller>("Adding example shipping data");
            var catalog = warehouse.WarehouseCatalogs.FirstOrDefault(x => x.Key == Core.Constants.DefaultKeys.Warehouse.DefaultWarehouseCatalogKey);
            var country = merchelloServices.StoreSettingService.GetCountryByCode("US");

            // The follow is internal to Merchello and not exposed in the public API
            var shipCountry = ((Core.Services.ServiceContext)merchelloServices).ShipCountryService.GetShipCountryByCountryCode(catalog.Key, "US");

            // Add the ship country
            if (shipCountry == null || shipCountry.CountryCode == "ELSE")
            {
                shipCountry = new ShipCountry(catalog.Key, country);
                ((Core.Services.ServiceContext)merchelloServices).ShipCountryService.Save(shipCountry);
            }

            // Associate the fixed rate Shipping Provider to the ShipCountry
            var key = Core.Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);
            var gatewayShipMethod = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, shipCountry, "Ground");

            // Add rate adjustments for Hawaii and Alaska
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustment     = 3M;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustment     = 2.5M;

            // Add a few of rate tiers to the rate table.
            gatewayShipMethod.RateTable.AddRow(0, 10, 5);
            gatewayShipMethod.RateTable.AddRow(10, 15, 10);
            gatewayShipMethod.RateTable.AddRow(15, 25, 25);
            gatewayShipMethod.RateTable.AddRow(25, 10000, 100);
            rateTableProvider.SaveShippingGatewayMethod(gatewayShipMethod);

            LogHelper.Info <BazaarDataInstaller>("Adding an example product");
            var product = merchelloServices.ProductService.CreateProduct("Bar of Soap", "soapbar", 5M);

            product.Shippable      = true;
            product.Taxable        = true;
            product.TrackInventory = false;
            product.Available      = true;
            product.Weight         = 1M;
            product.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(product, false);
            return(product);
        }
Example #2
0
        public ShipCountryDisplay NewShipCountry(Guid catalogKey, string countryCode)
        {
            ShipCountry newShipCountry = null;

            try
            {
                //ICountry country = _storeSettingService.GetCountryByCode(countryCode);
                //newShipCountry = new ShipCountry(catalogKey, country);
                //_shipCountryService.Save(newShipCountry);
                //newShipCountry = _shipCountryService.GetShipCountryByCountryCode(catalogKey, countryCode) as ShipCountry;
                var attempt = ((ShipCountryService)_shipCountryService).CreateShipCountryWithKey(catalogKey, countryCode);
                if (attempt.Success)
                {
                    newShipCountry = attempt.Result as ShipCountry;
                }
                else
                {
                    throw attempt.Exception;
                }
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            return(newShipCountry.ToShipCountryDisplay());
        }
Example #3
0
        public void Init()
        {
            _gatewayProviderService = PreTestDataWorker.GatewayProviderService;
            _storeSettingService    = PreTestDataWorker.StoreSettingService;
            _shipCountryService     = PreTestDataWorker.ShipCountryService;


            _catalog = PreTestDataWorker.WarehouseService.GetDefaultWarehouse().WarehouseCatalogs.FirstOrDefault();

            PreTestDataWorker.DeleteAllShipCountries();
            var country     = _storeSettingService.GetCountryByCode("US");
            var shipCountry = new ShipCountry(_catalog.Key, country);

            _shipCountryService.Save(shipCountry);


            var shippingProvider =
                (FixedRateShippingGatewayProvider)MerchelloContext.Gateways.Shipping.CreateInstance(Core.Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey);

            Assert.NotNull(shippingProvider);

            var resource          = shippingProvider.ListResourcesOffered().FirstOrDefault();
            var gatewayShipMethod = shippingProvider.CreateShippingGatewayMethod(resource, shipCountry, "Ground");

            shippingProvider.SaveShippingGatewayMethod(gatewayShipMethod);
        }
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            PreTestDataWorker.DeleteAllPaymentMethods();
            PreTestDataWorker.DeleteAllShipCountries();

            // Merchello CoreBootStrap
            var bootManager = new WebBootManager();

            bootManager.Initialize();

            _merchelloContext = Core.MerchelloContext.Current;

            var defaultCatalog = PreTestDataWorker.WarehouseService.GetDefaultWarehouse().WarehouseCatalogs.FirstOrDefault();

            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }

            var us        = _merchelloContext.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalog.Key, us);

            ((ServiceContext)_merchelloContext.Services).ShipCountryService.Save(usCountry);

            #region Settings -> Taxation

            var taxProvider = _merchelloContext.Gateways.Taxation.CreateInstance(Constants.ProviderKeys.Taxation.FixedRateTaxationProviderKey);

            taxProvider.DeleteAllTaxMethods();

            var gwTaxMethod = taxProvider.CreateTaxMethod("US", 0);

            gwTaxMethod.TaxMethod.Provinces["WA"].PercentAdjustment = 8.7M;

            taxProvider.SaveTaxMethod(gwTaxMethod);


            #endregion

            _address = new Address()
            {
                Address1    = "114 W. Magnolia St.",
                Address2    = "Suite 504",
                Locality    = "Bellingham",
                Region      = "WA",
                CountryCode = "US"
            };

            var gateway  = _merchelloContext.Gateways.Payment.GetAllActivatedProviders().FirstOrDefault();
            var provider = _merchelloContext.Gateways.Payment.CreateInstance(gateway.Key);
            var resource = provider.ListResourcesOffered().FirstOrDefault(x => x.ServiceCode == "Cash");
            var method   = provider.CreatePaymentMethod(resource, "Cash", "Cash Payments");
            provider.SavePaymentMethod(method);

            _paymentMethodKey = method.PaymentMethod.Key;
        }
Example #5
0
        //[Test]
        public void ReportTestsSetup()
        {
            DbPreTestDataWorker.DeleteAllAnonymousCustomers();
            DbPreTestDataWorker.DeleteAllProducts();
            DbPreTestDataWorker.DeleteAllInvoices();

            DbPreTestDataWorker.DeleteAllShipCountries();

            this.MakeProducts();

            var defaultWarehouse = DbPreTestDataWorker.WarehouseService.GetDefaultWarehouse();
            var defaultCatalog   = defaultWarehouse.WarehouseCatalogs.FirstOrDefault();

            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }


            var us        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalog.Key, us);

            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);


            var key = Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.CreateInstance(key);

            var gwshipMethod2 = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, usCountry, "Ground (Vary by Weight)");

            gwshipMethod2.RateTable.AddRow(0, 5, 5);
            gwshipMethod2.RateTable.AddRow(5, 7, 10);
            gwshipMethod2.RateTable.AddRow(7, 25, 25);
            gwshipMethod2.RateTable.AddRow(25, 10000, 100);
            rateTableProvider.SaveShippingGatewayMethod(gwshipMethod2);


            var taxProvider = MerchelloContext.Current.Gateways.Taxation.CreateInstance(Constants.ProviderKeys.Taxation.FixedRateTaxationProviderKey);

            taxProvider.DeleteAllTaxMethods();

            var gwTaxMethod = taxProvider.CreateTaxMethod("US", 0);

            gwTaxMethod.TaxMethod.Provinces["WA"].PercentAdjustment = 8.7M;

            taxProvider.SaveTaxMethod(gwTaxMethod);



            BuildOrders();
        }
Example #6
0
        public void Can_Verify_Attempting_To_Add_Two_Of_The_Same_Country_To_A_Catalog_Errors()
        {
            //// Arrange
            const string countryCode = "US";
            var          country     = _storeSettingService.GetCountryByCode(countryCode);

            //// Act
            var shipCountry1 = new ShipCountry(_catalog.Key, country);
            var shipCountry2 = new ShipCountry(_catalog.Key, country);

            _shipCountryService.Save(shipCountry1);

            //// Assert
            Assert.Throws <ConstraintException>(() => _shipCountryService.Save(shipCountry2));
        }
Example #7
0
        /// <summary>
        /// The create ship country with key.
        /// </summary>
        /// <param name="warehouseCatalogKey">
        /// The warehouse catalog key.
        /// </param>
        /// <param name="country">
        /// The country.
        /// </param>
        /// <param name="raiseEvents">
        /// The raise events.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        internal Attempt <IShipCountry> CreateShipCountryWithKey(Guid warehouseCatalogKey, ICountry country, bool raiseEvents = true)
        {
            Mandate.ParameterCondition(warehouseCatalogKey != Guid.Empty, "warehouseCatalog");
            if (country == null)
            {
                return(Attempt <IShipCountry> .Fail(new ArgumentNullException("country")));
            }

            var shipCountry = new ShipCountry(warehouseCatalogKey, country);

            if (raiseEvents)
            {
                if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs <IShipCountry>(shipCountry), this))
                {
                    shipCountry.WasCancelled = true;
                    return(Attempt <IShipCountry> .Fail(shipCountry));
                }
            }

            // verify that a ShipCountry does not already exist for this pair

            var sc = GetShipCountriesByCatalogKey(warehouseCatalogKey).FirstOrDefault(x => x.CountryCode.Equals(country.CountryCode));

            if (sc != null)
            {
                return
                    (Attempt <IShipCountry> .Fail(
                         new ConstraintException("A ShipCountry with CountryCode '" + country.CountryCode +
                                                 "' is already associate with this WarehouseCatalog")));
            }

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateShipCountryRepository(uow, _storeSettingService))
                {
                    repository.AddOrUpdate(shipCountry);
                    uow.Commit();
                }
            }

            if (raiseEvents)
            {
                Created.RaiseEvent(new Events.NewEventArgs <IShipCountry>(shipCountry), this);
            }

            return(Attempt <IShipCountry> .Succeed(shipCountry));
        }
Example #8
0
        public void Can_Create_And_Save_A_ShipCountry()
        {
            //// Arrange
            const string countryCode = "US";
            var          country     = _storeSettingService.GetCountryByCode(countryCode);

            //// Act
            var shipCountry = new ShipCountry(_catalog.Key, country);

            Assert.IsFalse(shipCountry.HasIdentity);

            _shipCountryService.Save(shipCountry);

            //// Assert
            Assert.IsTrue(shipCountry.HasIdentity);
        }
Example #9
0
        public IShipCountry BuildEntity(ShipCountryDto dto)
        {
            var country = dto.CountryCode.Equals(Constants.CountryCodes.EverywhereElse) ?
                          new Country(Constants.CountryCodes.EverywhereElse, new List <IProvince>()) :
                          _storeSettingService.GetCountryByCode(dto.CountryCode);

            var shipCountry = new ShipCountry(dto.CatalogKey, country)
            {
                Key        = dto.Key,
                UpdateDate = dto.UpdateDate,
                CreateDate = dto.CreateDate
            };

            shipCountry.ResetDirtyProperties();

            return(shipCountry);
        }
Example #10
0
        public void Can_Delete_A_ShipCountry()
        {
            //// Arrange
            const string countryCode = "US";
            var          country     = _storeSettingService.GetCountryByCode(countryCode);
            var          shipCountry = new ShipCountry(_catalog.Key, country);

            _shipCountryService.Save(shipCountry);
            Assert.IsTrue(shipCountry.HasIdentity);
            var key = shipCountry.Key;

            //// Act
            _shipCountryService.Delete(shipCountry);

            //// Assert
            Assert.IsNull(_shipCountryService.GetByKey(key));
        }
Example #11
0
        public void Can_Retrieve_A_ShipCountry()
        {
            //// Arrange
            const string countryCode = "US";
            var          country     = _storeSettingService.GetCountryByCode(countryCode);
            var          shipCountry = new ShipCountry(_catalog.Key, country);

            _shipCountryService.Save(shipCountry);
            Assert.IsTrue(shipCountry.HasIdentity);
            var key = shipCountry.Key;

            //// Act
            var retrieved = _shipCountryService.GetByKey(key);

            //// Assert
            Assert.NotNull(retrieved);
            Assert.AreEqual(shipCountry.CountryCode, retrieved.CountryCode);
        }
Example #12
0
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            var defaultCatalog = PreTestDataWorker.WarehouseService.GetDefaultWarehouse().WarehouseCatalogs.FirstOrDefault();

            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }

            // we need a ShipCountry
            PreTestDataWorker.DeleteAllShipCountries();

            var us        = PreTestDataWorker.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalog.Key, us);

            PreTestDataWorker.ShipCountryService.Save(usCountry);
        }
        public override void FixtureSetup()
        {
            base.FixtureSetup();


            var defaultWarehouse = DbPreTestDataWorker.WarehouseService.GetDefaultWarehouse();
            var defaultCatalog   = defaultWarehouse.WarehouseCatalogs.FirstOrDefault();

            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }

            DbPreTestDataWorker.DeleteAllShipCountries();
            var uk        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("GB");
            var ukCountry = new ShipCountry(defaultCatalog.Key, uk);

            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(ukCountry);

            this._settingService = MerchelloContext.Current.Services.StoreSettingService;
            var setting = this._settingService.GetByKey(Core.Constants.StoreSetting.GlobalTaxationApplicationKey);

            setting.Value = "Product";
            this._settingService.Save(setting);

            var taxProvider = MerchelloContext.Current.Gateways.Taxation.GetProviderByKey(Constants.ProviderKeys.Taxation.FixedRateTaxationProviderKey);

            taxProvider.DeleteAllTaxMethods();
            var gwTaxMethod = taxProvider.CreateTaxMethod("GB", 25);

            gwTaxMethod.TaxMethod.ProductTaxMethod = true;
            taxProvider.SaveTaxMethod(gwTaxMethod);
            ((TaxationContext)MerchelloContext.Current.Gateways.Taxation).ClearProductPricingMethod();

            DbPreTestDataWorker.DeleteAllProducts();
            var product = MockProductDataMaker.MockProductForInserting("Product", "PR", 16M);

            product.SalePrice = 12M;
            MerchelloContext.Current.Services.ProductService.Save(product);
            _productKey = product.Key;
        }
Example #14
0
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            // assert we have our defaults setup
            var dtos     = PreTestDataWorker.Database.Query <WarehouseDto>("SELECT * FROM merchWarehouse");
            var catalogs = PreTestDataWorker.Database.Query <WarehouseCatalogDto>("SELECT * FROM merchWarehouseCatalog");

            if (!dtos.Any() || !catalogs.Any())
            {
                Assert.Ignore("Warehouse defaults are not installed.");
            }

            // TODO : This is only going to be the case for the initial Merchello release
            Catalog = PreTestDataWorker.WarehouseService.GetDefaultWarehouse().WarehouseCatalogs.FirstOrDefault();

            if (Catalog == null)
            {
                Assert.Ignore("Warehouse Catalog is null");
            }

            GatewayProviderService = PreTestDataWorker.GatewayProviderService;
            StoreSettingService    = PreTestDataWorker.StoreSettingService;
            ShipCountryService     = PreTestDataWorker.ShipCountryService;


            PreTestDataWorker.DeleteAllShipCountries();
            const string countryCode = "US";

            var us          = StoreSettingService.GetCountryByCode(countryCode);
            var shipCountry = new ShipCountry(Catalog.Key, us);

            ShipCountryService.Save(shipCountry);

            var dk = StoreSettingService.GetCountryByCode("DK");

            ShipCountryService.Save(new ShipCountry(Catalog.Key, dk));
        }
Example #15
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Id;
         hashCode = (hashCode * 397) ^ (Customer != null ? Customer.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Employee != null ? Employee.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ OrderDate.GetHashCode();
         hashCode = (hashCode * 397) ^ RequiredDate.GetHashCode();
         hashCode = (hashCode * 397) ^ ShippedDate.GetHashCode();
         hashCode = (hashCode * 397) ^ ShipVia.GetHashCode();
         hashCode = (hashCode * 397) ^ Freight.GetHashCode();
         hashCode = (hashCode * 397) ^ (ShipName != null ? ShipName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ShipAddress != null ? ShipAddress.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ShipCity != null ? ShipCity.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ShipRegion != null ? ShipRegion.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ShipPostalCode != null ? ShipPostalCode.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (ShipCountry != null ? ShipCountry.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (OrderDetails != null ? OrderDetails.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (IntIds != null ? IntIds.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (CharMap != null ? CharMap.GetHashCode() : 0);
         return(hashCode);
     }
 }
        public override void FixtureSetup()
        {
            base.FixtureSetup();


            PreTestDataWorker.DeleteAllShipCountries();

            var defaultCatalog = PreTestDataWorker.WarehouseService.GetDefaultWarehouse().WarehouseCatalogs.FirstOrDefault();

            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }

            var us        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalog.Key, us);

            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);

            var key = Core.Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);

            rateTableProvider.DeleteAllActiveShipMethods(usCountry);

            #region Add and configure 3 rate table shipmethods

            var gwshipMethod1 = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByPrice, usCountry, "Ground (Vary by Price)");
            gwshipMethod1.RateTable.AddRow(0, 10, 25);
            gwshipMethod1.RateTable.AddRow(10, 15, 30);
            gwshipMethod1.RateTable.AddRow(15, 25, 35);
            gwshipMethod1.RateTable.AddRow(25, 60, 40); // total price should be 50M so we should hit this tier
            gwshipMethod1.RateTable.AddRow(25, 10000, 50);
            rateTableProvider.SaveShippingGatewayMethod(gwshipMethod1);

            #endregion
        }
Example #17
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (OrderID != 0)
            {
                hash ^= OrderID.GetHashCode();
            }
            if (CustomerID.Length != 0)
            {
                hash ^= CustomerID.GetHashCode();
            }
            if (EmployeeID != 0)
            {
                hash ^= EmployeeID.GetHashCode();
            }
            if (orderDate_ != null)
            {
                hash ^= OrderDate.GetHashCode();
            }
            if (requiredDate_ != null)
            {
                hash ^= RequiredDate.GetHashCode();
            }
            if (shippedDate_ != null)
            {
                hash ^= ShippedDate.GetHashCode();
            }
            if (ShipVia != 0)
            {
                hash ^= ShipVia.GetHashCode();
            }
            if (Freight != 0D)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(Freight);
            }
            if (ShipName.Length != 0)
            {
                hash ^= ShipName.GetHashCode();
            }
            if (ShipAddress.Length != 0)
            {
                hash ^= ShipAddress.GetHashCode();
            }
            if (ShipCity.Length != 0)
            {
                hash ^= ShipCity.GetHashCode();
            }
            if (ShipRegion.Length != 0)
            {
                hash ^= ShipRegion.GetHashCode();
            }
            if (ShipPostalCode.Length != 0)
            {
                hash ^= ShipPostalCode.GetHashCode();
            }
            if (ShipCountry.Length != 0)
            {
                hash ^= ShipCountry.GetHashCode();
            }
            hash ^= lines_.GetHashCode();
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        /// <summary>
        /// The add merchello data.
        /// </summary>
        private void AddMerchelloData()
        {
            if (!MerchelloContext.HasCurrent)
            {
                LogHelper.Info <FastTrackDataInstaller>("MerchelloContext was null");
            }

            var merchelloServices = MerchelloContext.Current.Services;


            LogHelper.Info <FastTrackDataInstaller>("Updating Default Warehouse Address");
            var warehouse = merchelloServices.WarehouseService.GetDefaultWarehouse();

            warehouse.Name        = "Merchello";
            warehouse.Address1    = "114 W. Magnolia St.";
            warehouse.Locality    = "Bellingham";
            warehouse.Region      = "WA";
            warehouse.PostalCode  = "98225";
            warehouse.CountryCode = "US";
            merchelloServices.WarehouseService.Save(warehouse);


            MultiLogHelper.Info <FastTrackDataInstaller>("Adding example shipping data");
            var catalog =
                warehouse.WarehouseCatalogs.FirstOrDefault(
                    x => x.Key == Core.Constants.Warehouse.DefaultWarehouseCatalogKey);
            var country = merchelloServices.StoreSettingService.GetCountryByCode("US");

            // The following is internal to Merchello and not exposed in the public API
            var shipCountry = merchelloServices.ShipCountryService.GetShipCountryByCountryCode(
                catalog.Key,
                "US");

            // Add the ship country
            if (shipCountry == null || shipCountry.CountryCode == "ELSE")
            {
                shipCountry = new ShipCountry(catalog.Key, country);
                merchelloServices.ShipCountryService.Save(shipCountry);
            }

            // Associate the fixed rate Shipping Provider to the ShipCountry
            var key = Core.Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider =
                (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);
            var gatewayShipMethod =
                (FixedRateShippingGatewayMethod)
                rateTableProvider.CreateShipMethod(
                    FixedRateShippingGatewayMethod.QuoteType.VaryByWeight,
                    shipCountry,
                    "Ground");

            // Add rate adjustments for Hawaii and Alaska
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustment     = 3M;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustment     = 2.5M;

            // Add a few of rate tiers to the rate table.
            gatewayShipMethod.RateTable.AddRow(0, 10, 5);
            gatewayShipMethod.RateTable.AddRow(10, 15, 10);
            gatewayShipMethod.RateTable.AddRow(15, 25, 25);
            gatewayShipMethod.RateTable.AddRow(25, 10000, 100);
            rateTableProvider.SaveShippingGatewayMethod(gatewayShipMethod);

            // Add the product collections
            LogHelper.Info <FastTrackDataInstaller>("Adding example product collections");

            // Create a featured products with home page under it

            var featuredProducts =
                merchelloServices.EntityCollectionService.CreateEntityCollectionWithKey(
                    EntityType.Product,
                    Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                    "Featured Products");


            // Create a main categories collection with Funny, Geeky and Sad under it

            var mainCategories =
                merchelloServices.EntityCollectionService.CreateEntityCollectionWithKey(
                    EntityType.Product,
                    Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                    "T-Shirts");

            var funny = merchelloServices.EntityCollectionService.CreateEntityCollection(
                EntityType.Product,
                Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                "Funny T-Shirts");

            funny.ParentKey = mainCategories.Key;

            var geeky = merchelloServices.EntityCollectionService.CreateEntityCollection(
                EntityType.Product,
                Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                "Geeky T-Shirts");

            geeky.ParentKey = mainCategories.Key;

            var sad = merchelloServices.EntityCollectionService.CreateEntityCollection(
                EntityType.Product,
                Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                "Sad T-Shirts");

            sad.ParentKey = mainCategories.Key;

            // Save the collections
            merchelloServices.EntityCollectionService.Save(new[] { mainCategories, funny, geeky, sad });

            // Add the collections to the collections dictionary
            _collections.Add(CollectionFeaturedProducts, featuredProducts.Key);
            _collections.Add(CollectionMainCategories, mainCategories.Key);
            _collections.Add(CollectionFunny, funny.Key);
            _collections.Add(CollectionGeeky, geeky.Key);
            _collections.Add(CollectionSad, sad.Key);



            // Add the detached content type
            LogHelper.Info <FastTrackDataInstaller>("Getting information for detached content");

            var contentType = _services.ContentTypeService.GetContentType("ftProduct");
            var detachedContentTypeService =
                ((Core.Services.ServiceContext)merchelloServices).DetachedContentTypeService;
            var detachedContentType = detachedContentTypeService.CreateDetachedContentType(
                EntityType.Product,
                contentType.Key,
                "Product");

            // Detached Content
            detachedContentType.Description = "Default Product Content";
            detachedContentTypeService.Save(detachedContentType);


            // Product data fields
            const string productOverview    = @"""<ul>
                                            <li>Leberkas strip steak tri-tip</li>
                                            <li>flank ham drumstick</li>
                                            <li>Bacon pastrami turkey</li>
                                            </ul>""";
            const string productDescription = @"""<p>Bacon ipsum dolor amet flank cupim filet mignon shoulder andouille kielbasa sirloin bacon spare ribs pork biltong rump ham. Meatloaf turkey tail, 
                                                        shoulder short loin capicola porchetta fatback. Jowl tenderloin sausage shank pancetta tongue.</p>
                                                <p>Ham hock spare ribs cow turducken porchetta corned beef, pastrami leberkas biltong meatloaf bacon shankle ribeye beef ribs. Picanha ham hock chicken 
                                                        biltong, ground round jowl meatloaf bacon short ribs tongue shoulder.</p>""";

            var template   = _templates.FirstOrDefault(x => x.Alias == "ftProduct");
            var templateId = template != null ? template.Id : 0;

            LogHelper.Info <FastTrackDataInstaller>("Adding an example product - Despite Shirt");

            var despiteShirt = merchelloServices.ProductService.CreateProduct("Despite Shirt", "shrt-despite", 7.39M);

            despiteShirt.Shippable      = true;
            despiteShirt.OnSale         = false;
            despiteShirt.SalePrice      = 6M;
            despiteShirt.CostOfGoods    = 4M;
            despiteShirt.Taxable        = true;
            despiteShirt.TrackInventory = false;
            despiteShirt.Available      = true;
            despiteShirt.Weight         = 1M;
            despiteShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(despiteShirt, false);

            // add to collections
            despiteShirt.AddToCollection(funny);
            despiteShirt.AddToCollection(geeky);


            var despiteImg = _media.ContainsKey("despite") ? _media["despite"] : string.Empty;

            despiteShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    despiteShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", despiteImg)
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(despiteShirt, templateId);



            LogHelper.Info <FastTrackDataInstaller>("Adding an example product  - Element Meh Shirt");
            var elementMehShirt = merchelloServices.ProductService.CreateProduct("Element Meh Shirt", "tshrt-meh", 12.99M);

            elementMehShirt.OnSale         = false;
            elementMehShirt.Shippable      = true;
            elementMehShirt.SalePrice      = 10M;
            elementMehShirt.CostOfGoods    = 8.50M;
            elementMehShirt.Taxable        = true;
            elementMehShirt.TrackInventory = false;
            elementMehShirt.Available      = true;
            elementMehShirt.Weight         = 1M;
            elementMehShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(elementMehShirt, false);

            AddOptionsToProduct(elementMehShirt);
            merchelloServices.ProductService.Save(elementMehShirt, false);

            // add to collections
            elementMehShirt.AddToCollection(featuredProducts);
            elementMehShirt.AddToCollection(geeky);

            var elementImg = _media.ContainsKey("element") ? _media["element"] : string.Empty;

            elementMehShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    elementMehShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", elementImg)
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(elementMehShirt, templateId);


            LogHelper.Info <FastTrackDataInstaller>("Adding an example product  - Evolution Shirt");
            var evolutionShirt = merchelloServices.ProductService.CreateProduct("Evolution Shirt", "shrt-evo", 13.99M);

            evolutionShirt.OnSale         = true;
            evolutionShirt.Shippable      = true;
            evolutionShirt.SalePrice      = 11M;
            evolutionShirt.CostOfGoods    = 10M;
            evolutionShirt.Taxable        = true;
            evolutionShirt.TrackInventory = false;
            evolutionShirt.Available      = true;
            evolutionShirt.Weight         = 1M;
            evolutionShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(evolutionShirt, false);

            AddOptionsToProduct(evolutionShirt);
            merchelloServices.ProductService.Save(evolutionShirt, false);

            var evolutionImg = _media.ContainsKey("evolution") ? _media["evolution"] : string.Empty;

            // add to collections
            evolutionShirt.AddToCollection(funny);
            evolutionShirt.AddToCollection(geeky);
            evolutionShirt.AddToCollection(featuredProducts);
            evolutionShirt.AddToCollection(sad);

            evolutionShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    evolutionShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", evolutionImg)
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(evolutionShirt, templateId);


            LogHelper.Info <FastTrackDataInstaller>("Adding an example product  - Flea Shirt");
            var fleaShirt = merchelloServices.ProductService.CreateProduct("Flea Shirt", "shrt-flea", 11.99M);

            fleaShirt.OnSale         = false;
            fleaShirt.Shippable      = true;
            fleaShirt.SalePrice      = 10M;
            fleaShirt.CostOfGoods    = 8.75M;
            fleaShirt.Taxable        = true;
            fleaShirt.TrackInventory = false;
            fleaShirt.Available      = true;
            fleaShirt.Weight         = 1M;
            fleaShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(fleaShirt, false);

            // add to collections
            fleaShirt.AddToCollection(funny);
            fleaShirt.AddToCollection(featuredProducts);

            var fleasImg = _media.ContainsKey("fleas") ? _media["fleas"] : string.Empty;

            fleaShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    fleaShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", fleasImg)
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(fleaShirt, templateId);



            LogHelper.Info <FastTrackDataInstaller>("Adding an example product  - Paranormal Shirt");
            var paranormalShirt = merchelloServices.ProductService.CreateProduct("Paranormal Shirt", "shrt-para", 14.99M);

            paranormalShirt.OnSale         = false;
            paranormalShirt.Shippable      = true;
            paranormalShirt.SalePrice      = 12M;
            paranormalShirt.CostOfGoods    = 9.75M;
            paranormalShirt.Taxable        = true;
            paranormalShirt.TrackInventory = false;
            paranormalShirt.Available      = true;
            paranormalShirt.Weight         = 1M;
            paranormalShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(paranormalShirt, false);

            // add to collections
            paranormalShirt.AddToCollection(geeky);
            paranormalShirt.AddToCollection(featuredProducts);

            var paraImg = _media.ContainsKey("paranormal") ? _media["paranormal"] : string.Empty;

            paranormalShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    paranormalShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", paraImg)
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(paranormalShirt, templateId);


            LogHelper.Info <FastTrackDataInstaller>("Adding an example product  - Plan Ahead Shirt");
            var planAheadShirt = merchelloServices.ProductService.CreateProduct("Plan Ahead Shirt", "shrt-plan", 8.99M);

            planAheadShirt.OnSale         = true;
            planAheadShirt.Shippable      = true;
            planAheadShirt.SalePrice      = 7.99M;
            planAheadShirt.CostOfGoods    = 4M;
            planAheadShirt.Taxable        = true;
            planAheadShirt.TrackInventory = false;
            planAheadShirt.Available      = true;
            planAheadShirt.Weight         = 1M;
            planAheadShirt.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(planAheadShirt, false);

            // add to collections
            planAheadShirt.AddToCollection(geeky);

            //// {"Key":"relatedProducts","Value":"[\r\n  \"a2d7c2c0-ebfa-4b8b-b7cb-eb398a24c83d\",\r\n  \"86e3c576-3f6f-45b8-88eb-e7b90c7c7074\"\r\n]"}

            var planImg = _media.ContainsKey("planahead") ? _media["planahead"] : string.Empty;

            planAheadShirt.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    planAheadShirt.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>("description", productDescription),
                new KeyValuePair <string, string>("brief", productOverview),
                new KeyValuePair <string, string>("image", planImg),
                new KeyValuePair <string, string>("relatedProucts", string.Format("[ \"{0}\", \"{1}\"]", paranormalShirt.Key, elementMehShirt.Key))
            }))
            {
                CanBeRendered = true
            });

            SetTemplateAndSave(planAheadShirt, templateId);
        }
        public override void FixtureSetup()
        {
            base.FixtureSetup();

            DbPreTestDataWorker.DeleteAllInvoices();
            DbPreTestDataWorker.DeleteAllShipCountries();


            #region Back Office

            #region Product Entry

            _product1 = DbPreTestDataWorker.MakeExistingProduct(true, 1, 1);
            _product2 = DbPreTestDataWorker.MakeExistingProduct(true, 1, 2);
            _product3 = DbPreTestDataWorker.MakeExistingProduct(true, 1, 3);
            _product4 = DbPreTestDataWorker.MakeExistingProduct(true, 1, 4);
            _product5 = DbPreTestDataWorker.MakeExistingProduct(true, 1, 5);


            #endregion

            #region WarehouseCatalog

            var defaultWarehouse = DbPreTestDataWorker.WarehouseService.GetDefaultWarehouse();
            var defaultCatalog   = defaultWarehouse.WarehouseCatalogs.FirstOrDefault();
            if (defaultCatalog == null)
            {
                Assert.Ignore("Default WarehouseCatalog is null");
            }

            #endregion // WarehouseCatalog

            #region Settings -> Shipping

            // Add countries (US & DK) to default catalog
            #region Add Countries

            var us        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalog.Key, us);
            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);

            var dk        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("DK");
            var dkCountry = new ShipCountry(defaultCatalog.Key, dk);
            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(dkCountry);

            #endregion // ShipCountry

            #region Add a GatewayProvider (RateTableShippingGatewayProvider)

            var key = Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);

            #region Add and configure 3 rate table shipmethods

            var gwshipMethod1 = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByPrice, usCountry, "Ground (Vary by Price)");
            gwshipMethod1.RateTable.AddRow(0, 10, 25);
            gwshipMethod1.RateTable.AddRow(10, 15, 30);
            gwshipMethod1.RateTable.AddRow(15, 25, 35);
            gwshipMethod1.RateTable.AddRow(25, 60, 40); // total price should be 50M so we should hit this tier
            gwshipMethod1.RateTable.AddRow(25, 10000, 50);
            rateTableProvider.SaveShippingGatewayMethod(gwshipMethod1);

            var gwshipMethod2 = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, usCountry, "Ground (Vary by Weight)");
            gwshipMethod2.RateTable.AddRow(0, 10, 5);
            gwshipMethod2.RateTable.AddRow(10, 15, 10); // total weight should be 10M so we should hit this tier
            gwshipMethod2.RateTable.AddRow(15, 25, 25);
            gwshipMethod2.RateTable.AddRow(25, 10000, 100);
            rateTableProvider.SaveShippingGatewayMethod(gwshipMethod2);

            var gwshipMethod3 = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByPrice, dkCountry, "Ground (Vary by Price)");
            gwshipMethod3.RateTable.AddRow(0, 10, 5);
            gwshipMethod3.RateTable.AddRow(10, 15, 10);
            gwshipMethod3.RateTable.AddRow(15, 25, 25);
            gwshipMethod3.RateTable.AddRow(25, 60, 30); // total price should be 50M so we should hit this tier
            gwshipMethod3.RateTable.AddRow(25, 10000, 50);
            rateTableProvider.SaveShippingGatewayMethod(gwshipMethod3);

            #endregion // ShipMethods

            #endregion // GatewayProvider

            #endregion // Shipping

            #region Settings -> Taxation

            var taxProvider = MerchelloContext.Current.Gateways.Taxation.CreateInstance(Constants.ProviderKeys.Taxation.FixedRateTaxationProviderKey);

            taxProvider.DeleteAllTaxMethods();

            var gwTaxMethod = taxProvider.CreateTaxMethod("US", 0);

            gwTaxMethod.TaxMethod.Provinces["WA"].PercentAdjustment = 8.7M;

            taxProvider.SaveTaxMethod(gwTaxMethod);


            #endregion


            #region Settings
            //// http://issues.merchello.com/youtrack/issue/M-608
            var storeSetting = DbPreTestDataWorker.StoreSettingService.GetByKey(Core.Constants.StoreSettingKeys.GlobalShippingIsTaxableKey);
            storeSetting.Value = true.ToString();
            DbPreTestDataWorker.StoreSettingService.Save(storeSetting);

            #endregion

            #endregion  // Back Office
        }
        public void Can_Create_A_Customer_Invoice_And_Order()
        {
            // Adding the shipmethod is typically done in the back office through the UI.
            // Interested in the use case to dynamically add theses?
            var key = Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var defaultCatalogKey = Constants.Warehouse.DefaultWarehouseCatalogKey;

            // this would have to be done through the back office as it uses an internal service
            var us        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalogKey, us);

            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);

            // we can use this later.
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);

            // again usually done in the back office
            if (!rateTableProvider.ShipMethods.Any())
            {
                // creates the rate table for ship rate quotes
                var gwShipmeMethod = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, usCountry, "Ground (Vary by Weight)");
                gwShipmeMethod.RateTable.AddRow(0, 10, 5);
                gwShipmeMethod.RateTable.AddRow(10, 15, 10); // total weight should be 10M so we should hit this tier
                gwShipmeMethod.RateTable.AddRow(15, 25, 25);
                gwShipmeMethod.RateTable.AddRow(25, 10000, 100);
                rateTableProvider.SaveShippingGatewayMethod(gwShipmeMethod);
            }



            // Get the persisted customer
            const string loginName = "rusty";

            var customerService = MerchelloContext.Current.Services.CustomerService;

            var customer = customerService.GetByLoginName(loginName)
                           ?? customerService.CreateCustomerWithKey(loginName, "Rusty", "Swayne", "*****@*****.**");

            // I'll use this for billing and shipping
            var billingAddress = new Address()
            {
                Name        = "Mindfly Web Design Studio",
                Address1    = "114 W. Magnolia St. Suite 300",
                Locality    = "Bellingham",
                Region      = "WA",
                PostalCode  = "98225",
                CountryCode = "US"
            };



            // Most of the time this information is brought in from the IProductVariant - but the idea is you can
            // describe things on the fly
            var extendedData = new ExtendedDataCollection();

            // this is used to determine where a shipment originates
            extendedData.SetValue(Constants.ExtendedDataKeys.WarehouseCatalogKey, defaultCatalogKey.ToString());
            // items set to shippable
            extendedData.SetValue(Constants.ExtendedDataKeys.TrackInventory, "false");
            extendedData.SetValue(Constants.ExtendedDataKeys.Shippable, "true");
            extendedData.SetValue(Constants.ExtendedDataKeys.Weight, "1.25");
            extendedData.SetValue(Constants.ExtendedDataKeys.CurrencyCode, "USD");

            var item = new InvoiceLineItem(LineItemType.Product, "My product", "mySku", 2, 10M, extendedData);

            var invoiceService = MerchelloContext.Current.Services.InvoiceService;

            var invoice = invoiceService.CreateInvoice(Constants.InvoiceStatus.Unpaid);

            // I'd say we need to add a parameter to the service so we don't have to do this
            // http://issues.merchello.com/youtrack/issue/M-434
            ((Invoice)invoice).CustomerKey = customer.Key;

            // The version key is useful in some cases to invalidate shipping quotes or taxation calculations
            invoice.VersionKey = Guid.NewGuid();

            invoice.Items.Add(item);

            // at this point the invoice is not saved and we don't have an invoice number
            // however, we may want to quote shipping so we need a shipment

            // Shipment Statuses are new in 1.5.0
            var warehouse = MerchelloContext.Current.Services.WarehouseService.GetDefaultWarehouse();

            var shipmentStatus =
                MerchelloContext.Current.Services.ShipmentService.GetShipmentStatusByKey(
                    Constants.ShipmentStatus.Quoted);

            // since we know all the items in the invoice will be shipped we don't need to filter
            var shipment = new Shipment(shipmentStatus, warehouse.AsAddress(), billingAddress, invoice.Items);

            // since we already know the shipping provider we want from above we can do
            var quotes = rateTableProvider.QuoteShippingGatewayMethodsForShipment(shipment);

            // if we wanted Merchello to get quotes from all shipping providers we'd do the following
            // var quotes = shipment.ShipmentRateQuotes();

            if (quotes.Any())
            {
                // this check makes certain a quote was returned.  For example if the collection of items was outside the allowable
                // weight range, the provider would not return a quote.

                // Add the first quote to the invoice.

                invoice.Items.Add(quotes.FirstOrDefault().AsLineItemOf <InvoiceLineItem>());
            }

            // you do need to update the total ... this is usually done in the InvoiceBuilder in
            // instantiated by a SalesPreparation sub class
            var charges   = invoice.Items.Where(x => x.LineItemType != LineItemType.Discount).Sum(x => x.TotalPrice);
            var discounts = invoice.Items.Where(x => x.LineItemType == LineItemType.Discount).Sum(x => x.TotalPrice);

            // total the invoice
            decimal converted;

            invoice.Total = decimal.TryParse((charges - discounts).ToString(CultureInfo.InvariantCulture), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out converted) ? converted : 0;

            // Now we save the invoice since we have to have a real record of something to collect a payment against
            // This also generates the invoice number
            invoiceService.Save(invoice);

            Console.WriteLine(invoice.InvoiceNumber);

            // cash payment method
            var cashProvider = MerchelloContext.Current.Gateways.Payment.GetProviderByKey(Constants.ProviderKeys.Payment.CashPaymentProviderKey);

            if (cashProvider != null)
            {
                var cash = cashProvider.PaymentMethods.FirstOrDefault(); // default install has a single payment method "Cash"

                // I usually Authorize a cash payment if taken online since we don't really see the money.  Capture is used
                // when the money comes in.  In your inquiry, it looks like you are assuming the money is in hand at the
                // time of the purchase, so we'll use AuthorizeCapture straight away.

                var attempt = invoice.AuthorizeCapturePayment(cash.Key);

                if (!attempt.Payment.Success)
                {
                    // handle the error
                }

                // otherwise you'll notice
                var approved = attempt.ApproveOrderCreation; // equals true

                // the order will be automatically created by the event handler in Merchello.Core.Gateways.GatewayEvents

                // however in this test I don't have the event wired up so I have to do it manuall
                if (approved)
                {
                    var order = invoice.PrepareOrder();
                    MerchelloContext.Current.Services.OrderService.Save(order);

                    var items = order.Items;
                }
            }
            // Cash provider is not active
        }
Example #21
0
        /// <summary>
        /// The create ship country with key.
        /// </summary>
        /// <param name="warehouseCatalogKey">
        /// The warehouse catalog key.
        /// </param>
        /// <param name="country">
        /// The country.
        /// </param>
        /// <param name="raiseEvents">
        /// The raise events.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        internal Attempt<IShipCountry> CreateShipCountryWithKey(Guid warehouseCatalogKey, ICountry country, bool raiseEvents = true)
        {
            Mandate.ParameterCondition(warehouseCatalogKey != Guid.Empty, "warehouseCatalog");
            if (country == null) return Attempt<IShipCountry>.Fail(new ArgumentNullException("country"));

            var shipCountry = new ShipCountry(warehouseCatalogKey, country);

            if (raiseEvents)
                if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IShipCountry>(shipCountry), this))
                {
                    shipCountry.WasCancelled = true;
                    return Attempt<IShipCountry>.Fail(shipCountry);
                }

            // verify that a ShipCountry does not already exist for this pair

            var sc = GetShipCountriesByCatalogKey(warehouseCatalogKey).FirstOrDefault(x => x.CountryCode.Equals(country.CountryCode));
            if (sc != null)
                return
                    Attempt<IShipCountry>.Fail(
                        new ConstraintException("A ShipCountry with CountryCode '" + country.CountryCode +
                                                "' is already associate with this WarehouseCatalog"));

            using (new WriteLock(Locker))
            {
                var uow = _uowProvider.GetUnitOfWork();
                using (var repository = _repositoryFactory.CreateShipCountryRepository(uow, _storeSettingService))
                {
                    repository.AddOrUpdate(shipCountry);
                    uow.Commit();
                }
            }

            if (raiseEvents)
                Created.RaiseEvent(new Events.NewEventArgs<IShipCountry>(shipCountry), this);

            return Attempt<IShipCountry>.Succeed(shipCountry);
        }
Example #22
0
        /// <summary>
        /// The add merchello data.
        /// </summary>
        private void AddMerchelloData()
        {
            if (!MerchelloContext.HasCurrent)
            {
                LogHelper.Info <BazaarDataInstaller>("MerchelloContext was null");
            }

            var merchelloServices = MerchelloContext.Current.Services;

            LogHelper.Info <BazaarDataInstaller>("Updating Default Warehouse Address");
            var warehouse = merchelloServices.WarehouseService.GetDefaultWarehouse();

            warehouse.Name        = "Merchello";
            warehouse.Address1    = "114 W. Magnolia St.";
            warehouse.Address2    = "Suite 300";
            warehouse.Locality    = "Bellingham";
            warehouse.Region      = "WA";
            warehouse.PostalCode  = "98225";
            warehouse.CountryCode = "US";
            merchelloServices.WarehouseService.Save(warehouse);

            LogHelper.Info <BazaarDataInstaller>("Adding example shipping data");
            var catalog =
                warehouse.WarehouseCatalogs.FirstOrDefault(
                    x => x.Key == Core.Constants.DefaultKeys.Warehouse.DefaultWarehouseCatalogKey);
            var country = merchelloServices.StoreSettingService.GetCountryByCode("US");

            // The follow is internal to Merchello and not exposed in the public API
            var shipCountry =
                ((Core.Services.ServiceContext)merchelloServices).ShipCountryService.GetShipCountryByCountryCode(
                    catalog.Key,
                    "US");

            // Add the ship country
            if (shipCountry == null || shipCountry.CountryCode == "ELSE")
            {
                shipCountry = new ShipCountry(catalog.Key, country);
                ((Core.Services.ServiceContext)merchelloServices).ShipCountryService.Save(shipCountry);
            }

            // Associate the fixed rate Shipping Provider to the ShipCountry
            var key = Core.Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var rateTableProvider =
                (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);
            var gatewayShipMethod =
                (FixedRateShippingGatewayMethod)
                rateTableProvider.CreateShipMethod(
                    FixedRateShippingGatewayMethod.QuoteType.VaryByWeight,
                    shipCountry,
                    "Ground");

            // Add rate adjustments for Hawaii and Alaska
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["HI"].RateAdjustment     = 3M;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustmentType = RateAdjustmentType.Numeric;
            gatewayShipMethod.ShipMethod.Provinces["AK"].RateAdjustment     = 2.5M;

            // Add a few of rate tiers to the rate table.
            gatewayShipMethod.RateTable.AddRow(0, 10, 5);
            gatewayShipMethod.RateTable.AddRow(10, 15, 10);
            gatewayShipMethod.RateTable.AddRow(15, 25, 25);
            gatewayShipMethod.RateTable.AddRow(25, 10000, 100);
            rateTableProvider.SaveShippingGatewayMethod(gatewayShipMethod);

            // Add the product collections
            LogHelper.Info <BazaarDataInstaller>("Adding example product collections");
            var featuredProducts =
                merchelloServices.EntityCollectionService.CreateEntityCollectionWithKey(
                    EntityType.Product,
                    Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                    "Featured Products");
            var soap =
                merchelloServices.EntityCollectionService.CreateEntityCollectionWithKey(
                    EntityType.Product,
                    Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                    "Soap");

            var specializedSoap = merchelloServices.EntityCollectionService.CreateEntityCollection(
                EntityType.Product,
                Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                "Specialized Soap");

            specializedSoap.ParentKey = soap.Key;

            var generic =
                merchelloServices.EntityCollectionService.CreateEntityCollection(
                    EntityType.Product,
                    Core.Constants.ProviderKeys.EntityCollection.StaticProductCollectionProviderKey,
                    "Generic");

            generic.ParentKey = soap.Key;
            merchelloServices.EntityCollectionService.Save(new[] { specializedSoap, generic });

            _collections.Add("featuredProducts", featuredProducts.Key);
            _collections.Add("specializedSoap", specializedSoap.Key);
            _collections.Add("generic", generic.Key);

            // Add the detached content type
            LogHelper.Info <BazaarDataInstaller>("Getting information for detached content");
            var contentType = _services.ContentTypeService.GetContentType("BazaarProductContent");
            var detachedContentTypeService =
                ((Core.Services.ServiceContext)merchelloServices).DetachedContentTypeService;
            var detachedContentType = detachedContentTypeService.CreateDetachedContentType(
                EntityType.Product,
                contentType.Key,
                "Bazaar Product");

            detachedContentType.Description = "Default Bazaar Product Content";
            detachedContentTypeService.Save(detachedContentType);
            LogHelper.Info <BazaarDataInstaller>("Adding an example product Avocado Bar");
            var avocadoBar = merchelloServices.ProductService.CreateProduct("Avocado Bar", "avocadobar", 5M);

            avocadoBar.Shippable      = true;
            avocadoBar.OnSale         = false;
            avocadoBar.SalePrice      = 3M;
            avocadoBar.Taxable        = true;
            avocadoBar.TrackInventory = false;
            avocadoBar.Available      = true;
            avocadoBar.Weight         = 1M;
            avocadoBar.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(avocadoBar, false);

            // add to collections
            avocadoBar.AddToCollection(featuredProducts);
            avocadoBar.AddToCollection(specializedSoap);

            avocadoBar.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    avocadoBar.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>(
                    "description",
                    "\"<p><span>Made with real avocados, this Avocado Moisturizing Bar is great for dry skin. Layers of color are achieved by using oxide colorants. Scented with Wasabi Fragrance Oil, this soap smells slightly spicy, making it a great choice for both men and women. To ensure this soap does not overheat, place in the freezer to keep cool and prevent gel phase.</span></p>\""),
                new KeyValuePair <string, string>(
                    "brief",
                    "\"Avocado Moisturizing Bar is great for dry skin.\""),
                new KeyValuePair <string, string>(
                    "image",
                    "{ \"focalPoint\": { \"left\": 0.5, \"top\": 0.5 }, \"src\": \"/media/1035/avocadobars.jpg\" }"),
            }))
            {
                CanBeRendered = true
            });
            merchelloServices.ProductService.Save(avocadoBar);

            LogHelper.Info <BazaarDataInstaller>("Adding an example product Liquid Soap");
            var liquidSoap = merchelloServices.ProductService.CreateProduct("Liquid Soap", "liquidsoap", 16M);

            liquidSoap.OnSale         = true;
            liquidSoap.SalePrice      = 12M;
            liquidSoap.Taxable        = true;
            liquidSoap.TrackInventory = false;
            liquidSoap.Available      = true;
            liquidSoap.Weight         = 1M;
            liquidSoap.AddToCatalogInventory(catalog);
            merchelloServices.ProductService.Save(liquidSoap, false);

            // add to collections
            liquidSoap.AddToCollection(featuredProducts);
            liquidSoap.AddToCollection(specializedSoap);

            liquidSoap.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    liquidSoap.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>(
                    "description",
                    "\"<p>Soap is better liquefied.</p>\""),
                new KeyValuePair <string, string>(
                    "brief",
                    "\"Liquid Soap.\""),
                new KeyValuePair <string, string>(
                    "image",
                    "{ \"focalPoint\": { \"left\": 0.5, \"top\": 0.5 }, \"src\": \"/media/1037/beeswaxlotionbase_lotionbee_main_a.jpg\" }"),
            }))
            {
                CanBeRendered = true
            });
            merchelloServices.ProductService.Save(liquidSoap);

            LogHelper.Info <BazaarDataInstaller>("Adding an example product Generic Soap");
            var genericSoap = merchelloServices.ProductService.CreateProduct("Generic Soap", "generic", 3M);

            genericSoap.OnSale         = false;
            genericSoap.SalePrice      = 2M;
            genericSoap.Taxable        = true;
            genericSoap.TrackInventory = false;
            genericSoap.Available      = true;
            genericSoap.Weight         = 1M;
            genericSoap.AddToCatalogInventory(catalog);
            genericSoap.ProductOptions.Add(new ProductOption("Color"));
            genericSoap.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("White", "White"));
            genericSoap.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Green", "Green"));
            genericSoap.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Blue", "Blue"));
            genericSoap.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Pink", "Pink"));
            genericSoap.ProductOptions.First(x => x.Name == "Color").Choices.Add(new ProductAttribute("Purple", "Purple"));
            merchelloServices.ProductService.Save(genericSoap, false);

            // add to collections
            genericSoap.AddToCollection(generic);

            genericSoap.DetachedContents.Add(
                new ProductVariantDetachedContent(
                    genericSoap.ProductVariantKey,
                    detachedContentType,
                    "en-US",
                    new DetachedDataValuesCollection(
                        new[]
            {
                new KeyValuePair <string, string>(
                    "description",
                    "\"<p>A substance used with water for washing and cleaning, made of a compound of natural oils or fats with sodium hydroxide or another strong alkali, and typically having perfume and coloring added.</p>\""),
                new KeyValuePair <string, string>(
                    "brief",
                    "\"Generic soap.\""),
                new KeyValuePair <string, string>(
                    "image",
                    "{ \"focalPoint\": { \"left\": 0.5, \"top\": 0.5 }, \"src\": \"/media/1038/bathbombs.jpg\" }"),
            }))
            {
                CanBeRendered = true
            });

            merchelloServices.ProductService.Save(genericSoap);
        }