Esempio n. 1
0
        public TaxResult GetTax(TaxRequest request)
        {
            string url = "https://api.taxjar.com/sales_tax?amount=" + request.Amount
                + "&shipping=" + request.Shipping
                + "&to_country=" + request.ToCountry
                + "&to_state=" + request.ToState
                + "&to_city=" + request.ToCity
                + "&to_zip=" + request.ToZip;
            JObject response = MakeTaxJarApiRequest(url);

            var result = new TaxResult();
            try
            {
                result.TotalTax = (decimal) response["amount_to_collect"];
                result.Rate = (decimal) response["rate"];
                result.HasNexus = (bool) response["has_nexus"];
                if (response["freight_taxable"].HasValues)
                    result.FreightTaxable = (bool) response["freight_taxable"];
                if (response["tax_source"].HasValues)
                    result.TaxSource = (string) response["tax_source"];
                result.Success = true;
            }
            catch
            {
                result.Success = false;
            }

            return result;
        }
Esempio n. 2
0
        public TaxResult GetTax(TaxRequest request)
        {
            string url = "https://api.taxjar.com/sales_tax?amount=" + request.Amount
                         + "&shipping=" + request.Shipping
                         + "&to_country=" + request.ToCountry
                         + "&to_state=" + request.ToState
                         + "&to_city=" + request.ToCity
                         + "&to_zip=" + request.ToZip;
            JObject response = MakeTaxJarApiRequest(url);

            var result = new TaxResult();

            try
            {
                result.TotalTax = (decimal)response["amount_to_collect"];
                result.Rate     = (decimal)response["rate"];
                result.HasNexus = (bool)response["has_nexus"];
                if (response["freight_taxable"].HasValues)
                {
                    result.FreightTaxable = (bool)response["freight_taxable"];
                }
                if (response["tax_source"].HasValues)
                {
                    result.TaxSource = (string)response["tax_source"];
                }
                result.Success = true;
            }
            catch
            {
                result.Success = false;
            }

            return(result);
        }
        public Task <TaxResult> GetTaxRate(TaxRequest calculateTaxRequest)
        {
            var result = new TaxResult {
                TaxRate = GetTaxRate(calculateTaxRequest.TaxCategoryId)
            };

            return(Task.FromResult(result));
        }
Esempio n. 4
0
        public TaxResult GetTaxResultForOrder(decimal amount, decimal shippingAmount, string taxApiEndpointUrl, string taxJarApiKey, string taxRequestJsonString)
        {
            var taxRate   = GetTaxRateForLocation(taxApiEndpointUrl, taxJarApiKey, taxRequestJsonString);
            var taxAmount = (amount + shippingAmount) * taxRate;

            TaxResult taxResult = new TaxResult();

            taxResult.TaxRate   = taxRate;
            taxResult.TaxAmount = taxAmount;

            return(taxResult);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets a <see cref="HttpWebResponse"/> from the API.
        /// </summary>
        /// <param name="requestUrl">
        /// The request url.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="requestMethod">The request method</param>
        /// <returns>
        /// The <see cref="HttpWebResponse"/>.
        /// </returns>
        internal string GetResponse(string requestUrl, string data = "", RequestMethod requestMethod = RequestMethod.HttpGet)
        {
            try
            {
                var address = new Uri(requestUrl);

                var request = WebRequest.Create(address) as HttpWebRequest;

                //// Add Authorization header
                var pair  = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", _accountNumber, _licenseKey));
                var basic = string.Format("Basic {0}", Convert.ToBase64String(pair));

                request.Headers.Add(HttpRequestHeader.Authorization, basic);

                if (requestMethod == RequestMethod.HttpPost)
                {
                    request.Method        = "POST";
                    request.ContentType   = "application/json";
                    request.ContentLength = data.Length;
                    var s = request.GetRequestStream();
                    s.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
                }
                else
                {
                    request.Method = "GET";
                }

                var response = request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    return(sr.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <AvaTaxService>("AvaTax API Failure", ex);
                var result = new TaxResult()
                {
                    ResultCode = SeverityLevel.Exception,
                    Messages   = new[]
                    {
                        new ApiResponseMessage()
                        {
                            Details = ex.Message, Source = typeof(AvaTaxService).Name, RefersTo = "GetTax", Severity = SeverityLevel.Exception
                        }
                    }
                };

                return(JsonConvert.SerializeObject(result));
            }
        }
Esempio n. 6
0
        public TaxResult GetTaxResultForOrder(TaxRequest taxRequest)
        {
            // API Credentials in config file
            var taxApiEndpointUrl = WebConfigurationManager.AppSettings["TaxApiEndpointUrl"];
            var taxJarApiKey      = WebConfigurationManager.AppSettings["TaxJarApiKey"];
            // API expects TaxRequest as JSON string
            var taxRequestJsonString = JsonConvert.SerializeObject(taxRequest);

            TaxResult taxResult = new TaxResult();

            // Instantiate TaxJar Tax Calculator
            TaxCalculator taxJarTaxCalculator = new TaxCalculator();

            // Call TaxCalculator application
            taxResult = taxJarTaxCalculator.GetTaxResultForOrder(taxRequest.Amount, taxRequest.ShippingAmount, taxApiEndpointUrl, taxJarApiKey, taxRequestJsonString);

            return(taxResult);
        }
    private TaxResult CreateTaxResult(TaxRequest request)
    {
        var result = new TaxResult();

        result.Dates = request.PassagesThroughCustoms
                       .Where(a => !DateIsTaxFree(a))
                       .GroupBy(a => a.Date)
                       .Select(a =>
                               new DateOfPassage()
        {
            Date      = a.Key.ToString("yyyy/MM/dd"),
            Occasions = a.Select(a => a.ToString("HH:mm")).ToList(),
            Tax       = GetDayTax(a)
        })
                       .ToList();
        result.IsTaxPayingVehicle = true;

        return(result);
    }
        public void GetTaxResultForOrder()
        {
            // Arrange
            TaxServiceController controller = new TaxServiceController();

            // Act

            // Verify tax rate is successfully returned with valid query
            TaxResult result = controller.GetTaxResultForOrder(new TaxRequest()
            {
                FromCountry    = "US",
                FromState      = "NY",
                FromCity       = "New York",
                FromZip        = "10003",
                Amount         = 100,
                ShippingAmount = 0,
                ToCountry      = "US",
                ToState        = "CT",
                ToZip          = "06877",
                NexusAddresses = new List <NexusAddress>()
                {
                    new NexusAddress
                    {
                        Country = "US",
                        State   = "NY",
                        ZipCode = "10003"
                    },
                    new NexusAddress
                    {
                        Country = "US",
                        State   = "CT",
                        ZipCode = "06877"
                    }
                }
            });

            // Assert

            // Valid query
            Assert.IsNotNull(result);
            // Object returned is of type TaxResult
            Assert.IsTrue(result.GetType() == typeof(TaxResult));
        }
Esempio n. 9
0
        private static async Task <TaxResult> GetTaxAsync(int id)
        {
            var client = new HttpClient();

            client.BaseAddress = new Uri(taxUrl);
            string              result;
            TaxResult           tax      = null;
            HttpResponseMessage response = await client.GetAsync(string.Empty + id);

            if (response.IsSuccessStatusCode)
            {
                result = await response.Content.ReadAsStringAsync();

                tax = JsonConvert.DeserializeObject <TaxResult>(result);
            }
            else
            {
                Console.WriteLine("Get tax failed for ID " + id + " with error " + response.ReasonPhrase);
            }
            return(tax);
        }
Esempio n. 10
0
        public void GetTaxResultForOrder()
        {
            // Arrange
            TaxCalculator taxCalculator = new TaxCalculator();

            // Act

            // Verify valid TaxResult is returned to page
            TaxResult result = taxCalculator.GetTaxResultForOrder(100, 0, "https://api.taxjar.com/v2/taxes", "5da2f821eee4035db4771edab942a4cc", "{\"from_country\":\"US\",\"from_zip\":\"10003\",\"from_state\":\"NY\",\"from_city\":\"New York\",\"from_street\":null,\"to_country\":\"US\",\"to_zip\":\"06877\",\"to_state\":\"CT\",\"amount\":100.0,\"shipping\":0.0,\"nexus_addresses\":[{\"country\":\"US\",\"state\":\"NY\",\"zip\":\"10003\"},{\"country\":\"US\",\"state\":\"CT\",\"zip\":\"06877\"}]}");
            // Verify no error is generated when query with state/zicode mismatch
            TaxResult resultStateZipMismatch = taxCalculator.GetTaxResultForOrder(100, 0, "https://api.taxjar.com/v2/taxes", "5da2f821eee4035db4771edab942a4cc", "{\"from_country\":\"US\",\"from_zip\":\"10003\",\"from_state\":\"NY\",\"from_city\":\"New York\",\"from_street\":null,\"to_country\":\"US\",\"to_zip\":\"10590\",\"to_state\":\"CT\",\"amount\":100.0,\"shipping\":0.0,\"nexus_addresses\":[{\"country\":\"US\",\"state\":\"NY\",\"zip\":\"10003\"},{\"country\":\"US\",\"state\":\"CT\",\"zip\":\"10590\"}]}");

            // Assert

            // Valid TaxResult
            Assert.IsNotNull(result);
            // Object returned is of type TaxResult
            Assert.IsTrue(result.GetType() == typeof(TaxResult));
            // State/Zipcode mismatch
            Assert.IsNotNull(resultStateZipMismatch);
        }
Esempio n. 11
0
        public Decimal GetTaxRateForLocation(string taxApiEndpointUrl, string taxJarApiKey, string taxRequestJsonString)
        {
            TaxResult taxResult = new TaxResult();
            var       taxRate   = 0.00M;

            try
            {
                // Send request to TaxJar Sales Tax API
                var client = new RestClient(taxApiEndpointUrl);
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Authorization", "Token token=\"" + taxJarApiKey + "\"");
                request.AddHeader("Content-Type", "application/json");
                request.AddParameter("application/json", taxRequestJsonString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);

                var data = (JObject)JsonConvert.DeserializeObject(response.Content);

                // check for error result
                // i.e. due to bad request (zipcode and state mismatch)
                if (data["tax"] == null && data["error"] != null)
                {
                    // Log Error
                    Console.Write(string.Format("Error result received from TaxJar Sales Tax API. Request: {0}", taxRequestJsonString));

                    return(-1);
                }

                // assign taxRate
                taxRate = data["tax"]["rate"].Value <decimal>();
            }
            catch
            {
                // Log Error
                Console.Write(string.Format("Error trying to call TaxJar Sales Tax API. Request: {0}", taxRequestJsonString));
            }

            return(taxRate);
        }
Esempio n. 12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ITaxResult TaxResultObj = null;

        try
        {
            Cart         CartObj        = new JavaScriptSerializer().Deserialize <Cart>(CookieProxy.Instance().GetValue("Cart").ToString());
            IAddress     AddressObj     = new Address(int.Parse(Request.Form["aid"].ToString()));
            IUserProfile UserProfileObj = new UserProfile(CookieProxy.Instance().GetValue("t").ToString());
            TaxResultObj = new TaxManagement().CalculateTaxFromCartItems(CartObj, AddressObj, UserProfileObj);
        }
        catch (Exception)
        {
            TaxResultObj = new TaxResult(false);
        }
        finally
        {
            var ResultObj = new
            {
                Response = TaxResultObj
            };
            Response.Write(new JavaScriptSerializer().Serialize(ResultObj));
        }
    }
Esempio n. 13
0
        /// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="calculateTaxRequest">Tax calculation request</param>
        /// <returns>Tax</returns>
        public async Task <TaxResult> GetTaxRate(TaxRequest calculateTaxRequest)
        {
            var result = new TaxResult();

            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 _cacheBase.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         = _workContext.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);
        }
Esempio n. 14
0
        /// <summary>
        /// Gets a <see cref="HttpWebResponse"/> from the API.
        /// </summary>
        /// <param name="requestUrl">
        /// The request url.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="requestMethod">The request method</param>
        /// <returns>
        /// The <see cref="HttpWebResponse"/>.
        /// </returns>
        internal string GetResponse(string requestUrl, string data = "", RequestMethod requestMethod = RequestMethod.HttpGet)
        {
            try
            {
                var address = new Uri(requestUrl);

                var request = WebRequest.Create(address) as HttpWebRequest;

                //// Add Authorization header
                var pair = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", _accountNumber, _licenseKey));
                var basic = string.Format("Basic {0}", Convert.ToBase64String(pair));
                
                request.Headers.Add(HttpRequestHeader.Authorization, basic);

                if (requestMethod == RequestMethod.HttpPost)
                {
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = data.Length;
                    var s = request.GetRequestStream();
                    s.Write(Encoding.ASCII.GetBytes(data), 0, data.Length);
                }
                else
                {
                    request.Method = "GET";
                }

                var response = request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error<AvaTaxService>("AvaTax API Failure", ex);
                var result = new TaxResult() 
                { 
                    ResultCode = SeverityLevel.Exception, 
                    Messages = new[] 
                    { 
                        new ApiResponseMessage() { Details = ex.Message, Source = typeof(AvaTaxService).Name, RefersTo = "GetTax", Severity = SeverityLevel.Exception } 
                    }
                };

                return JsonConvert.SerializeObject(result);
            }
        }