Example #1
0
        public static coreModel.Store ToCoreModel(this webModel.Store store, ShippingMethod[] shippingMethods, PaymentMethod[] paymentMethods, TaxProvider[] taxProviders)
        {
            var retVal = new coreModel.Store();
            retVal.InjectFrom(store);
            retVal.SeoInfos = store.SeoInfos;
            retVal.StoreState = store.StoreState;
            retVal.DynamicProperties = store.DynamicProperties;

            if (store.ShippingMethods != null)
            {
                retVal.ShippingMethods = new List<ShippingMethod>();
                foreach (var shippingMethod in shippingMethods)
                {
                    var webShippingMethod = store.ShippingMethods.FirstOrDefault(x => x.Code == shippingMethod.Code);
                    if (webShippingMethod != null)
                    {
                        retVal.ShippingMethods.Add(webShippingMethod.ToCoreModel(shippingMethod));
                    }
                }
            }

            if (store.PaymentMethods != null)
            {
                retVal.PaymentMethods = new List<PaymentMethod>();
                foreach (var paymentMethod in paymentMethods)
                {
                    var webPaymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == paymentMethod.Code);
                    if (webPaymentMethod != null)
                    {
                        retVal.PaymentMethods.Add(webPaymentMethod.ToCoreModel(paymentMethod));
                    }
                }
            }

            if (store.TaxProviders != null)
            {
                retVal.TaxProviders = new List<TaxProvider>();
                foreach (var taxProvider in taxProviders)
                {
                    var webTaxProvider = store.TaxProviders.FirstOrDefault(x => x.Code == taxProvider.Code);
                    if (webTaxProvider != null)
                    {
                        retVal.TaxProviders.Add(webTaxProvider.ToCoreModel(taxProvider));
                    }
                }
            }

            if (store.Languages != null)
                retVal.Languages = store.Languages;
            if (store.Currencies != null)
                retVal.Currencies = store.Currencies;
            if (store.ReturnsFulfillmentCenter != null)
                retVal.ReturnsFulfillmentCenter = store.ReturnsFulfillmentCenter.ToCoreModel();
            if (store.FulfillmentCenter != null)
                retVal.FulfillmentCenter = store.FulfillmentCenter.ToCoreModel();

            return retVal;
        }
        protected void BtnCreate_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid ) {
            ShippingMethod shippingMethod = new ShippingMethod( StoreId, TxtName.Text );
            shippingMethod.Save();

            Redirect( WebUtils.GetPageUrl( Constants.Pages.EditShippingMethod ) + "?id=" + shippingMethod.Id + "&storeId=" + shippingMethod.StoreId );
              }
        }
Example #3
0
 public Order(Customer customer, string shippingAddress, string billingAddress,
     ShippingMethod shippingMethod)
     : this()
 {
     this.customer.Value = customer;
     this.shippingAddress = shippingAddress;
     this.shippingMethod = shippingMethod;
     this.billingAddress = billingAddress;
 }
        public void Delete(ShippingMethod method)
        {
            if (method.IsEnabled)
            {
                Disable(method);
            }

            _repository.Delete(method);
        }
        public ShippingRateCalculationContext(ShippingMethod shippingMethod, object shippingRateProviderConfig, PriceCalculationContext pricingContext)
        {
            Require.NotNull(shippingMethod, "shippingMethod");
            Require.NotNull(pricingContext, "pricingContext");

            ShippingMethod = shippingMethod;
            ShippingRateProviderConfig = shippingRateProviderConfig;
            PricingContext = pricingContext;
        }
        public static ShippingMethod ToWebModel(this VirtoCommerceQuoteModuleWebModelShipmentMethod serviceModel, Currency currency)
        {
            var webModel = new ShippingMethod();

            webModel.InjectFrom<NullableAndEnumValueInjecter>(serviceModel);

            webModel.Price = new Money(serviceModel.Price ?? 0, currency);

            return webModel;
        }
        public static ShippingMethod ToViewModel(this DataContracts.Cart.ShipmentMethod shipmentMethod)
        {
            var shippingMethodViewModel = new ShippingMethod();

            shippingMethodViewModel.ImageUrl = shipmentMethod.LogoUrl;
            shippingMethodViewModel.Keyword = shipmentMethod.ShipmentMethodCode;
            shippingMethodViewModel.Price = shipmentMethod.Price;
            shippingMethodViewModel.Title = shipmentMethod.Name;

            return shippingMethodViewModel;
        }
        public bool Enable(ShippingMethod method)
        {
            if (method.IsEnabled)
            {
                return false;
            }

            method.IsEnabled = true;
            _repository.Database.SaveChanges();

            Event.Raise(new ShippingMethodEnabled(method), _instance);

            return true;
        }
        ShippingMethod GetOrderShippingMethod(Commerce.Data.SqlRepository.ShippingMethod method, SqlRepository.Order order) {

            ShippingMethod result = null;
            Decimal orderWeight = order.OrderItems.Sum(x => x.Product.WeightInPounds);
            if (method != null) {
                result = new ShippingMethod();
                result.ID = method.ShippingMethodID;
                result.Carrier = method.Carrier;
                result.EstimatedDelivery = method.EstimatedDelivery;
                result.RatePerPound = method.RatePerPound;
                result.ServiceName = method.ServiceName;
                result.Cost = method.BaseRate + (method.RatePerPound * orderWeight);
            }

            return result;
        }
        public static ShippingMethod ToWebModel(this VirtoCommerceCartModuleWebModelShippingMethod shippingMethod, IEnumerable<Currency> availCurrencies, Language language)
        {
            var shippingMethodModel = new ShippingMethod();

            shippingMethodModel.InjectFrom(shippingMethod);

            var currency = availCurrencies.FirstOrDefault(x=> x.Equals(shippingMethod.Currency)) ?? new Currency(language, shippingMethod.Currency); 
            if (shippingMethod.Discounts != null)
            {
                shippingMethodModel.Discounts = shippingMethod.Discounts.Select(d => d.ToWebModel(availCurrencies, language)).ToList();
            }

            shippingMethodModel.Price = new Money(shippingMethod.Price ?? 0, currency);

            return shippingMethodModel;
        }
Example #11
0
		public static coreModel.Store ToCoreModel(this webModel.Store store, ShippingMethod[] shippingMethods, PaymentMethod[] paymentMethods)
		{
			var retVal = new coreModel.Store();
			retVal.InjectFrom(store);
			retVal.SeoInfos = store.SeoInfos;
			retVal.StoreState = store.StoreState;
			if (store.Settings != null)
				retVal.Settings = store.Settings.Select(x => x.ToCoreModel()).ToList();

			if (store.ShippingMethods != null)
			{
				retVal.ShippingMethods = new List<ShippingMethod>();
				foreach (var shippingMethod in shippingMethods)
				{
					var webShippingMethod = store.ShippingMethods.FirstOrDefault(x => x.Code == shippingMethod.Code);
					if (webShippingMethod != null)
					{
						retVal.ShippingMethods.Add(webShippingMethod.ToCoreModel(shippingMethod));
					}
				}
			}

			if (store.PaymentMethods != null)
			{
				retVal.PaymentMethods = new List<PaymentMethod>();
				foreach (var paymentMethod in paymentMethods)
				{
					var webPaymentMethod = store.PaymentMethods.FirstOrDefault(x => x.Code == paymentMethod.Code);
					if (webPaymentMethod != null)
					{
						retVal.PaymentMethods.Add(webPaymentMethod.ToCoreModel(paymentMethod));
					}
				}
			}

			if (store.Languages != null)
				retVal.Languages = store.Languages;
			if (store.Currencies != null)
				retVal.Currencies = store.Currencies;
			if (store.ReturnsFulfillmentCenter != null)
				retVal.ReturnsFulfillmentCenter = store.ReturnsFulfillmentCenter.ToCoreModel();
			if (store.FulfillmentCenter != null)
				retVal.FulfillmentCenter = store.FulfillmentCenter.ToCoreModel();
			

			return retVal;
		}
        public static ShippingMethod ToWebModel(this VirtoCommerceCartModuleWebModelShippingMethod shippingMethod)
        {
            var shippingMethodModel = new ShippingMethod();

            shippingMethodModel.InjectFrom(shippingMethod);

            var currency = new Currency(EnumUtility.SafeParse(shippingMethod.Currency, CurrencyCodes.USD));

            if (shippingMethod.Discounts != null)
            {
                shippingMethodModel.Discounts = shippingMethod.Discounts.Select(d => d.ToWebModel()).ToList();
            }

            shippingMethodModel.Price = new Money(shippingMethod.Price ?? 0, currency.Code);

            return shippingMethodModel;
        }
Example #13
0
        public virtual StoreShippingMethodEntity FromModel(ShippingMethod shippingMethod, PrimaryKeyResolvingMap pkMap)
        {
            if (shippingMethod == null)
            {
                throw new ArgumentNullException(nameof(shippingMethod));
            }

            pkMap.AddPair(shippingMethod, this);

            Id       = shippingMethod.Id;
            IsActive = shippingMethod.IsActive;
            Code     = shippingMethod.Code;
            TaxType  = shippingMethod.TaxType;
            LogoUrl  = shippingMethod.LogoUrl;
            Priority = shippingMethod.Priority;
            StoreId  = shippingMethod.StoreId;
            TypeName = shippingMethod.TypeName;

            return(this);
        }
Example #14
0
        public void OrderService_CanCreateShippingMethod()
        {
            var app = BaseTest.CreateHccAppInMemory();

            app.CurrentRequestContext.CurrentStore    = new Store();
            app.CurrentRequestContext.CurrentStore.Id = 230;

            var target = new ShippingMethod();

            target.Adjustment     = 1.23m;
            target.AdjustmentType = ShippingMethodAdjustmentType.Percentage;
            target.Bvin           = string.Empty;
            target.Name           = "Test Name";
            target.Settings.AddOrUpdate("MySetting", "MySetVal");
            target.ShippingProviderId = "123456";
            target.ZoneId             = -101;

            Assert.IsTrue(app.OrderServices.ShippingMethods.Create(target));
            Assert.AreNotEqual(string.Empty, target.Bvin, "Bvin should not be empty");
        }
Example #15
0
        public ActionResult ShippingMethodCreate()
        {
            if (!MyHelp.CheckAuth("shipping", "shippingMethod", EnumData.AuthType.Insert))
            {
                return(RedirectToAction("index", "main"));
            }

            using (Method = new GenericRepository <ShippingMethod>())
            {
                ShippingMethod newMethod = new ShippingMethod()
                {
                    IsEnable = false, IsDirectLine = false, IsExport = false, IsBattery = false
                };
                Method.Create(newMethod);
                Method.SaveChanges();

                MyHelp.Log("ShippingMethod", newMethod.ID, "新增運輸方式");
                return(RedirectToAction("shippingMethodEdit", new { id = newMethod.ID }));
            }
        }
Example #16
0
        public void EnumMethod()
        {
            ShippingMethod method = ShippingMethod.Express;

            Console.WriteLine(method);
            Console.WriteLine((int)method);

            // converting int to enum
            int methodId = 3;
            //Console.WriteLine((ShippingMethod)methodId);

            // Console.WriteLine does the below ToString method on values passed in by default.
            //Console.WriteLine(method.ToString());

            // Parsing - getting a string and converting it to a different type.
            string methodName     = "Express";
            var    shippingMethod = Enum.Parse(typeof(ShippingMethod), methodName);

            Console.WriteLine(shippingMethod);
        }
Example #17
0
        public void CalculateTotals_StandardCustomer_TotalEqualsCostPlusShipping(ShippingMethod shippingMethod)
        {
            var originAddress      = CreateAddress(city: "city 1");
            var destinationAddress = CreateAddress(city: "city 2");

            var target = new CheckOutEngine(new ShippingCalculator(originAddress), _mapper, new CouponEngine());

            var cart = new CartBuilder()
                       .WithShippingAddress(destinationAddress)
                       .WithShippingMethod(shippingMethod)
                       .WithItems(new List <Item>
            {
                CreateItem(price: 2, quantity: 3)
            })
                       .Build();

            var result = target.CalculateTotals(cart, null);

            Assert.Equal((2 * 3) + result.ShippingCost, result.Total);
        }
Example #18
0
        public double CalculateShippingCost(ShippingMethod method)
        {
            double cost = 0;
            switch(method)
            {
                case ShippingMethod.USPS:
                    cost = 1.0 * 1;
                    break;
                case ShippingMethod.FedEx:
                    cost = 1.0 * 2;
                    break;
                case ShippingMethod.DHL:
                    cost = 1.0 * 3;
                    break;
                case ShippingMethod.UPS:
                    cost = 1.0 * 4;
                    break;
            }

            return cost;
        }
Example #19
0
        public void ShoppiningTest(string sex, string name, string surname, string email, string password, string date,
                                   string company, string vat, string adress, string storage, string zipcod, string city, string phone)
        {
            SearchPage sp = mainPage.ClickOnT();

            sp.ClickOn();
            Thread.Sleep(2000);
            Cart        ct = sp.AddToCart();
            PrivateData pd = ct.ClickOnDiv();

            pd.Sex(sex).FirstName(name).LastName(surname).Email(email).Password(password).Brithday(date).Agree();
            Adress aadress = pd.ClickOnContinue();

            aadress.Company(company).PDV(vat)._Adress(adress).Storage(storage).PostCode(zipcod).City(city).Phone(phone);
            ShippingMethod SM = aadress.SM();

            SM.Coment();
            Paying pay = SM.Pay();

            pay.SwichPay();
        }
Example #20
0
        public async Task ShouldCreateAndDeleteShippingMethodAsync()
        {
            ShippingMethodDraft       shippingMethodDraft = Helper.GetTestShippingMethodDraft(_project, _testTaxCategory, _testZone);
            Response <ShippingMethod> response            = await _client.ShippingMethods().CreateShippingMethodAsync(shippingMethodDraft);

            Assert.True(response.Success);

            ShippingMethod shippingMethod = response.Result;

            Assert.NotNull(shippingMethod.Id);

            string deletedShippingMethodId = shippingMethod.Id;

            response = await _client.ShippingMethods().DeleteShippingMethodAsync(shippingMethod);

            Assert.True(response.Success);

            response = await _client.ShippingMethods().GetShippingMethodByIdAsync(deletedShippingMethodId);

            Assert.False(response.Success);
        }
Example #21
0
        protected virtual List <LocalizedProperty> UpdateLocales(ShippingMethod shippingMethod, ShippingMethodModel 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
                });
                localized.Add(new LocalizedProperty()
                {
                    LanguageId  = local.LanguageId,
                    LocaleKey   = "Description",
                    LocaleValue = local.Description
                });
            }
            return(localized);
        }
Example #22
0
        /// <summary>
        /// Edits the flat rate per order shipping method.
        /// </summary>
        //[TestMethod]
        //[Priority(16)]
        public void EditSM_FlatRatePerOrder()
        {
            #region Arrange
            var smethod0 = new ShippingMethod();
            var setting  = _irepo.GetEditSMInfo_FlatRatePerOrder(ref smethod0);


            var smethod1 = _application.OrderServices.ShippingMethods.FindAll(_application.CurrentStore.Id)
                           .FirstOrDefault(x => x.ShippingProviderId.Equals(GetShippingProviderId(smethod0.ShippingProviderId)));

            smethod1.Name   = smethod0.Name;
            smethod1.ZoneId = smethod0.ZoneId;
            var settings = new FlatRatePerOrderSettings();
            settings.Merge(smethod1.Settings);
            settings.Amount = Money.RoundCurrency(setting.Amount);
            smethod1.Settings.Merge(settings);
            #endregion

            //Act/Assert
            Assert.IsTrue(_application.OrderServices.ShippingMethods.Update(smethod1));
        }
Example #23
0
        public IList <ShippingMethod> GetAllShippingMethods()
        {
            ShippingMethod         tmpData;
            IList <ShippingMethod> list = new List <ShippingMethod>();

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = " select DELIV_CODE, DELIV_DESC from DEL_MTHD where ACTIVE ='T' ";

                ds = ReturnDataSet(Query, "", "DEL_MTHD", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //Map Properties
                    tmpData = new ShippingMethod();

                    tmpData.Company   = CurCompany;
                    tmpData.Name      = dr["DELIV_DESC"].ToString();
                    tmpData.ErpCode   = dr["DELIV_CODE"].ToString();
                    tmpData.IsFromErp = true;

                    list.Add(tmpData);
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetAllShippingMethods", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Example #24
0
        public void OrderService_CanUpdateShippingMethod()
        {
            var app = BaseTest.CreateHccAppInMemory();

            app.CurrentRequestContext.CurrentStore    = new Store();
            app.CurrentRequestContext.CurrentStore.Id = 230;

            var target = new ShippingMethod();

            target.Adjustment     = 1.23m;
            target.AdjustmentType = ShippingMethodAdjustmentType.Percentage;
            target.Bvin           = string.Empty;
            target.Name           = "Test Name";
            target.Settings.AddOrUpdate("MySetting", "MySetVal");
            target.ShippingProviderId = "123456";
            target.ZoneId             = -101;

            app.OrderServices.ShippingMethods.Create(target);
            Assert.AreNotEqual(string.Empty, target.Bvin, "Bvin should not be empty");

            target.Adjustment     = 1.95m;
            target.AdjustmentType = ShippingMethodAdjustmentType.Amount;
            target.Name           = "Test Name Updated";
            target.Settings.AddOrUpdate("MySetting", "MySetVal 2");
            target.ShippingProviderId = "1Update";
            target.ZoneId             = -100;
            Assert.IsTrue(app.OrderServices.ShippingMethods.Update(target));

            var actual = app.OrderServices.ShippingMethods.Find(target.Bvin);

            Assert.IsNotNull(actual, "Actual should not be null");

            Assert.AreEqual(actual.Adjustment, target.Adjustment);
            Assert.AreEqual(actual.AdjustmentType, target.AdjustmentType);
            Assert.AreEqual(actual.Bvin, target.Bvin);
            Assert.AreEqual(actual.Name, target.Name);
            Assert.AreEqual(actual.Settings["MySetting"], target.Settings["MySetting"]);
            Assert.AreEqual(actual.ShippingProviderId, target.ShippingProviderId);
            Assert.AreEqual(actual.ZoneId, target.ZoneId);
        }
Example #25
0
        protected void btnOk_Click(object sender, EventArgs e)
        {
            var type   = (ShippingType)int.Parse(ddlType.SelectedValue);
            var method = new ShippingMethod
            {
                Type                = type,
                Name                = txtName.Text,
                Description         = txtDescription.Text,
                Enabled             = type == ShippingType.FreeShipping,
                DisplayCustomFields = true,
                SortOrder           = txtSortOrder.Text.TryParseInt(),
                ZeroPriceMessage    = Resources.Resource.Admin_ShippingMethod_ZeroPriceMessage
            };

            TrialService.TrackEvent(TrialEvents.AddShippingMethod, method.Type.ToString());
            var id = ShippingMethodService.InsertShippingMethod(method);

            if (id != 0)
            {
                Response.Redirect("~/Admin/ShippingMethod.aspx?ShippingMethodID=" + id);
            }
        }
Example #26
0
        private void PrepareShippingMethodModel(ShippingMethodModel model, ShippingMethod shippingMethod)
        {
            if (shippingMethod != null)
            {
                var allFilters = _shippingService.GetAllShippingMethodFilters();
                var configUrls = allFilters
                                 .Select(x => x.GetConfigurationUrl(shippingMethod.Id))
                                 .Where(x => x.HasValue())
                                 .ToList();

                model.FilterConfigurationUrls = configUrls
                                                .Select(x => string.Concat("'", x, "'"))
                                                .OrderBy(x => x)
                                                .ToList();
            }
            else
            {
                model.FilterConfigurationUrls = new List <string>();
            }

            model.SelectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(shippingMethod);
        }
        protected override OpResult _Store(ShippingMethod _obj)
        {
            if (_obj == null)
            {
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "CostCentreAccountActivity object cannot be created as it is null"));
            }

            if (Exists(_obj))
            {
                ExecuteNonQuery(GetQuery_UpdateQuery(_obj));
                return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj));
            }

            ExecuteNonQuery(GetQuery_InsertQuery(_obj));
            if (_obj.ShippingMethodID == null)
            {
                _obj.ShippingMethodID = DbMgr.GetLastInsertID();
            }
            _obj.FromDb = true;

            return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj));
        }
        public override IQuery GetHsql(Object data)
        {
            StringBuilder  sql = new StringBuilder("select a from ShippingMethod a    where  ");
            ShippingMethod sh  = (ShippingMethod)data;

            if (sh != null)
            {
                Parms = new List <Object[]>();
                if (sh.ShpMethodID != 0)
                {
                    sql.Append(" a.ShpMethodID = :id     and   ");
                    Parms.Add(new Object[] { "id", sh.ShpMethodID });
                }

                if (sh.Company != null && sh.Company.CompanyID != 0)
                {
                    sql.Append(" a.Company.CompanyID= :id1     and   ");
                    Parms.Add(new Object[] { "id1", sh.Company.CompanyID });
                }

                if (!String.IsNullOrEmpty(sh.Name))
                {
                    sql.Append(" a.Name = :nom     and   ");
                    Parms.Add(new Object[] { "nom", sh.Name });
                }

                if (!String.IsNullOrEmpty(sh.ErpCode))
                {
                    sql.Append(" a.ErpCode = :nom1     and   ");
                    Parms.Add(new Object[] { "nom1", sh.ErpCode });
                }
            }
            sql = new StringBuilder(sql.ToString());
            sql.Append(" 1=1 order by a.ShpMethodID asc ");
            IQuery query = Factory.Session.CreateQuery(sql.ToString());

            SetParameters(query);
            return(query);
        }
        public void CalculateTotals_StandardCustomer_TotalEqualsCostPlusShipping(ShippingMethod shippingMethod)
        {
            var originAddress = CreateAddress(city: "city 1");

            _mocker.Use <IShippingCalculator>(new ShippingCalculator(originAddress));
            var destinationAddress = CreateAddress(city: "city 2");

            var target = _mocker.CreateInstance <CheckOutEngine>();

            var cart = new CartBuilder()
                       .WithShippingAddress(destinationAddress)
                       .WithShippingMethod(shippingMethod)
                       .WithItems(new List <Item>
            {
                CreateItem(price: 2, quantity: 3)
            })
                       .Build();

            var result = target.CalculateTotals(cart);

            Assert.Equal(2 * 3 + result.ShippingCost, result.Total);
        }
Example #30
0
        /// <summary>
        /// Gets a shipping method that has a zone for a specific country.
        /// </summary>
        /// <param name="client">Client</param>
        /// <param name="country">Country</param>
        /// <returns>Shipping method that has a zone for the specified country, or null if one was not found</returns>
        public static async Task <ShippingMethod> GetShippingMethodForCountry(Client client, string country)
        {
            Response <ShippingMethodQueryResult> shippingMethodQueryResponse = await client.ShippingMethods().QueryShippingMethodsAsync();

            if (!shippingMethodQueryResponse.Success || shippingMethodQueryResponse.Result.Count < 1)
            {
                return(null);
            }

            ShippingMethod shippingMethod  = null;
            var            shippingMethods = shippingMethodQueryResponse.Result.Results.Where(s => s.ZoneRates != null && s.ZoneRates.Count > 0);

            foreach (ShippingMethod s in shippingMethods)
            {
                foreach (ZoneRate zoneRate in s.ZoneRates)
                {
                    Response <Zone> zoneResponse = await client.Zones().GetZoneByIdAsync(zoneRate.Zone.Id);

                    if (zoneResponse.Success && zoneResponse.Result.Locations != null)
                    {
                        foreach (Location location in zoneResponse.Result.Locations)
                        {
                            if (location.Country.Equals(country, StringComparison.OrdinalIgnoreCase))
                            {
                                shippingMethod = s;
                                break;
                            }
                        }
                    }

                    if (shippingMethod != null)
                    {
                        break;
                    }
                }
            }

            return(shippingMethod);
        }
        void ApplyShippingPromotion(ShippingMethod shippingMethod, IEnumerable <Promotions.ShippingPromotionDiscount> shippingDiscounts)
        {
            var discountIncludedText = "(including promo discounts)";

            //Have to assign some kind of order to make sure this is calculated the same every time
            shippingDiscounts = shippingDiscounts.OrderBy(d => d.DiscountType);

            foreach (var discount in shippingDiscounts)
            {
                if (!discount.ShippingMethodIds.Contains(shippingMethod.Id))
                {
                    continue;
                }

                if (discount.DiscountType == Promotions.DiscountType.Fixed)
                {
                    shippingMethod.Freight = shippingMethod.Freight - discount.DiscountAmount;
                }
                else if (discount.DiscountType == Promotions.DiscountType.Percentage)
                {
                    shippingMethod.Freight = shippingMethod.Freight - (shippingMethod.Freight * discount.DiscountAmount);
                }

                if (!string.IsNullOrEmpty(shippingMethod.DisplayName))
                {
                    shippingMethod.DisplayName += discountIncludedText;
                }
                else
                {
                    shippingMethod.Name += discountIncludedText;
                }

                //Safety check
                if (shippingMethod.Freight < 0)
                {
                    shippingMethod.Freight = 0;
                }
            }
        }
Example #32
0
        /// <summary>
        /// Edits the rate table shipping method.
        /// </summary>
        //[TestMethod]
        //[Priority(20)]
        public void EditSM_RateTable()
        {
            #region Arrange
            var smethod0 = new ShippingMethod();
            var setting  = _irepo.GetEditSMInfo_RateTable(ref smethod0);
            var lstlevel = setting.GetLevels();
            var smethod1 = _application.OrderServices.ShippingMethods.FindAll(_application.CurrentStore.Id)
                           .FirstOrDefault(x => x.ShippingProviderId.Equals(GetShippingProviderId(smethod0.ShippingProviderId)));

            smethod1.Name   = smethod0.Name;
            smethod1.ZoneId = smethod0.ZoneId;
            var settings = new RateTableSettings();
            settings.Merge(smethod1.Settings);

            settings.RemoveLevel(lstlevel.FirstOrDefault());

            smethod1.Settings.Merge(settings);
            #endregion

            //Act/Assert
            Assert.IsTrue(_application.OrderServices.ShippingMethods.Update(smethod1));
        }
Example #33
0
        public ActionResult ShippingMethodEdit(int id)
        {
            if (!MyHelp.CheckAuth("shipping", "shippingMethod", EnumData.AuthType.Edit))
            {
                return(RedirectToAction("index", "main"));
            }

            Method = new GenericRepository <ShippingMethod>(db);

            ShippingMethod method = Method.Get(id);

            if (method == null)
            {
                return(HttpNotFound());
            }

            if (TryUpdateModel(method) && ModelState.IsValid)
            {
                Method.SaveChanges();

                MyHelp.Log("ShippingMethod", method.ID, "編輯運輸方式");
                return(RedirectToAction("shippingMethod", "shipping"));
            }

            Carriers = new GenericRepository <Carriers>(db);
            ViewData["carrierSelect"] = Carriers.GetAll(true).Where(c => c.IsEnable).OrderBy(c => c.ID).ToList();

            List <object> directLineSelect = new List <object>()
            {
                new { text = "無", value = (byte)0 }
            };

            directLineSelect.AddRange(db.DirectLine.AsNoTracking().Where(d => d.IsEnable).Select(d => new { text = d.Name, value = d.ID }).ToList());
            ViewData["directLineSelect"] = new SelectList(directLineSelect.AsEnumerable(), "value", "text", method.DirectLine);

            ViewBag.WCPScript = WebClientPrint.CreateScript(Url.Action("ProcessRequest", "WebClientPrintAPI", null, HttpContext.Request.Url.Scheme), Url.Action("PrintFile", "File", null, HttpContext.Request.Url.Scheme), HttpContext.Session.SessionID);
            return(View(method));
        }
Example #34
0
        //SHIPPING METHODS
        /// <summary>
        /// Get Shipping Methods from Dynamics GP
        /// </summary>
        /// <returns></returns>
        public IList <ShippingMethod> GetAllShippingMethods()
        {
            ShippingMethod         tmpData;
            IList <ShippingMethod> list = new List <ShippingMethod>();

            try
            {
                //Lamar los documents que necesita del Erp usando econnect
                ds = DynamicsGP_ec.GetDataSet(DynamicsGP_ec.RetreiveData("WSShippingMethod", false, 2, 0, "", true));

                if (ds.Tables.Count == 0)
                {
                    return(null);
                }

                //En el dataset, Tables: 1 - Methods
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    //Map Properties
                    tmpData = new ShippingMethod();

                    tmpData.Company   = CurCompany;
                    tmpData.Name      = dr["SHIPMTHD"].ToString() + ", " + dr["SHMTHDSC"].ToString();
                    tmpData.ErpCode   = dr["SHIPMTHD"].ToString();
                    tmpData.IsFromErp = true;

                    list.Add(tmpData);
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetAllShippingMethods", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Example #35
0
        /// <summary>
        /// Edits the FedEx shipping method.
        /// </summary>
        //[TestMethod]
        //[Priority(22)]
        public void EditSM_FedEx()
        {
            #region Arrange
            var smethod0 = new ShippingMethod();
            var store    = _application.CurrentStore;
            var setting  = _irepo.GetEditSMInfo_FedEx(ref store, ref smethod0);

            var smethod1 = _application.OrderServices.ShippingMethods.FindAll(_application.CurrentStore.Id)
                           .FirstOrDefault(x => x.ShippingProviderId.Equals(GetShippingProviderId(smethod0.ShippingProviderId)));

            smethod1.Name   = smethod0.Name;
            smethod1.ZoneId = smethod0.ZoneId;

            var settings = new FedExServiceSettings();
            settings.Merge(smethod1.Settings);

            settings.ServiceCode = setting.ServiceCode;
            settings.Packaging   = setting.Packaging;

            smethod1.Settings.Merge(settings);

            _application.CurrentStore.Settings.ShippingFedExKey                      = store.Settings.ShippingFedExKey;
            _application.CurrentStore.Settings.ShippingFedExPassword                 = store.Settings.ShippingFedExPassword;
            _application.CurrentStore.Settings.ShippingFedExAccountNumber            = store.Settings.ShippingFedExAccountNumber;
            _application.CurrentStore.Settings.ShippingFedExMeterNumber              = store.Settings.ShippingFedExMeterNumber;
            _application.CurrentStore.Settings.ShippingFedExDefaultPackaging         = store.Settings.ShippingFedExDefaultPackaging;
            _application.CurrentStore.Settings.ShippingFedExDropOffType              = store.Settings.ShippingFedExDropOffType;
            _application.CurrentStore.Settings.ShippingFedExForceResidentialRates    = store.Settings.ShippingFedExForceResidentialRates;
            _application.CurrentStore.Settings.ShippingFedExUseListRates             = store.Settings.ShippingFedExUseListRates;
            _application.CurrentStore.Settings.ShippingFedExDiagnostics              = store.Settings.ShippingFedExDiagnostics;
            _application.CurrentStore.Settings.ShippingFedExUseDevelopmentServiceUrl = store.Settings.ShippingFedExUseDevelopmentServiceUrl;

            smethod1.Settings.Merge(settings);
            #endregion

            //Act/Assert
            Assert.IsTrue(_application.OrderServices.ShippingMethods.Update(smethod1));
        }
Example #36
0
        public void CreateShipMethodTest()
        {
            //Arrange
            ShippingMethod newMethod = new ShippingMethod
            {
                Carrier = "Local",
                Method  = "Local Pickup"
            };

            ShipMethodManager mgr = new ShipMethodManager();

            mgr.CreateShipMethod(newMethod);

            using (var context = DbContextFactory.Create())   //no 'NEW' b/c of static class
            {
                var query = from ShippingMethod s in context.ShippingMethod
                            where s.Method == newMethod.Method
                            select s;

                //Assert.AreEqual(5, query.First().Id);
                Assert.AreEqual(newMethod.Method, query.First().Method);
            }
        }
Example #37
0
        public static ShippingMethod ToShippingMethod(this cartDto.ShippingRate shippingRate, Currency currency, IEnumerable <Currency> availCurrencies)
        {
            var rateCurrency = availCurrencies.FirstOrDefault(x => x.Equals(shippingRate.Currency)) ?? new Currency(new Language(currency.CultureName), shippingRate.Currency);
            var ratePrice    = new Money(shippingRate.Rate ?? 0, rateCurrency);
            var rateDiscount = new Money(shippingRate.DiscountAmount ?? 0, rateCurrency);

            if (rateCurrency != currency)
            {
                ratePrice    = ratePrice.ConvertTo(currency);
                rateDiscount = rateDiscount.ConvertTo(currency);
            }

            var result = new ShippingMethod(currency);

            result.OptionDescription = shippingRate.OptionDescription;
            result.OptionName        = shippingRate.OptionName;

            result.Price          = ratePrice;
            result.DiscountAmount = rateDiscount;

            if (shippingRate.ShippingMethod != null)
            {
                result.LogoUrl  = shippingRate.ShippingMethod.LogoUrl;
                result.Name     = shippingRate.ShippingMethod.Name;
                result.Priority = shippingRate.ShippingMethod.Priority ?? 0;
                result.TaxType  = shippingRate.ShippingMethod.TaxType;

                result.ShipmentMethodCode = shippingRate.ShippingMethod.Code;
                if (shippingRate.ShippingMethod.Settings != null)
                {
                    result.Settings = shippingRate.ShippingMethod.Settings.Where(x => !x.ValueType.EqualsInvariant("SecureString"))
                                      .Select(x => x.JsonConvert <platformDto.Setting>().ToSettingEntry()).ToList();
                }
            }

            return(result);
        }
Example #38
0
        private void SeedShippingMethods(StoreContext context)
        {
            var shippingMethod1 =
                new ShippingMethod
            {
                Id         = 1,
                Name       = "DHL Parcel",
                MaximumPcs = 100,
                Price      = 16.00M
            };

            context.Set <ShippingMethod>().AddOrUpdate(shippingMethod1);

            var shippingMethod2 =
                new ShippingMethod
            {
                Id         = 2,
                Name       = "InPost 48",
                MaximumPcs = 3,
                Price      = 9.00M
            };

            context.Set <ShippingMethod>().AddOrUpdate(shippingMethod2);

            var shippingMethod3 =
                new ShippingMethod
            {
                Id         = 3,
                Name       = "Post office",
                MaximumPcs = 5,
                Price      = 12.00M
            };

            context.Set <ShippingMethod>().AddOrUpdate(shippingMethod3);

            context.SaveChanges();
        }
        void SetShippingMethod(ShippingMethod shippingMethod, ShoppingCart cart, Customer customer)
        {
            int    shippingMethodId;
            string shippingMethodNameForDatabase;

            if (cart.ShippingIsFree &&
                !AppConfigProvider.GetAppConfigValue <bool>("FreeShippingAllowsRateSelection") &&
                !AppLogic
                .AppConfig("ShippingMethodIDIfFreeShippingIsOn")
                .ParseAsDelimitedList <int>()
                .Contains(shippingMethod.Id))
            {
                shippingMethodId = 0;
                shippingMethodNameForDatabase = string.Format(
                    "{0} : {1}",
                    StringResourceProvider.GetString("shoppingcart.aspx.16"),
                    cart.GetFreeShippingReason());
            }
            else
            {
                shippingMethodId = shippingMethod.Id;
                shippingMethodNameForDatabase = Shipping.GetActiveShippingCalculationID() != Shipping.ShippingCalculationEnum.UseRealTimeRates
                                        ? Shipping.GetShippingMethodDisplayName(shippingMethod.Id, null)
                                        : Shipping.GetFormattedRealTimeShippingMethodForDatabase(shippingMethod.Name, shippingMethod.Freight, shippingMethod.VatRate);
            }

            // Update the persisted checkout context
            PersistedCheckoutContextProvider.SaveCheckoutContext(
                customer,
                new PersistedCheckoutContextBuilder()
                .From(PersistedCheckoutContextProvider.LoadCheckoutContext(customer))
                .WithSelectedShippingMethodId(shippingMethodId)
                .Build());

            // Update the database for legacy cases
            ShippingMethodCartItemApplicator.UpdateCartItemsShippingMethod(customer, cart, shippingMethod);
        }
Example #40
0
        /// <summary>
        /// Adds the UPS shipping method.
        /// </summary>
        //[TestMethod]
        //[Priority(23)]
        public void AddSM_UPS()
        {
            #region Arrange
            var smethod0     = new ShippingMethod();
            var store        = _application.CurrentStore;
            var setting      = _irepo.GetAddSMInfo_UPS(ref store, ref smethod0);
            var spproviderid = GetShippingProviderId(smethod0.ShippingProviderId);
            var smethod1     = new ShippingMethod
            {
                Name               = smethod0.Name,
                StoreId            = _application.CurrentStore.Id,
                ZoneId             = smethod0.ZoneId,
                AdjustmentType     = ShippingMethodAdjustmentType.Amount,
                Adjustment         = 0,
                ShippingProviderId = spproviderid,
            };

            var settings = new UPSServiceSettings();
            settings.Merge(smethod1.Settings);
            settings.GetAllRates       = setting.GetAllRates;
            settings.ServiceCodeFilter = SetServicesFilterCode("UPS", setting.ServiceCodeFilter);

            smethod1.Settings.Merge(settings);

            _application.CurrentStore.Settings.ShippingFedExAccountNumber  = store.Settings.ShippingUpsAccountNumber;
            _application.CurrentStore.Settings.ShippingUpsForceResidential = store.Settings.ShippingUpsForceResidential;
            _application.CurrentStore.Settings.ShippingUpsPickupType       = store.Settings.ShippingUpsPickupType;
            _application.CurrentStore.Settings.ShippingUpsDefaultService   = store.Settings.ShippingUpsDefaultService;
            _application.CurrentStore.Settings.ShippingUpsDefaultPackaging = store.Settings.ShippingUpsDefaultPackaging;
            _application.CurrentStore.Settings.ShippingUpsSkipDimensions   = store.Settings.ShippingUpsSkipDimensions;
            _application.CurrentStore.Settings.ShippingUPSDiagnostics      = store.Settings.ShippingUPSDiagnostics;
            #endregion

            //Act/Assert
            Assert.IsTrue(_application.OrderServices.ShippingMethods.Create(smethod1));
        }
        public IShippingCostCalculator GetCalculator(ShippingMethod shippingMethod)
        {
            //switch (shippingMethod)
            //{
            //    case ShippingMethod.Express:
            //        return new ExpressShippingCalculator();
            //    case ShippingMethod.PriceSaver:
            //        return new PriceSaverShippingCalculator();
            //    case ShippingMethod.Standard:
            //    default:
            //        return new StandardShippingCalculator();
            //}

            return (from c in _calculators
                    let handles = c as IHandleShippingMethod
                    where handles != null
                    && handles.CanHandle(shippingMethod)
                    select c).First();

            //return (from c in this.candidates
            //        let t = c.GetType()
            //        where t.Name.StartsWith(shippingMethod.ToString())
            //        select c).First();
        }
Example #42
0
        public IShippingCostCalculator GetCalculator(ShippingMethod shippingMethod)
        {
            //switch (shippingMethod)
            //{
            //    case ShippingMethod.Express:
            //        return new ExpressShippingCalculator();
            //    case ShippingMethod.PriceSaver:
            //        return new PriceSaverShippingCalculator();
            //    case ShippingMethod.Standard:
            //    default:
            //        return new StandardShippingCalculator();
            //}

            return((from c in _calculators
                    let handles = c as IHandleShippingMethod
                                  where handles != null &&
                                  handles.CanHandle(shippingMethod)
                                  select c).First());

            //return (from c in this.candidates
            //        let t = c.GetType()
            //        where t.Name.StartsWith(shippingMethod.ToString())
            //        select c).First();
        }
        private void CreateShippingMethod(string name, decimal shippingFee, Currency currency, PriceGroup priceGroup)
        {
            var shippingMethod = ShippingMethod.SingleOrDefault(x => x.Name == name) ??
                                 new ShippingMethodFactory().NewWithDefaults(name);

            var shippingMethodPrice =
                shippingMethod.ShippingMethodPrices.FirstOrDefault(p =>
                                                                   p.PriceGroup.Currency.ISOCode == currency.ISOCode);

            if (shippingMethodPrice == null)
            {
                shippingMethodPrice = new ShippingMethodPrice()
                {
                    PriceGroup = priceGroup
                };
                shippingMethod.AddShippingMethodPrice(shippingMethodPrice);
            }

            shippingMethodPrice.Price      = shippingFee;
            shippingMethodPrice.PriceGroup = priceGroup;
            shippingMethodPrice.Save();

            shippingMethod.ClearEligibleCountries();
            foreach (var country in _countries)
            {
                shippingMethod.AddEligibleCountry(country);
            }

            shippingMethod.ClearEligibilePaymentMethods();
            foreach (var method in _paymentMethods)
            {
                shippingMethod.AddEligiblePaymentMethod(method);
            }

            shippingMethod.Save();
        }
Example #44
0
        /// <summary>
        /// Edits the rate per weight formula shipping method.
        /// </summary>
        //[TestMethod]
        //[Priority(18)]
        public void EditSM_RatePerWeightFormula()
        {
            #region Arrange
            var smethod0 = new ShippingMethod();
            var setting  = _irepo.GetEditSMInfo_RatePerWeightFormula(ref smethod0);

            var smethod1 = _application.OrderServices.ShippingMethods.FindAll(_application.CurrentStore.Id)
                           .FirstOrDefault(x => x.ShippingProviderId.Equals(GetShippingProviderId(smethod0.ShippingProviderId)));

            smethod1.Name   = smethod0.Name;
            smethod1.ZoneId = smethod0.ZoneId;
            var settings = new RatePerWeightFormulaSettings();
            settings.Merge(smethod1.Settings);
            settings.BaseAmount             = setting.BaseAmount;
            settings.BaseWeight             = setting.BaseWeight;
            settings.AdditionalWeightCharge = setting.AdditionalWeightCharge;
            settings.MaxWeight = setting.MaxWeight;
            settings.MinWeight = setting.MinWeight;
            smethod1.Settings.Merge(settings);
            #endregion

            //Act/Assert
            Assert.IsTrue(_application.OrderServices.ShippingMethods.Update(smethod1));
        }
 public bool CanHandle(ShippingMethod shippingMethod)
 {
     return shippingMethod == ShippingMethod.Express;
 }
Example #46
0
        public void ShipProduct(Product product, ShippingMethod method)
        {
            var shipping = CalculateShippingCost(method);
            var total = shipping + product.Price;

            // Charge Customer the {total} amount
            // Not Implemented

            product.Ship(total);
        }
Example #47
0
        public async Task<CartBuilder> AddShipmentAsync(ShippingMethod shippingMethod)
        {
            var shipment = shippingMethod.ToShipmentModel(_currency);

            _cart.Shipments.Clear();
            _cart.Shipments.Add(shipment);

            await EvaluatePromotionsAsync();

            return this;
        }
Example #48
0
 public void Create(ShippingMethod method)
 {
     _repository.Insert(method);
 }
 public void Disable(ShippingMethod method)
 {
     method.Disable();
 }
 public bool CanHandle(ShippingMethod shippingMethod)
 {
     return shippingMethod == ShippingMethod.Standard;
 }
 public decimal GetShippingRate(ShippingMethod method, ShippingRateCalculationContext context)
 {
     return 0m;
 }
 public string GetEditorVirtualPath(ShippingMethod shippingMethod)
 {
     return "~/Areas/" + Strings.AreaName + "/Views/Config.cshtml";
 }
 public bool CanHandle(ShippingMethod shippingMethod)
 {
     return shippingMethod == ShippingMethod.PriceSaver;
 }
Example #54
0
 public ShippingMethodEnabled(ShippingMethod method)
 {
     ShippingMethodId = method.Id;
 }
 public void Save(ShippingMethod shippingMethod)
 {
     _shippingMethods.Value.Save(shippingMethod);
 }
Example #56
0
 public ShippingMethod SaveShippingMethod(ShippingMethod data)
 {
     try {
     SetService();  return SerClient.SaveShippingMethod(data); }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
         SerClient.Abort(); 
     }
 }
 public void Enable(ShippingMethod method)
 {
     method.Enable();
 }
Example #58
0
 public void DeleteShippingMethod(ShippingMethod data)
 {
     try {
     SetService();  SerClient.DeleteShippingMethod(data); }
     finally
     {
         SerClient.Close();
         if (SerClient.State == CommunicationState.Faulted)
         SerClient.Abort(); 
     }
 }
 public ShippingRateProviderEditor GetEditor(ShippingMethod shippingMethod)
 {
     return new ShippingRateProviderEditor("~/Areas/" + Strings.AreaName + "/Views/Config.cshtml");
 }
Example #60
0
 public void ChangeShippingMethod(ShoppingCart cart, ShippingMethod shippingMethod)
 {
     if (cart.ShippingMethod == null || cart.ShippingMethod.Id != shippingMethod.Id)
     {
         cart.ShippingMethod = shippingMethod;
         _repository.Database.SaveChanges();
     }
 }