/// <summary>
        /// Gets tax rate
        /// </summary>
        /// <param name="taxRateRequest">Tax rate request</param>
        /// <returns>Tax</returns>
        public TaxRateResult GetTaxRate(TaxRateRequest taxRateRequest)
        {
            var result = new TaxRateResult();

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

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

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

            var storeId         = taxRateRequest.CurrentStoreId;
            var taxCategoryId   = taxRateRequest.TaxCategoryId;
            var countryId       = taxRateRequest.Address.CountryId;
            var stateProvinceId = taxRateRequest.Address.StateProvinceId;
            var zip             = taxRateRequest.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);
        }
Example #2
0
        public async Task <TaxRateResult> GetTaxRateAsync(TaxRateRequest taxRateRequest)
        {
            var result = new TaxRateResult();

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

            var foundRecord = await _abcTaxService.GetAbcTaxRateAsync(
                taxRateRequest.CurrentStoreId,
                taxRateRequest.TaxCategoryId,
                taxRateRequest.Address
                );

            if (foundRecord == null)
            {
                return(result);
            }

            // get TaxJar rate if appropriate
            result.TaxRate = foundRecord.IsTaxJarEnabled ?
                             await _taxjarRateService.GetTaxJarRateAsync(taxRateRequest.Address) :
                             foundRecord.Percentage;

            return(result);
        }
        public async Task <TaxRateResult> CalculateAsync(Proxy proxy, string api, TaxRequest request)
        {
            return(await Task.Factory.StartNew(() =>
            {
                HttpWebRequest webRequest = WebRequest.Create("https://api.printful.com/tax/rates") as HttpWebRequest;

                if (proxy != null)
                {
                    webRequest.Proxy = proxy.Get();
                    webRequest.Credentials = proxy.GetCredential();
                }
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.Headers.Add("Authorization", "Basic " + Manager.API.Encode(api));

                string data = JsonConvert.SerializeObject(request);
                byte[] data_form = Encoding.UTF8.GetBytes(data);

                webRequest.ContentLength = data_form.Length;
                Stream newStream = webRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data_form, 0, data_form.Length);
                newStream.Close();

                WebResponse response = webRequest.GetResponse();
                if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
                {
                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();
                    if (dataStream != null)
                    {
                        // Open the stream using a StreamReader for easy access.
                        StreamReader reader = new StreamReader(dataStream);
                        // Read the content.
                        string responseFromServer = reader.ReadToEnd();
                        // Display the content.
                        TaxRateResult result =
                            JsonConvert.DeserializeObject <TaxRateResult>(responseFromServer, Converter.Settings);

                        return result;
                    }
                }
                return null;
            }));
        }
 /// <summary>
 /// Ctor
 /// </summary>
 /// <param name="taxRateResult">Tax rate result</param>
 public TaxRateCalculatedEvent(TaxRateResult taxRateResult)
 {
     TaxRateResult = taxRateResult;
 }