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 static TaxRequest CreateTaxQuoteRequest() { var taxQuote = new TaxRequest() { SaleDate = DateTime.Now, ShipToInformation = new ShipToInformation() { ZipCode = "64057", Country = "USA" }, TaxCalculationType = 1, LineItemInformation = new List <TaxLineItemRequest>() { new TaxLineItemRequest() { GrossAmount = 100, Quantity = 1, TransactionType = 1, } } }; return(taxQuote); }
/// <summary> /// Calculates tax for invoice. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="taxAddress"> /// The tax address. /// </param> /// <returns> /// The <see cref="ITaxCalculationResult"/>. /// </returns> public override ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress) { decimal amount = 0m; foreach (var item in invoice.Items) { // can I use?: https://github.com/Merchello/Merchello/blob/5706b8c9466f7417c41fdd29de7930b3e8c4dd2d/src/Merchello.Core/Models/ExtendedDataExtensions.cs#L287-L295 if (item.ExtendedData.GetTaxableValue()) { amount = amount + item.TotalPrice; } } TaxRequest taxRequest = new TaxRequest(); taxRequest.Amount = amount; taxRequest.Shipping = invoice.TotalShipping(); taxRequest.ToCity = taxAddress.Locality; taxRequest.ToCountry = taxAddress.CountryCode; taxRequest.ToState = taxAddress.Region; taxRequest.ToZip = taxAddress.PostalCode; Models.TaxResult taxResult = _taxjarService.GetTax(taxRequest); if (taxResult.Success) { var extendedData = new ExtendedDataCollection(); extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(taxResult)); return(new TaxCalculationResult(TaxMethod.Name, taxResult.Rate, taxResult.TotalTax, extendedData)); } throw new Exception("TaxJar.com error"); }
/// <summary> /// Calculates tax for invoice. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="taxAddress"> /// The tax address. /// </param> /// <returns> /// The <see cref="ITaxCalculationResult"/>. /// </returns> public override ITaxCalculationResult CalculateTaxForInvoice(IInvoice invoice, IAddress taxAddress) { decimal amount = 0m; foreach (var item in invoice.Items) { // can I use?: https://github.com/Merchello/Merchello/blob/5706b8c9466f7417c41fdd29de7930b3e8c4dd2d/src/Merchello.Core/Models/ExtendedDataExtensions.cs#L287-L295 if (item.ExtendedData.GetTaxableValue()) amount = amount + item.TotalPrice; } TaxRequest taxRequest = new TaxRequest(); taxRequest.Amount = amount; taxRequest.Shipping = invoice.TotalShipping(); taxRequest.ToCity = taxAddress.Locality; taxRequest.ToCountry = taxAddress.CountryCode; taxRequest.ToState = taxAddress.Region; taxRequest.ToZip = taxAddress.PostalCode; Models.TaxResult taxResult = _taxjarService.GetTax(taxRequest); if (taxResult.Success) { var extendedData = new ExtendedDataCollection(); extendedData.SetValue(Core.Constants.ExtendedDataKeys.TaxTransactionResults, JsonConvert.SerializeObject(taxResult)); return new TaxCalculationResult(TaxMethod.Name, taxResult.Rate, taxResult.TotalTax, extendedData); } throw new Exception("TaxJar.com error"); }
public double Calculate(IEnumerable <TaxRecord> municipalityData, TaxRequest request) { var taxes = ApplicableTaxes(municipalityData, request).OrderBy(x => { return(x.End - x.Start); }); // apply the shortest maching tax period return(taxes.First().TaxRate); }
public SOCEstimate GetRecurringCharges(List <DataContract.ProductInfo> products) { SOCEstimate socEstimate = null; if (products != null) { socEstimate = new SOCEstimate(); socEstimate.Monthly = products.Sum(prod => prod.Rate); socEstimate.FirstBill = socEstimate.Monthly + (products.Sum(prod => prod.Rate) / 2); TaxRequest taxrequest = new TaxRequest(); List <Microservice_GetEstimate_WCF.GetTaxes.ProductInfo> taxprodlst = new List <Microservice_GetEstimate_WCF.GetTaxes.ProductInfo>(); //Get Taxes foreach (DataContract.ProductInfo prod in products) { Microservice_GetEstimate_WCF.GetTaxes.ProductInfo taxProd = new Microservice_GetEstimate_WCF.GetTaxes.ProductInfo(); taxProd.ProductIOSC = prod.ProductIOSC; taxProd.Rate = prod.Rate; taxprodlst.Add(taxProd); } taxrequest.Products = taxprodlst.ToArray(); socEstimate.TaxResponse = GetTaxInfo(taxrequest); } return(socEstimate); }
public static TaxRequest CreateTaxPendingRequest() { var taxQuote = new TaxRequest() { SaleDate = DateTime.Now, TransactionSource = "ERP", OrderNumber = "Test" + Guid.NewGuid(), InvoiceNumber = "Test", ShipToInformation = new ShipToInformation() { ZipCode = "64057", Country = "USA" }, TaxCalculationType = 1, LineItemInformation = new List <TaxLineItemRequest>() { new TaxLineItemRequest() { GrossAmount = 100, Quantity = 1, TransactionType = 1, } } }; return(taxQuote); }
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)); }
private double Test(DateTime date) { var r = new TaxRequest() { Municipality = "Vilnius", Date = date }; return(calc.Calculate(taxRecords, r)); }
/// <summary> /// Calculate Taxes Get tax details for a transaction. /// </summary> /// <exception cref="CyberSource.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="taxRequest"></param> /// <returns>VasV2PaymentsPost201Response</returns> public VasV2PaymentsPost201Response CalculateTax(TaxRequest taxRequest) { logger.Debug("CALLING API \"CalculateTax\" STARTED"); this.SetStatusCode(null); ApiResponse <VasV2PaymentsPost201Response> localVarResponse = CalculateTaxWithHttpInfo(taxRequest); logger.Debug("CALLING API \"CalculateTax\" ENDED"); this.SetStatusCode(localVarResponse.StatusCode); return(localVarResponse.Data); }
private List <TaxRate> GetTaxRates(TaxRequest taxRequest) { List <TaxRate> retVal = new List <TaxRate>(); LogInvoker <AvalaraLogger.TaxRequestContext> .Execute(log => { if (IsEnabled && !string.IsNullOrEmpty(AccountNumber) && !string.IsNullOrEmpty(LicenseKey) && !string.IsNullOrEmpty(ServiceUrl) && !string.IsNullOrEmpty(CompanyCode)) { var request = taxRequest.ToAvaTaxRequest(CompanyCode, false); if (request != null) { log.docCode = request.DocCode; log.docType = request.DocType.ToString(); log.customerCode = request.CustomerCode; var taxSvc = new JsonTaxSvc(AccountNumber, LicenseKey, ServiceUrl); var getTaxResult = taxSvc.GetTax(request); if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success)) { //if tax calculation failed create exception with provided error info var error = string.Join(Environment.NewLine, getTaxResult.Messages.Select(m => m.Summary)); throw new Exception(error); } foreach (var taxLine in getTaxResult.TaxLines ?? Enumerable.Empty <AvaTaxCalcREST.TaxLine>()) { var rate = new TaxRate { Rate = taxLine.Tax, Currency = taxRequest.Currency, TaxProvider = this, Line = taxRequest.Lines.First(l => l.Id == taxLine.LineNo) }; retVal.Add(rate); } } else { throw new Exception("Failed to create get tax request"); } } else { throw new Exception("Failed to create get tax request"); } }) .OnError(_logger, AvalaraLogger.EventCodes.TaxCalculationError) .OnSuccess(_logger, AvalaraLogger.EventCodes.GetSalesInvoiceRequestTime); return(retVal); }
public async Task <IActionResult> GetTax([FromBody] TaxRequest taxRequest) { if (ModelState.IsValid) { return(Ok(await _taxService.GetTax(taxRequest))); } else { return(BadRequest(ModelState)); } }
private static TaxResponse GetTaxInfo(TaxRequest taxRequest) { TaxResponse taxresponse = null; if (taxRequest != null) { GetTaxesClient getTaxesClient = new GetTaxesClient("NetTcpBinding_IGetTaxes"); taxresponse = getTaxesClient.GetSOCTaxes(taxRequest); } return(taxresponse); }
public TaxResponse GetSOCTaxes(TaxRequest taxrequest) { TaxResponse taxresponse = new TaxResponse(); if (taxrequest != null && taxrequest.Products != null) { taxresponse = getTaxes(taxrequest.Products); } return(taxresponse); }
public async Task <TaxResponse> GetTax(TaxRequest taxRequest) { var taxSetupResult = await _taxRepository.GetTax(taxRequest); var taxAmount = TaxRuleFactory.GetTaxRule(taxRequest.municipalityName)?.ApplyRule(taxSetupResult); return(new TaxResponse { municipilityName = taxRequest?.municipalityName, taxRate = taxAmount, message = !taxSetupResult.Any() ? "No result found." : String.Empty }); }
public static void getSOCTaxes() { TaxRequest request = new TaxRequest(); List <GetTaxes.ProductInfo> prodlst = new List <GetTaxes.ProductInfo>(); GetTaxes.ProductInfo prodA = new GetTaxes.ProductInfo(); prodA.ProductIOSC = "A"; prodA.Rate = 10.0M; GetTaxes.ProductInfo prodB = new GetTaxes.ProductInfo(); prodB.ProductIOSC = "B"; prodB.Rate = 20.0M; GetTaxes.ProductInfo prodC = new GetTaxes.ProductInfo(); prodC.ProductIOSC = "C"; prodC.Rate = 30.0M; GetTaxes.ProductInfo prodD = new GetTaxes.ProductInfo(); prodD.ProductIOSC = "D"; prodD.Rate = 40.0M; prodlst.Add(prodA); prodlst.Add(prodB); prodlst.Add(prodC); prodlst.Add(prodD); request.Products = prodlst.ToArray(); GetTaxes.TaxResponse response = getTaxes.GetSOCTaxes(request); if (response != null) { Console.WriteLine("\n"); Console.WriteLine("Standalone TaxResponse :"); Console.WriteLine("Monthly Taxes:" + response.MonthlyTaxes); Console.WriteLine("FirstBill Taxes" + response.FirstBillTaxes); Console.WriteLine("\n"); } else { Console.WriteLine("\n"); Console.WriteLine("No Tax response"); Console.WriteLine("\n"); } }
public Decimal GetTaxRateForLocation(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); // Instantiate TaxJar Tax Calculator TaxCalculator taxJarTaxCalculator = new TaxCalculator(); // Call TaxCalculator application Decimal taxRateForLocation = taxJarTaxCalculator.GetTaxRateForLocation(taxApiEndpointUrl, taxJarApiKey, taxRequestJsonString); return(taxRateForLocation); }
/// <summary> /// Ensure the transactionId and source are provided. This may include the invoice number. /// </summary> /// <param name="taxInformation"></param> /// <returns></returns> public async Task <TaxResponse> GetPendingTaxCalculation(TaxRequest taxInformation) { var taxRequest = TaxRelayMapper.CreateSovosTaxRequest(taxInformation, _sovosSettings); try { var response = await _client.GetTaxDeterminationAsync(taxRequest); var taxResponse = TaxRelayMapper.CreateTaxResponseFromSovos(response, taxInformation.SaleDate); return(taxResponse); } catch (Refit.ApiException ex) { var response = new TaxResponse(); return((TaxResponse)response.CreateErrorResponse(ex.Content)); } }
public TaxResponse Post(TaxRequest request) { try { var taxRate = _calc.Calculate(_data.GetMunicipalityTaxRecords(request.Municipality), request); var resp = new TaxResponse() { Request = request, TaxRate = taxRate }; return(resp); } catch (Exception ex) { _logger.LogError(ex, "Error Calculating tax rate", new { request = request }); throw ex; } }
private async Task <Guid> CreateTax(Guid municipalityId, DateTime PeriodStartDate, DateTime PeriodEndDate, decimal Value) { var taxRequest = new TaxRequest() { Value = Value, PeriodStartDate = PeriodStartDate, PeriodEndDate = PeriodEndDate, MunicipalityId = municipalityId }; StringContent taxData = new StringContent(JsonConvert.SerializeObject(taxRequest), Encoding.UTF8, "application/json"); var response = await _client.PostAsync("/taxes", taxData); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); return(await response.Content.ReadAsAsync <Guid>()); }
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; })); }
public TaxResponse Post(TaxRequest request) { try { //var request = new TaxRequest(){Municipality="Vilnius", Date= new DateTime(2016,5,2) }; var taxRate = _calc.Calculate(_data.GetMunicipalityTaxRecords(request.Municipality),request ); var resp = new TaxResponse(){Request = request, TaxRate = taxRate }; return resp; }catch(Exception ex) { _logger.LogError(ex,"Error Calculating tax rate", new {request= request}); throw new Exception("Error Calculating tax rate"); } }
/// <summary> /// Gets the <see cref="TaxResult"/> from the AvaTax API based on request parameters. /// </summary> /// <param name="request"> /// The <see cref="TaxRequest"/>. /// </param> /// <returns> /// The <see cref="TaxResult"/>. /// </returns> public TaxResult GetTax(TaxRequest request) { var requestUrl = this.GetApiUrl("tax", "get"); request.CustomerCode = _accountNumber; var requestData = JsonConvert.SerializeObject( request, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var json = this.GetResponse(requestUrl, requestData, RequestMethod.HttpPost); return(JsonConvert.DeserializeObject <TaxResult>(json)); }
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); }
/// <summary> /// Gets the <see cref="TaxResult"/> from the AvaTax API based on request parameters. /// </summary> /// <param name="request"> /// The <see cref="TaxRequest"/>. /// </param> /// <returns> /// The <see cref="TaxResult"/>. /// </returns> public TaxResult GetTax(TaxRequest request) { var requestUrl = this.GetApiUrl("tax", "get"); request.CustomerCode = _accountNumber; var requestData = JsonConvert.SerializeObject( request, Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var json = this.GetResponse(requestUrl, requestData, RequestMethod.HttpPost); return JsonConvert.DeserializeObject<TaxResult>(json); }
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); }
static void Main(string[] args) { Console.WriteLine("Start"); var configBuilder = new ConfigurationBuilder(); configBuilder.AddJsonFile("appSettings.json"); var config = configBuilder.Build(); var services = new ServiceCollection(); services.AddSovosTaxAdapter(config); var container = services.BuildServiceProvider(); var taxhandler = container.GetService <ITaxHandler>(); var taxQuote = new TaxRequest() { SaleDate = DateTime.Now, ShipToInformation = new ShipToInformation() { ZipCode = "64057", Country = "USA" }, TaxCalculationType = 1, LineItemInformation = new List <TaxLineItemRequest>() { new TaxLineItemRequest() { GrossAmount = 100, Quantity = 1, TransactionType = 1, } } }; var response = taxhandler.GetTaxQuote(taxQuote).GetAwaiter().GetResult(); Console.WriteLine(response.InvoiceTotalTaxAmount); Console.WriteLine(response.ErrorMessage); Console.ReadKey(); }
public TaxResult GetTaxResult(TaxRequest request) { return(NonTaxPayingVehicles.Any(a => a == request.VehicleType) ? new TaxResult() : CreateTaxResult(request)); }
/// <summary> /// Maps an <see cref="IInvoice"/> to tax request. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="defaultStoreAddress"> /// The default store address. This is required for items without shipping information. /// </param> /// <param name="estimateOnly"> /// Indicates if the quote should be an estimate or recorded /// </param> /// <returns> /// The <see cref="TaxRequest"/>. /// </returns> public static TaxRequest AsTaxRequest(this IInvoice invoice, ITaxAddress defaultStoreAddress, bool estimateOnly = true) { var addresses = new List <TaxAddress>(); var lines = new List <StatementLineItem>(); defaultStoreAddress.AddressCode = "1"; addresses.Add(defaultStoreAddress as TaxAddress); var shippingItems = invoice.ShippingLineItems().ToArray(); if (shippingItems.Any()) { var counter = 1; var lineNo = 1; foreach (var shipLine in shippingItems) { var shipment = shipLine.ExtendedData.GetShipment <OrderLineItem>(); var shipmentAddresses = shipment.GetTaxAddressArray(counter + 1); foreach (var line in shipment.Items) { lines.Add( new StatementLineItem() { LineNo = lineNo.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'), ItemCode = line.Sku, Amount = line.TotalPrice, Qty = line.Quantity, Description = line.Name, OriginCode = shipmentAddresses[0].AddressCode, DestinationCode = shipmentAddresses[1].AddressCode }); lineNo++; } lines.Add(new StatementLineItem() { LineNo = string.Format("{0}-FR", lineNo.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0')), Amount = shipLine.Price, ItemCode = shipLine.Sku, Qty = shipLine.Quantity, Description = shipLine.Name, OriginCode = shipmentAddresses[0].AddressCode, DestinationCode = shipmentAddresses[1].AddressCode, TaxCode = "FR020100" // TODO this should probably not be hard coded here }); addresses.AddRange(shipmentAddresses); counter++; } } // add items not included in the shipment var notShipped = invoice.Items.Where( x => x.LineItemType != LineItemType.Shipping && x.LineItemType != LineItemType.Discount && !lines.Any(line => line.ItemCode.Contains(x.Sku))); // TODO add lines for non shippable - like downloadable and discounts var taxRequest = new TaxRequest(estimateOnly ? StatementType.SalesOrder : StatementType.SalesInvoice) { DocCode = invoice.PrefixedInvoiceNumber(), Addresses = addresses.ToArray(), DocDate = invoice.InvoiceDate.ToString("yyyy-MM-dd"), Lines = lines }; return(taxRequest); }
internal async Task <CalculateTaxRateResponse> CalculateTaxRate(TaxRequest taxRequest) { var apiResponse = await _client.PostAsync <CalculateTaxRateResponse, TaxRequest>("tax/rates", taxRequest); return(apiResponse); }
public ActionResult Checkout(decimal orderTotal, string state, string zipCode, bool resetFlag = false) { TaxResultViewModel taxResultViewModel = new TaxResultViewModel(); // Reset the form to accept new data if requested by the user if (resetFlag) { // Populate error message used by client side validation taxResultViewModel.ErrorMessage = "Please correct the highlighted fields and try again."; return(View(taxResultViewModel)); } TaxRequest taxRequest = new TaxRequest(); // Assuming the store is located at this address, so this From Address is used in all tax calculations // This can be made configurable with additional form fields in the view taxRequest.FromCity = "New York"; taxRequest.FromCountry = "US"; taxRequest.FromState = "NY"; // taxRequest.FromStreet = "20 Cooper Square"; taxRequest.FromZip = "10003"; taxRequest.Amount = orderTotal; // Special Promotion: FREE SHIPPING on all orders winter 2021! taxRequest.ShippingAmount = 0; taxRequest.ToCountry = "US"; taxRequest.ToState = state; taxRequest.ToZip = zipCode; // Add From Address to Nexus Addresses taxRequest.NexusAddresses.Add(new NexusAddress() { Country = taxRequest.FromCountry, State = taxRequest.FromState, ZipCode = taxRequest.FromZip }); // Add To Address to Nexus Addresses taxRequest.NexusAddresses.Add(new NexusAddress() { Country = taxRequest.ToCountry, State = taxRequest.ToState, ZipCode = taxRequest.ToZip }); taxResultViewModel.OrderTotal = orderTotal; taxResultViewModel.State = state; taxResultViewModel.ZipCode = zipCode; // Call TaxCalculator taxResultViewModel.TaxResult = GetTaxResultForOrder(taxRequest); taxResultViewModel.OrderTotalWithTax = orderTotal + taxResultViewModel.TaxResult.TaxAmount; // Check for bad request // Likely due to state/zipcode mismatch if (taxResultViewModel.TaxResult.TaxRate == -1) { // Populate error message to display to user in case of bad request taxResultViewModel.ErrorMessage = "Sorry but there was a problem finding your tax rate, please check state and zipcode or try again later."; taxResultViewModel.BadRequest = true; } return(View(taxResultViewModel)); }
private IEnumerable <TaxRecord> ApplicableTaxes(IEnumerable <TaxRecord> municipalityData, TaxRequest request) { foreach (var period in municipalityData) { if (request.Date >= period.Start && request.Date <= period.End) { yield return(period); } } }