Пример #1
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <param name="error">Error</param>
        /// <returns>Tax</returns>
        public decimal GetTaxRate(CalculateTaxRequest calculateTaxRequest, ref string error)
        {
            if (calculateTaxRequest.Address == null)
            {
                error = "Address is not set";
                return(0);
            }

            decimal taxRate = decimal.Zero;

            int taxClassID = 0;

            if (calculateTaxRequest.TaxClassId > 0)
            {
                taxClassID = calculateTaxRequest.TaxClassId;
            }
            else
            {
                var productVariant = calculateTaxRequest.Item;
                if (productVariant != null)
                {
                    taxClassID = productVariant.TaxCategoryId;
                }
            }
            taxRate = GetTaxRate(calculateTaxRequest.Address, taxClassID);

            return(taxRate);
        }
        public void CalculateTaxForOrder_TaxJar_ProperRequest_WithNexusAddresses_ReturnsAmountToCollectAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "19.99"
            });
            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "9.95"
            });

            var nexusItems = new List <CalculateTax_NexusAddress>();

            nexusItems.Add(new CalculateTax_NexusAddress {
                country = "US", state = "FL", zip = "32801"
            });
            nexusItems.Add(new CalculateTax_NexusAddress {
                country = "US", state = "MO", zip = "63101"
            });

            var taxRequest     = new CalculateTaxRequest("US", "Orlando", "32801", "FL", null, "US", "Kansas City", "64155", "MO", null, "29.94", "7.99", lineItems, nexusItems);
            var taxjarService  = new TaxJar_Calculator("https://api.taxjar.com/v2/");
            var expectedAmount = 2.9;

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount);
        }
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            //the tax rate calculation by fixed rate
            if (!_countryStateZipSettings.CountryStateZipEnabled)
            {
                result.TaxRate = _settingService.GetSettingByKey <decimal>(string.Format(FixedOrByCountryStateZipDefaults.FixedRateSettingsKey, calculateTaxRequest.TaxCategoryId));
                return(result);
            }

            //the tax rate calculation by country & state & zip
            if (calculateTaxRequest.Address == null)
            {
                result.Errors.Add("Address is not set");
                return(result);
            }

            //first, load all tax rate records (cached) - loaded only once
            var cacheKey    = ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY;
            var allTaxRates = _cacheManager.Get(cacheKey, () => _taxRateService.GetAllTaxRates().Select(taxRate => new TaxRateForCaching
            {
                Id              = taxRate.Id,
                StoreId         = taxRate.StoreId,
                TaxCategoryId   = taxRate.TaxCategoryId,
                CountryId       = taxRate.CountryId,
                StateProvinceId = taxRate.StateProvinceId,
                Zip             = taxRate.Zip,
                Percentage      = taxRate.Percentage
            }).ToList());

            var storeId         = calculateTaxRequest.CurrentStoreId;
            var taxCategoryId   = calculateTaxRequest.TaxCategoryId;
            var countryId       = calculateTaxRequest.Address.Country?.Id ?? 0;
            var stateProvinceId = calculateTaxRequest.Address.StateProvince?.Id ?? 0;
            var zip             = calculateTaxRequest.Address.ZipPostalCode?.Trim() ?? string.Empty;

            var existingRates = allTaxRates.Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId);

            //filter by store
            var matchedByStore = existingRates.Where(taxRate => storeId == taxRate.StoreId || taxRate.StoreId == 0);

            //filter by state/province
            var matchedByStateProvince = matchedByStore.Where(taxRate => stateProvinceId == taxRate.StateProvinceId || taxRate.StateProvinceId == 0);

            //filter by zip
            var matchedByZip = matchedByStateProvince.Where(taxRate => string.IsNullOrWhiteSpace(taxRate.Zip) || taxRate.Zip.Equals(zip, StringComparison.InvariantCultureIgnoreCase));

            //sort from particular to general, more particular cases will be the first
            var foundRecords = matchedByZip.OrderBy(r => r.StoreId == 0).ThenBy(r => r.StateProvinceId == 0).ThenBy(r => string.IsNullOrEmpty(r.Zip));

            var foundRecord = foundRecords.FirstOrDefault();

            if (foundRecord != null)
            {
                result.TaxRate = foundRecord.Percentage;
            }

            return(result);
        }
Пример #4
0
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            if (calculateTaxRequest.Address == null)
            {
                result.Errors.Add("Address is not set");
                return(result);
            }

            if (_taxSettings.EuVatEnabled)
            {
                if (!(calculateTaxRequest.Address.Country?.SubjectToVat ?? false))
                {
                    // Fallback to fixed rate (merchant country VAT rate).
                    result.TaxRate = _settingService.GetSettingByKey <decimal>($"Tax.TaxProvider.FixedRate.TaxCategoryId{calculateTaxRequest.TaxCategoryId}");
                    return(result);
                }
            }

            var taxRates = _taxRateService.GetAllTaxRates(
                calculateTaxRequest.TaxCategoryId,
                calculateTaxRequest.Address.Country?.Id ?? 0,
                calculateTaxRequest.Address.StateProvince?.Id ?? 0,
                calculateTaxRequest.Address.ZipPostalCode);

            if (taxRates.Any())
            {
                result.TaxRate = taxRates[0].Percentage;
            }

            return(result);
        }
Пример #5
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult()
            {
                TaxRate = GetTaxRate(calculateTaxRequest.TaxCategoryId)
            };

            return(result);
        }
Пример #6
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public Task <CalculateTaxResult> GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult
            {
                TaxRate = GetTaxRate(calculateTaxRequest.TaxCategoryId)
            };

            return(Task.FromResult(result));
        }
Пример #7
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult()
            {
                TaxRate = decimal.Zero
            };

            return(result);
        }
Пример #8
0
        public void CallTaxService_GenerateTaxJarCalculator_CalculateTaxForOrder_NoLineItems_ReturnsArgumentException()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            var taxRequest    = new CalculateTaxRequest("US", "Kansas City", "64", "MO", null, "US", "Orlando", "32801", "FL", null, "29.94", "7.99", lineItems, null);
            var taxjarService = new TaxService.Services.TaxService(new TaxJar_Calculator("https://api.taxjar.com/v2/"));

            Assert.ThrowsException <System.ArgumentException>(() => taxjarService.CalculateTaxForOrder(taxRequest));
        }
Пример #9
0
        public HttpResponseMessage CalculateTaxForOrder([FromBody] CalculateTaxRequest request)
        {
            var    response = Request.CreateResponse();
            string result   = "";

            //Define Tax Service Class
            Services.TaxService taxService;

            try
            {
                //Instantiate
                //TODO: Again, we need to think of a way to have either the service decide, or the calling application decide.
                taxService = new Services.TaxService(new TaxJar_Calculator());

                //Call service's Calculate Tax function.
                var objResult = taxService.CalculateTaxForOrder(request);
                //serialize for HTTP
                result = JsonConvert.SerializeObject(objResult);
                response.StatusCode = HttpStatusCode.OK;
            }
            catch (ArgumentException ex)
            {
                //Return 400 level errors here if any are caught
                if (ex.ParamName == "Country")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Country code requires two characters"));
                }
                if (ex.ParamName == "State")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "State code requires two characters"));
                }
                if (ex.ParamName == "ZipCode")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Zip Code is Required"));
                }
                if (ex.ParamName == "US ZipCode")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "US Zip Code Must Be at least 3 characters long"));
                }
                if (ex.ParamName == "CA ZipCode")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "CA Zip Code Must Be 6 characters long"));
                }
                if (ex.ParamName == "No Line Items")
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "An order is required to calculate the tax"));
                }
            }

            //Format for HTTP
            response.Content = new StringContent(result, Encoding.UTF8, "application/json");
            return(response);
        }
Пример #10
0
        public void CallTaxService_GenerateTaxJarCalculator_CalculateTaxForOrder_ShortCAZipCode_ReturnsArgumentException()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "16.95"
            });

            var taxRequest    = new CalculateTaxRequest("CA", null, "V6", "BC", null, "CA", null, "M5T 2T6", "ON", null, "16.95", "10", lineItems, null);
            var taxjarService = new TaxService.Services.TaxService(new TaxJar_Calculator("https://api.taxjar.com/v2/"));

            Assert.ThrowsException <System.ArgumentException>(() => taxjarService.CalculateTaxForOrder(taxRequest));
        }
        public void CalculateTaxForOrder_TaxJar_ShortUSZipCode_ReturnsArgumentException()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "19.99"
            });

            var taxRequest    = new CalculateTaxRequest("US", "Kansas City", "64", "MO", null, "US", "Orlando", "32801", "FL", null, "29.94", "7.99", lineItems, null);
            var taxjarService = new TaxJar_Calculator("https://api.taxjar.com/v2/");

            Assert.ThrowsException <System.ArgumentException>(() => taxjarService.CalculateTaxForOrder(taxRequest));
        }
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            if (calculateTaxRequest.Address == null)
            {
                return new CalculateTaxResult {
                           Errors = new List <string> {
                               "Address is not set"
                           }
                }
            }
            ;

            var cacheKey = string.Format(TAXRATE_KEY,
                                         !string.IsNullOrEmpty(calculateTaxRequest.Address.ZipPostalCode) ? calculateTaxRequest.Address.ZipPostalCode : string.Empty,
                                         calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.Id : 0,
                                         !string.IsNullOrEmpty(calculateTaxRequest.Address.City) ? calculateTaxRequest.Address.City : string.Empty);

            // we don't use standard way _cacheManager.Get() due the need write errors to CalculateTaxResult
            if (_cacheManager.IsSet(cacheKey))
            {
                return new CalculateTaxResult {
                           TaxRate = _cacheManager.Get <decimal>(cacheKey)
                }
            }
            ;

            var taxJarManager = new TaxJarManager {
                Api = _taxJarSettings.ApiToken
            };
            var result = taxJarManager.GetTaxRate(
                calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.TwoLetterIsoCode : null,
                calculateTaxRequest.Address.City,
                calculateTaxRequest.Address.Address1,
                calculateTaxRequest.Address.ZipPostalCode);

            if (!result.IsSuccess)
            {
                return new CalculateTaxResult {
                           Errors = new List <string> {
                               result.ErrorMessage
                           }
                }
            }
            ;

            _cacheManager.Set(cacheKey, result.Rate.TaxRate * 100, 60);
            return(new CalculateTaxResult {
                TaxRate = result.Rate.TaxRate * 100
            });
        }
        public void CalculateTaxForOrder_TaxJar_ProperRequest_Canada_ReturnsAmountToCollectAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "16.95"
            });

            var taxRequest     = new CalculateTaxRequest("CA", null, "V6G 3E", "BC", null, "CA", null, "M5T 2T6", "ON", null, "16.95", "10", lineItems, null);
            var taxjarService  = new TaxJar_Calculator("https://api.taxjar.com/v2/");
            var expectedAmount = 3.5; //weirdly no extra taxes?

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount, 0.0);
        }
        public void CalculateTaxForOrder_TaxJar_ProperRequest_US_CAExemption_ReturnsAmountToCollectAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                id = "3", quantity = "1", unit_price = "16.95", product_tax_code = "40030"
            });

            var taxRequest     = new CalculateTaxRequest("US", "San Francisco", "94111", "CA", "600 Montgomery St", "US", "Campbell", "95008", "CA", "33 N. First Street", "16.95", "10", lineItems, null);
            var taxjarService  = new TaxJar_Calculator("https://api.taxjar.com/v2/");
            var expectedAmount = 0.0; //weirdly no extra taxes?

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount, 0.0);
        }
        public void CalculateTaxForOrder_TaxJar_ProperRequest_NoNexusAddresses_ReturnsAmountToCollectAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                id = "3", quantity = "1", unit_price = "16.95", product_tax_code = "40030"
            });

            var taxRequest     = new CalculateTaxRequest("US", "San Francisco", "94111", "CA", "600 Montgomery St", "US", "Orlando", "32801", "FL", "200 S. Orange Ave", "16.95", "10", lineItems, null);
            var taxjarService  = new TaxJar_Calculator("https://api.taxjar.com/v2/");
            var expectedAmount = 0.0; //for some reason, probably an error on their part.

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount, 0.0);
        }
Пример #16
0
        public void CallTaxService_GenerateTaxJarCalculator_CalculateTaxForOrder_ReturnsTotalTaxAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "15.0", product_tax_code = "31000"
            });

            var taxRequest     = new CalculateTaxRequest("US", null, "07001", "NJ", null, "US", null, "07446", "NJ", null, "16.50", "1.5", lineItems, null);
            var taxjarService  = new TaxService.Services.TaxService(new TaxJar_Calculator("https://api.taxjar.com/v2/"));
            var expectedAmount = 1.09;

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount, 0.0);
        }
        public void CalculateTaxForOrder_TaxJar_ProperRequest_US_NYExemption_ReturnsAmountToCollectAsDouble()
        {
            //arrange
            var lineItems = new List <CalculateTax_LineItem>();

            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "19.99", product_tax_code = "20010"
            });
            lineItems.Add(new CalculateTax_LineItem {
                quantity = "1", unit_price = "9.95", product_tax_code = "20010"
            });

            var taxRequest     = new CalculateTaxRequest("US", "Delmar", "12054", "NY", null, "US", "Mahopac", "10541", "NY", null, "29.94", "7.99", lineItems, null);
            var taxjarService  = new TaxJar_Calculator("https://api.taxjar.com/v2/");
            var expectedAmount = 1.98;

            var actualAmount = taxjarService.CalculateTaxForOrder(taxRequest);

            Assert.AreEqual(expectedAmount, actualAmount);
        }
Пример #18
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            if (calculateTaxRequest.Address == null)
            {
                result.Errors.Add("Address is not set");
                return(result);
            }

            var taxRates = _taxRateService.GetAllTaxRates(calculateTaxRequest.TaxCategoryId,
                                                          calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.Id: 0,
                                                          calculateTaxRequest.Address.StateProvince != null ? calculateTaxRequest.Address.StateProvince.Id : 0,
                                                          calculateTaxRequest.Address.ZipPostalCode);

            if (taxRates.Count > 0)
            {
                result.TaxRate = taxRates[0].Percentage;
            }

            return(result);
        }
Пример #19
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <param name="error">Error</param>
        /// <returns>Tax</returns>
        public decimal GetTaxRate(CalculateTaxRequest calculateTaxRequest, ref string error)
        {
            decimal taxRate = decimal.Zero;

            int taxClassId = 0;

            if (calculateTaxRequest.TaxClassId > 0)
            {
                taxClassId = calculateTaxRequest.TaxClassId;
            }
            else
            {
                var productVariant = calculateTaxRequest.Item;
                if (productVariant != null)
                {
                    taxClassId = productVariant.TaxCategoryId;
                }
            }
            taxRate = GetTaxRate(taxClassId);

            return(taxRate);
        }
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public async Task <CalculateTaxResult> GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            if (calculateTaxRequest.Address == null)
            {
                result.Errors.Add("Address is not set");
                return(result);
            }

            const string cacheKey    = ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY;
            var          allTaxRates = await _cacheManager.GetAsync(cacheKey, async() =>
            {
                var taxes = await _taxRateService.GetAllTaxRates();
                return(taxes.Select(x => new TaxRateForCaching
                {
                    Id = x.Id,
                    StoreId = x.StoreId,
                    TaxCategoryId = x.TaxCategoryId,
                    CountryId = x.CountryId,
                    StateProvinceId = x.StateProvinceId,
                    Zip = x.Zip,
                    Percentage = x.Percentage
                }));
            });

            var storeId         = _storeContext.CurrentStore.Id;
            var taxCategoryId   = calculateTaxRequest.TaxCategoryId;
            var countryId       = calculateTaxRequest.Address.CountryId;
            var stateProvinceId = calculateTaxRequest.Address.StateProvinceId;
            var zip             = calculateTaxRequest.Address.ZipPostalCode;

            if (zip == null)
            {
                zip = string.Empty;
            }
            zip = zip.Trim();

            var existingRates = allTaxRates.Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId).ToList();

            //filter by store
            var matchedByStore = existingRates.Where(taxRate => storeId == taxRate.StoreId).ToList();

            //not found? use the default ones (ID == 0)
            if (!matchedByStore.Any())
            {
                matchedByStore.AddRange(existingRates.Where(taxRate => string.IsNullOrEmpty(taxRate.StoreId)));
            }

            //filter by state/province
            var matchedByStateProvince = matchedByStore.Where(taxRate => stateProvinceId == taxRate.StateProvinceId).ToList();

            //not found? use the default ones (ID == 0)
            if (!matchedByStateProvince.Any())
            {
                matchedByStateProvince.AddRange(matchedByStore.Where(taxRate => string.IsNullOrEmpty(taxRate.StateProvinceId)));
            }

            //filter by zip
            var matchedByZip = matchedByStateProvince.Where(taxRate => (string.IsNullOrEmpty(zip) && string.IsNullOrEmpty(taxRate.Zip)) || zip.Equals(taxRate.Zip, StringComparison.OrdinalIgnoreCase)).ToList();

            if (!matchedByZip.Any())
            {
                matchedByZip.AddRange(matchedByStateProvince.Where(taxRate => string.IsNullOrWhiteSpace(taxRate.Zip)));
            }

            if (matchedByZip.Any())
            {
                result.TaxRate = matchedByZip[0].Percentage;
            }

            return(result);
        }
Пример #21
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <param name="error">Error</param>
        /// <returns>Tax</returns>
        public decimal GetTaxRate(CalculateTaxRequest calculateTaxRequest, ref string error)
        {
            var address = calculateTaxRequest.Address;

            if (address == null)
            {
                error = "Billing address is not set";
                return(0);
            }
            if (address.Country == null)
            {
                error = "Country is not set";
                return(0);
            }

            //**************************************************************************************************************
            // As a Registered StrikeIron user, you can authenticate to a StrikeIron web service with either a
            // UserID/Password combination or a License Key.  If you wish to use a License Key,
            // assign this value to the UserID field and set the Password field to null.
            //**************************************************************************************************************
            string userID   = SettingManager.GetSettingValue("Tax.TaxProvider.StrikeIron.UserID");
            string password = SettingManager.GetSettingValue("Tax.TaxProvider.StrikeIron.Password");
            //if (Password == " " || !String.IsNullOrEmpty(Password))
            //    Password = String.Empty;
            //**************************************************************************************************************

            decimal taxRate = decimal.Zero;

            if (address.Country.TwoLetterIsoCode.ToLower() == "us")
            {
                if (String.IsNullOrEmpty(address.ZipPostalCode))
                {
                    error = "Zip is not provided";
                    return(0);
                }
                taxRate = GetTaxRateUSA(address.ZipPostalCode, userID, password, ref error);
            }
            else if (address.Country.TwoLetterIsoCode.ToLower() == "ca")
            {
                if (address.StateProvince == null)
                {
                    error = "Province is not set";
                    return(0);
                }
                taxRate = GetTaxRateCanada(address.StateProvince.Abbreviation, userID, password, ref error);
            }
            else
            {
                error = "Tax can be calculated only for USA zip or Canada province";
                return(0);
            }

            if (String.IsNullOrEmpty(error))
            {
                return(taxRate * 100);
            }
            else
            {
                return(0);
            }
        }
Пример #22
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            if (calculateTaxRequest.Address == null)
            {
                result.Errors.Add("Address is not set");
                return(result);
            }

            //first, load all tax rate records (cached) - loaded only once
            string cacheKey    = ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY;
            var    allTaxRates = _cacheManager.Get(cacheKey, () =>
                                                   _taxRateService
                                                   .GetAllTaxRates()
                                                   .Select(x => new TaxRateForCaching
            {
                Id              = x.Id,
                StoreId         = x.StoreId,
                TaxCategoryId   = x.TaxCategoryId,
                CountryId       = x.CountryId,
                StateProvinceId = x.StateProvinceId,
                Zip             = x.Zip,
                Percentage      = x.Percentage,
            }
                                                           )
                                                   .ToList()
                                                   );

            string storeId         = _storeContext.CurrentStore.Id;
            string taxCategoryId   = calculateTaxRequest.TaxCategoryId;
            string countryId       = calculateTaxRequest.Address.CountryId;
            string stateProvinceId = calculateTaxRequest.Address.StateProvinceId;
            string zip             = calculateTaxRequest.Address.ZipPostalCode;


            if (zip == null)
            {
                zip = string.Empty;
            }
            zip = zip.Trim();

            var existingRates = new List <TaxRateForCaching>();

            foreach (var taxRate in allTaxRates)
            {
                if (taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId)
                {
                    existingRates.Add(taxRate);
                }
            }

            //filter by store
            var matchedByStore = new List <TaxRateForCaching>();

            //first, find by a store ID
            foreach (var taxRate in existingRates)
            {
                if (storeId == taxRate.StoreId)
                {
                    matchedByStore.Add(taxRate);
                }
            }
            //not found? use the default ones (ID == 0)
            if (matchedByStore.Count == 0)
            {
                foreach (var taxRate in existingRates)
                {
                    if (!String.IsNullOrEmpty(taxRate.StoreId))
                    {
                        matchedByStore.Add(taxRate);
                    }
                }
            }


            //filter by state/province
            var matchedByStateProvince = new List <TaxRateForCaching>();

            //first, find by a state ID
            foreach (var taxRate in matchedByStore)
            {
                if (stateProvinceId == taxRate.StateProvinceId)
                {
                    matchedByStateProvince.Add(taxRate);
                }
            }
            //not found? use the default ones (ID == 0)
            if (matchedByStateProvince.Count == 0)
            {
                foreach (var taxRate in matchedByStore)
                {
                    if (String.IsNullOrEmpty(taxRate.StateProvinceId))
                    {
                        matchedByStateProvince.Add(taxRate);
                    }
                }
            }


            //filter by zip
            var matchedByZip = new List <TaxRateForCaching>();

            foreach (var taxRate in matchedByStateProvince)
            {
                if ((String.IsNullOrEmpty(zip) && String.IsNullOrEmpty(taxRate.Zip)) ||
                    (zip.Equals(taxRate.Zip, StringComparison.InvariantCultureIgnoreCase)))
                {
                    matchedByZip.Add(taxRate);
                }
            }
            if (matchedByZip.Count == 0)
            {
                foreach (var taxRate in matchedByStateProvince)
                {
                    if (String.IsNullOrWhiteSpace(taxRate.Zip))
                    {
                        matchedByZip.Add(taxRate);
                    }
                }
            }

            if (matchedByZip.Count > 0)
            {
                result.TaxRate = matchedByZip[0].Percentage;
            }

            return(result);
        }
Пример #23
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result  = new CalculateTaxResult();
            var address = calculateTaxRequest.Address;

            if (address == null)
            {
                result.AddError("Address is not set");
                return(result);
            }
            if (address.Country == null)
            {
                result.AddError("Country is not set");
                return(result);
            }

            string  licenseKey = _strikeIronTaxSettings.LicenseKey;
            decimal taxRate;

            if (address.Country.TwoLetterIsoCode.ToLower() == "us")
            {
                if (String.IsNullOrEmpty(address.ZipPostalCode))
                {
                    result.AddError("Zip is not provided");

                    return(result);
                }

                string error = "";

                taxRate = GetTaxRateUsa(address.ZipPostalCode, licenseKey, ref error);

                if (!String.IsNullOrEmpty(error))
                {
                    result.AddError(error);

                    return(result);
                }
            }
            else if (address.Country.TwoLetterIsoCode.ToLower() == "ca")
            {
                if (address.StateProvince == null)
                {
                    result.AddError("Province is not set");

                    return(result);
                }

                string error = "";

                taxRate = GetTaxRateCanada(address.StateProvince.Abbreviation, licenseKey, ref error);

                if (!String.IsNullOrEmpty(error))
                {
                    result.AddError(error);

                    return(result);
                }
            }
            else
            {
                result.AddError("Tax can be calculated only for USA zip or Canada province");

                return(result);
            }

            result.TaxRate = taxRate * 100;

            return(result);
        }
Пример #24
0
        protected virtual CalculateTaxRequest CreateCalculateTaxRequest(Product product,
                                                                        int taxCategoryId, Customer customer, decimal price, out int taxCategoryIdOut)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var calculateTaxRequest = new CalculateTaxRequest
            {
                Customer      = customer,
                Product       = product,
                Price         = price,
                TaxCategoryId = taxCategoryId > 0 ? taxCategoryId : (product != null ? product.TaxCategoryId : 0)
            };

            taxCategoryIdOut = calculateTaxRequest.TaxCategoryId;
            var basedOn = _taxSettings.TaxBasedOn;

            //new EU VAT rules starting January 1st 2015
            //find more info at http://ec.europa.eu/taxation_customs/taxation/vat/how_vat_works/telecom/index_en.htm#new_rules
            var overridenBasedOn = _taxSettings.EuVatEnabled &&                                                         //EU VAT enabled?
                                   product != null && product.IsTelecommunicationsOrBroadcastingOrElectronicServices && //telecommunications, broadcasting and electronic services?
                                   DateTime.UtcNow > new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc) &&             //January 1st 2015 passed?
                                   IsEuConsumer(customer);                                                              //Europe Union consumer?

            if (overridenBasedOn)
            {
                //We must charge VAT in the EU country where the customer belongs (not where the business is based)
                basedOn = TaxBasedOn.BillingAddress;
            }

            //tax is based on pickup point address
            if (!overridenBasedOn && _taxSettings.TaxBasedOnPickupPointAddress && _shippingSettings.AllowPickUpInStore)
            {
                var pickupPoint = customer.GetAttribute <PickupPoint>(SystemCustomerAttributeNames.SelectedPickupPoint, _storeContext.CurrentStore.Id);
                if (pickupPoint != null)
                {
                    var country = _countryService.GetCountryByTwoLetterIsoCode(pickupPoint.CountryCode);
                    var state   = _stateProvinceService.GetStateProvinceByAbbreviation(pickupPoint.StateAbbreviation);

                    calculateTaxRequest.Address = new Address
                    {
                        Address1        = pickupPoint.Address,
                        City            = pickupPoint.City,
                        Country         = country,
                        CountryId       = country.Return(c => c.Id, 0),
                        StateProvince   = state,
                        StateProvinceId = state.Return(sp => sp.Id, 0),
                        ZipPostalCode   = pickupPoint.ZipPostalCode,
                        CreatedOnUtc    = DateTime.UtcNow
                    };

                    return(calculateTaxRequest);
                }
            }

            if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null ||
                basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null)
            {
                basedOn = TaxBasedOn.DefaultAddress;
            }

            switch (basedOn)
            {
            case TaxBasedOn.BillingAddress:
                calculateTaxRequest.Address = customer.BillingAddress;
                break;

            case TaxBasedOn.ShippingAddress:
                calculateTaxRequest.Address = customer.ShippingAddress;
                break;

            case TaxBasedOn.DefaultAddress:
            default:
                calculateTaxRequest.Address = _addressService.GetAddressById(_taxSettings.DefaultTaxAddressId);
                break;
            }

            return(calculateTaxRequest);
        }
Пример #25
0
 public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <param name="Error">Error</param>
        /// <returns>Tax</returns>
        public decimal GetTaxRate(CalculateTaxRequest calculateTaxRequest, ref string Error)
        {
            decimal rate = SettingManager.GetSettingValueDecimalNative("Tax.TaxProvider.FixedRate.Rate");

            return(rate);
        }
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var result = new CalculateTaxResult();

            var address = calculateTaxRequest.Address;

            if (address == null)
            {
                result.AddError("Address is not set");
                return(result);
            }
            if (address.Country == null)
            {
                result.AddError("Country is not set");
                return(result);
            }

            //**************************************************************************************************************
            // As a Registered StrikeIron user, you can authenticate to a StrikeIron web service with either a
            // UserID/Password combination or a License Key.  If you wish to use a License Key,
            // assign this value to the UserID field and set the Password field to null.
            //**************************************************************************************************************
            string userId   = _strikeIronTaxSettings.UserId;
            string password = _strikeIronTaxSettings.Password;

            decimal taxRate = decimal.Zero;

            if (address.Country.TwoLetterIsoCode.ToLower() == "us")
            {
                if (String.IsNullOrEmpty(address.ZipPostalCode))
                {
                    result.AddError("Zip is not provided");
                    return(result);
                }
                string error = "";
                taxRate = GetTaxRateUsa(address.ZipPostalCode, userId, password, ref error);
                if (!String.IsNullOrEmpty(error))
                {
                    result.AddError(error);
                    return(result);
                }
            }
            else if (address.Country.TwoLetterIsoCode.ToLower() == "ca")
            {
                if (address.StateProvince == null)
                {
                    result.AddError("Province is not set");
                    return(result);
                }
                string error = "";
                taxRate = GetTaxRateCanada(address.StateProvince.Abbreviation, userId, password, ref error);
                if (!String.IsNullOrEmpty(error))
                {
                    result.AddError(error);
                    return(result);
                }
            }
            else
            {
                result.AddError("Tax can be calculated only for USA zip or Canada province");
                return(result);
            }

            result.TaxRate = taxRate * 100;
            return(result);
        }
Пример #28
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public CalculateTaxResult GetTaxRate(CalculateTaxRequest calculateTaxRequest)
        {
            var _productMappingRepo = EngineContext.Current.Resolve <IRepository <ProductMapping> >();
            var productMapping      = _productMappingRepo.TableNoTracking.FirstOrDefault(x => x.ProductId == calculateTaxRequest.Product.Id);
            var result = new CalculateTaxResult();
            var _taxCategoryMappingService = EngineContext.Current.Resolve <IWB_TaxCategoryMappingService>();

            if (productMapping != null)
            {
                //choose the tax rate calculation method
                if (!_countryStateZipSettings.CountryStateZipEnabled)
                {
                    if (calculateTaxRequest.Product.TaxCategoryId != 0)
                    {
                        result = new CalculateTaxResult
                        {
                            TaxRate = _settingService.GetSettingByKey <decimal>(string.Format("Tax.Worldbuy.TaxProvider.FixedOrByCountryStateZip.TaxCategoryId{0}", calculateTaxRequest.TaxCategoryId)),
                        };
                    }

                    else
                    {
                        var product = calculateTaxRequest.Product;
                        if (product.ProductCategories.Count == 0)
                        {
                        }
                        else
                        {
                            int taxCategoryId = _taxCategoryMappingService.GetTaxCategoryId(product);
                            var curRate       = _settingService.GetSettingByKey <decimal>(string.Format("Tax.Worldbuy.TaxProvider.FixedOrByCountryStateZip.TaxCategoryId{0}", taxCategoryId));
                            result = new CalculateTaxResult
                            {
                                TaxRate = curRate,
                            };
                        }
                    }
                }
                else
                {
                    //the tax rate calculation by country & state & zip

                    if (calculateTaxRequest.Address == null)
                    {
                        result.Errors.Add("Address is not set");
                        return(result);
                    }

                    //first, load all tax rate records (cached) - loaded only once
                    const string cacheKey    = WB_ModelCacheEventConsumer.ALL_TAX_RATES_MODEL_KEY;
                    var          allTaxRates = _cacheManager.Get(cacheKey, () =>
                                                                 _taxRateService
                                                                 .GetAllTaxRates()
                                                                 .Select(x => new WB_TaxRateForCaching
                    {
                        Id              = x.Id,
                        StoreId         = x.StoreId,
                        TaxCategoryId   = x.TaxCategoryId,
                        CountryId       = x.CountryId,
                        StateProvinceId = x.StateProvinceId,
                        Zip             = x.Zip,
                        Percentage      = x.Percentage,
                    }).ToList()
                                                                 );

                    var storeId         = _storeContext.CurrentStore.Id;
                    var taxCategoryId   = calculateTaxRequest.TaxCategoryId;
                    var countryId       = calculateTaxRequest.Address.Country != null ? calculateTaxRequest.Address.Country.Id : 0;
                    var stateProvinceId = calculateTaxRequest.Address.StateProvince != null
                        ? calculateTaxRequest.Address.StateProvince.Id
                        : 0;
                    var zip = calculateTaxRequest.Address.ZipPostalCode;

                    if (zip == null)
                    {
                        zip = string.Empty;
                    }
                    zip = zip.Trim();

                    var existingRates = allTaxRates.Where(taxRate => taxRate.CountryId == countryId && taxRate.TaxCategoryId == taxCategoryId).ToList();

                    //filter by store
                    //first, find by a store ID
                    var matchedByStore = existingRates.Where(taxRate => storeId == taxRate.StoreId).ToList();

                    //not found? use the default ones (ID == 0)
                    if (!matchedByStore.Any())
                    {
                        matchedByStore.AddRange(existingRates.Where(taxRate => taxRate.StoreId == 0));
                    }

                    //filter by state/province
                    //first, find by a state ID
                    var matchedByStateProvince = matchedByStore.Where(taxRate => stateProvinceId == taxRate.StateProvinceId).ToList();

                    //not found? use the default ones (ID == 0)
                    if (!matchedByStateProvince.Any())
                    {
                        matchedByStateProvince.AddRange(matchedByStore.Where(taxRate => taxRate.StateProvinceId == 0));
                    }

                    //filter by zip
                    var matchedByZip = matchedByStateProvince.Where(taxRate => (string.IsNullOrEmpty(zip) && string.IsNullOrEmpty(taxRate.Zip)) || zip.Equals(taxRate.Zip, StringComparison.InvariantCultureIgnoreCase)).ToList();
                    if (!matchedByZip.Any())
                    {
                        matchedByZip.AddRange(matchedByStateProvince.Where(taxRate => string.IsNullOrWhiteSpace(taxRate.Zip)));
                    }

                    if (matchedByZip.Any())
                    {
                        result.TaxRate = matchedByZip[0].Percentage;
                    }
                }
            }

            return(result);
        }
Пример #29
0
 public double CalculateTaxForOrder(CalculateTaxRequest order)
 {
     return(calculator.CalculateTaxForOrder(order));
 }
Пример #30
0
 /// <summary>
 /// Gets tax rate
 /// </summary>
 /// <param name="calculateTaxRequest">Tax calculation request</param>
 /// <param name="error">Error</param>
 /// <returns>Tax</returns>
 public decimal GetTaxRate(CalculateTaxRequest calculateTaxRequest, ref string error)
 {
     return(decimal.Zero);
 }