public async Task <TaxResponse> CalculateTax(Tax taxInfo) { TaxResponse taxResponse = new TaxResponse(); string url = this.apiUrl + "taxes"; try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.apiKey); HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, url); string jsonContent = JsonConvert.SerializeObject(taxInfo); requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponse = await client.PostAsync(url, requestMessage.Content); if (httpResponse.IsSuccessStatusCode) { taxResponse = JsonConvert.DeserializeObject <TaxResponse>(httpResponse.Content.ToString()); } } } catch (Exception ex) { System.Diagnostics.Debug.Write("Error {0}", ex.Message); } return(taxResponse); }
public Response EditOrder(Order order, DateTime date) { Response response = new Response(); TaxResponse taxResponse = new TaxResponse(); ProductResponse productRepsone = new ProductResponse(); OrderResponse orderResponse = new OrderResponse(); orderResponse = GetOrder(order.OrderNumber, date); productRepsone.product = productRepo.FindByProductType(order.ProductType); taxResponse.tax = taxRepo.FindByState(order.State); if (!orderResponse.Success) { response.Success = false; response.Message = orderResponse.Message; return(response); } if (string.IsNullOrWhiteSpace(order.CustomerName) || order.Area < 100 || taxResponse.tax == null || productRepsone.product == null) { response.Success = false; response.Message = "Missing some required fields or invalid inputs."; return(response); } response.Success = true; order = CalculateOrder(order); repo.EditOrder(order, date.ToString("MMddyyyy")); return(response); }
private TaxResponse ParseTaxLine(string line, int lineNR) { TaxResponse response = new TaxResponse(); string[] columns = line.Split(_delimeter); if (columns.Length != Enum.GetNames(typeof(TaxFileHeaderElement)).Length) { response.Message = $"The data on line number {lineNR} in the file {TaxesFileName} is corrupt. \nContact IT!"; response.Success = false; return(response); } bool taxReadSuccess = true; string taxReadExMessage = $"The following elements on line number {lineNR} were not able to be parsed:\n"; StateTax myStateTax = new StateTax(); //StateAbbreviation if (columns[(int)TaxFileHeaderElement.StateAbbreviation].All(c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c))) { myStateTax.StateCode = columns[(int)TaxFileHeaderElement.StateAbbreviation]; } else { taxReadExMessage += $"* StateAbbreviation\n"; taxReadSuccess = false; } //StateName if (columns[(int)TaxFileHeaderElement.StateName].All(c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c))) { myStateTax.StateName = columns[(int)TaxFileHeaderElement.StateName]; } else { taxReadExMessage += $"* StateName\n"; taxReadSuccess = false; } //TaxRate if (decimal.TryParse(columns[(int)TaxFileHeaderElement.TaxRate], out decimal parsedTaxRate)) { myStateTax.TaxRate = parsedTaxRate; } else { taxReadExMessage += $"* TaxRate\n"; taxReadSuccess = false; } //Check if all elements were read w/o error if (taxReadSuccess) { response.Success = true; response.StateTax = myStateTax; return(response); } else { response.Message = taxReadExMessage; response.Success = true; return(response); } }
public OrderResponse AddOrder(Order order, DateTime date) { OrderResponse response = new OrderResponse(); TaxResponse taxResponse = new TaxResponse(); ProductResponse productRepsone = new ProductResponse(); productRepsone.product = productRepo.FindByProductType(order.ProductType); taxResponse.tax = taxRepo.FindByState(order.State); if (date < DateTime.Today) { response.Success = false; response.Message = "Cannot add to past days."; return(response); } if (string.IsNullOrWhiteSpace(order.CustomerName) || order.Area < 100 || taxResponse.tax == null || productRepsone.product == null) { response.Success = false; response.Message = "Missing some required fields or invalid inputs."; return(response); } order = CalculateOrder(order); order.OrderNumber = repo.AddOrder(order, date.ToString("MMddyyyy")).OrderNumber; response.Success = true; response.order = order; return(response); }
public async Task <IActionResult> GetTax([FromBody] string rawJsonOject) { try { var tax = JsonConvert.DeserializeObject <Tax>(rawJsonOject); Vehicle vehicle = null; switch (tax.Vehicle.ToLower()) { case "car": vehicle = new Car(); break; case "motorcycle": vehicle = new Motorcycle(); break; default: return(NotFound()); break; } var response = new TaxResponse(); response.TotalTax = new CongestionTaxCalculator().GetTax(vehicle, tax.Dates); return(Ok(JsonConvert.SerializeObject(response))); } catch { return(NotFound()); } }
public void CalculateTax_SantaMonicaZipTest() { TaxJar taxJar = new TaxJar(); TaxResponse taxResponse = new TaxResponse(); Tax tax = new Tax(); tax.FromCountry = "US"; tax.FromZip = "07001"; tax.FromState = "NJ"; tax.ToCountry = "US"; tax.ToZip = "07446"; tax.ToState = "NJ"; tax.Amount = 16.5m; tax.Shipping = 1.5m; TaxLineItem lineItem = new TaxLineItem(); lineItem.Quantity = 1; lineItem.UnitPrice = 15.0m; lineItem.ProductTaxCode = "31000"; tax.LineItems.Add(lineItem); var taxService = new TaxService.TaxService(); Task.Run(async() => { taxResponse.Tax = await taxService.CalculateTax(taxJar, tax); }); Assert.IsTrue(taxResponse.OrderTotalAmount == 16.5m); Assert.IsTrue(taxResponse.Shipping == 1.5m); }
public void AskState(OrderLookupResponse response) { TaxManager taxManager = TaxFactory.Create(); while (true) { Console.Clear(); Console.Write($"Enter State ({response.Order.State}): "); string state = (Console.ReadLine()).ToUpper(); TaxResponse taxResponse = taxManager.TaxRate(state); if (string.IsNullOrEmpty(state)) { ConsoleIO.DisplayOrderDetails(response.Order); return; } else { if (taxResponse.Success) { response.Order.State = taxResponse.Tax.StateAbbreviation; //set state response.Order.TaxRate = taxResponse.Tax.TaxRate; //make sure the new tax goes through ConsoleIO.DisplayOrderDetails(response.Order); break; } else { Console.WriteLine(taxResponse.Message); ConsoleIO.PressAnyKey(); continue; //Console.Clear(); } } } }
public async Task <TaxRefundResponse> RefundRequest(TaxRefundRequest refundRequest) { var taxRequest = TaxRelayMapper.CreateSovosTaxRequest(refundRequest, _sovosSettings); if (refundRequest.IsRefund) { foreach (var line in taxRequest.LineItems) { line.DebitCreditIndicator = DebitCreditIndicator.Credit; } } try { var response = await _client.GetTaxDeterminationAsync(taxRequest); var taxResponse = TaxRelayMapper.CreateTaxRefundResponseFromSovos(response, refundRequest.SaleDate); return(taxResponse); } catch (Refit.ApiException ex) { var response = new TaxResponse(); return((TaxRefundResponse)response.CreateErrorResponse(ex.Content)); } }
public async Task <Tax> CalculateTax(TaxJar taxJar, Tax taxInfo) { //setting the api auth values TaxResponse taxResponse = new TaxResponse(); if (taxInfo.ToCountry.Equals("")) { taxResponse.Tax = null; } else { try { await Task.Run(async() => { taxResponse = await taxJar.CalculateTax(taxInfo); }); } catch (Exception ex) { System.Diagnostics.Debug.Write("Error {0}", ex.Message); } } return(taxResponse.Tax); }
public void GetTaxFail() { IStateRepo repo = new TestTaxRepo(); TaxMgr tm = new TaxMgr(repo); TaxResponse resp = tm.GetTaxes("OHO"); Assert.AreEqual(false, resp.Success); }
public void TestCalculateTax(float expectedFullPrice, float price, RegionTax regionTax) { TaxResponse response = _taxCalculatorService.CalculateTax(price, regionTax); Assert.AreEqual(expectedFullPrice, response.FullPrice); Assert.AreEqual(price, response.OriginalPrice); Assert.AreEqual(regionTax.EstimatedCombinedRate, response.TaxRate); }
public void GetTax() { IStateRepo repo = new TestTaxRepo(); TaxMgr tm = new TaxMgr(repo); TaxResponse resp = tm.GetTaxes("OH"); StateTax tax = resp.StateTax; Assert.IsNotNull(tax); }
public TaxResponse GetSOCTaxes(TaxRequest taxrequest) { TaxResponse taxresponse = new TaxResponse(); if (taxrequest != null && taxrequest.Products != null) { taxresponse = getTaxes(taxrequest.Products); } return(taxresponse); }
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 IMC.API.DTO.Tax TaxForOrder(APIRequestData apiRequest, OrderData orderData) { APIResponseData apiResponse = new APIResponseData(); TaxResponse response = null; string jsonString = string.Empty; var toVendorEntityMapperConfig = new MapperConfiguration(cfg => { cfg.CreateMap <OrderData, TaxForOrderRequest>(); cfg.CreateMap <IMC.API.DTO.LineItem, IMC.API.Integrations.Taxjar.MessageBodies.LineItem>(); }); var toVendorEntityMapper = toVendorEntityMapperConfig.CreateMapper(); TaxForOrderRequest taxForOrder = toVendorEntityMapper.Map <TaxForOrderRequest>(orderData); jsonString = JsonConvert.SerializeObject(taxForOrder); apiRequest.VendorName = "Taxjar"; apiRequest.PostURL = apiRequest.BaseURL + "taxes/"; apiRequest.HttpRequestType = HttpRequestTypeEnum.POST; apiRequest.PostDataJSON = jsonString; //Execuring HTTP POST Action to make API call to Vendor API ApiHelper.ExecuteHttpAction(apiRequest, out apiResponse); string result = apiResponse.ResponseContent; response = JsonConvert.DeserializeObject <TaxResponse>(apiResponse.ResponseContent); var toDTOMapperConfig = new MapperConfiguration(cfg1 => { cfg1.CreateMap <TaxResponseAttributes, IMC.API.DTO.Tax>(); cfg1.CreateMap <IMC.API.Integrations.Taxjar.MessageBodies.TaxJurisdictions, IMC.API.DTO.TaxJurisdictions>(); cfg1.CreateMap <IMC.API.Integrations.Taxjar.MessageBodies.TaxBreakdown, IMC.API.DTO.TaxBreakdown>(); cfg1.CreateMap <IMC.API.Integrations.Taxjar.MessageBodies.TaxBreakdownLineItem, IMC.API.DTO.TaxBreakdownLineItem>(); cfg1.CreateMap <IMC.API.Integrations.Taxjar.MessageBodies.TaxBreakdownShipping, IMC.API.DTO.TaxBreakdownShipping>(); cfg1.CreateMap <IMC.API.Integrations.Taxjar.MessageBodies.Breakdown, IMC.API.DTO.Breakdown>(); }); var toDTOMapper = toDTOMapperConfig.CreateMapper(); IMC.API.DTO.Tax tax = toDTOMapper.Map <IMC.API.DTO.Tax>(response.Tax); //Clear all the object assignments toVendorEntityMapperConfig = null; toDTOMapperConfig = null; toVendorEntityMapper = null; toDTOMapper = null; return(tax); }
[TestCase("New York", "NY", 8.0)]//true public void TaxGetTest(string state, string abb, decimal taxi) { Tax tax = new Tax { StateName = state, StateAbbreviation = abb, TaxRate = taxi }; TaxManager manager = TaxFactory.Create(); TaxResponse response = manager.TaxRate(state); Assert.AreEqual(response.Tax.StateName, state); Assert.AreEqual(response.Tax.StateAbbreviation, abb); Assert.AreEqual(response.Tax.TaxRate, taxi); }
public TaxResponse GetTaxByState(string stateAbbr) { TaxResponse response = new TaxResponse(); try { TaxesResponse responseTs = new TaxesResponse(); responseTs = GetTaxes(); if (responseTs.Success) { StateTax statetaxToGet = responseTs.Taxes.Find(t => t.StateCode.ToUpper() == stateAbbr.ToUpper()); if (statetaxToGet == null) { response.Message = $"Was unable to find a state matching state abbreviation: {stateAbbr}!"; response.Success = false; return(response); } else { response.Success = true; response.StateTax = statetaxToGet; return(response); } } else { response.Message = responseTs.Message; response.Success = false; return(response); } } catch (FileNotFoundException) { response.Message = $"The file: {TaxesFileName} was not found. \nContact IT!"; response.Success = false; return(response); } catch (Exception ex) { throw ex; //Throw exception up to calling method for handling in catch there. } finally { } }
/// <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; } }
public async Task <TaxResponse> GetTax(TaxJarRequest taxJarRequest) { try { taxResponse = new TaxResponse(); using (FaceDBEntities db = new FaceDBEntities()) { var client = new TaxjarApi(ApplicationConfiguration.TAX_JAR_ACCESS_KEY); if (!string.IsNullOrEmpty(taxJarRequest.UserEmail)) { var systemUser = await db.system_user.Where(x => x.email == taxJarRequest.UserEmail && x.Blocked == "N").FirstOrDefaultAsync(); if (systemUser.id > 0) { //var rates = client.RatesForLocation(systemUser.ZipCode.ToString(), new { }); var tax = client.TaxForOrder(new { from_zip = systemUser.ZipCode.ToString() }); taxResponse.combined_rate = tax.Rate; } else { taxResponse.Success = false; taxResponse.Message = CustomErrorMessages.INVALID_EMAIL; } } else { taxResponse.Success = false; taxResponse.Message = CustomErrorMessages.INVALID_INPUTS; } taxResponse.Success = true; taxResponse.Message = null; } } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); taxResponse.Success = false; taxResponse.Message = CustomErrorMessages.INTERNAL_ERROR; } return(taxResponse); }
public TaxResponse GetTaxFromTaxFile(string state) { TaxResponse response = new TaxResponse(); Tax tax = taxRepo.FindByState(state.ToUpper()); if (tax == null) { response.Success = false; response.Message = "Not allowed to sell to that state."; return(response); } response.tax = tax; response.Success = true; return(response); }
public TaxResponse GetTaxes(string stateAbb) { StateTax tax = repo.GetTaxes(stateAbb); TaxResponse resp = new TaxResponse(); if (tax == null) { resp.Success = false; resp.Message = "Do not have tax info for this state..."; } else { resp.Success = true; resp.StateTax = tax; } return(resp); }
public TaxResponse TaxRate(string state) { TaxResponse response = new TaxResponse(); response.Tax = _taxRepository.GetTax(state); if (response.Tax == null) { response.Success = false; response.Message = $"{state} is an invalid State"; } else { response.Success = true; } return(response); }
public void CanGetStateTaxByStateCode() { //TaxManager myTM = TaxManagerFactory.Create(); TaxFileRepository myTR = new TaxFileRepository(_dataPath + _taxTestFile); TaxResponse taxResponse = new TaxResponse(); taxResponse = myTR.GetTaxByState("OR"); Assert.IsFalse(taxResponse.Success); taxResponse = myTR.GetTaxByState("TN"); Assert.IsTrue(taxResponse.Success); //TN,Tennessee,9.46 Assert.AreEqual("TN", taxResponse.StateTax.StateCode); Assert.AreEqual("Tennessee", taxResponse.StateTax.StateName); Assert.AreEqual(9.46, taxResponse.StateTax.TaxRate); }
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"); } }
public void CalculateTax_EmptyToCountryTaxInfoTest() { TaxJar taxJar = new TaxJar(); TaxResponse taxResponse = new TaxResponse(); Tax tax = new Tax(); tax.ToCountry = ""; var taxService = new TaxService.TaxService(); Task.Run(async() => { taxResponse.Tax = await taxService.CalculateTax(taxJar, tax); }); Assert.IsNull(taxResponse.Tax); }
/// <summary> /// Updates a pending tax request; does not commit/abort it. /// Requires TransactionId, Transaction Source AND Invoice Number. /// Aborts the existing request by TransactionId, then submits a new request with the provided information, providing /// a new transactionId. /// </summary> /// <param name="updateRequest"></param> /// <returns></returns> public async Task <TaxResponse> UpdatePendingTaxCalculation(TaxUpdatePendingTaxRequest updateRequest) { var taxRequest = TaxRelayMapper.CreateSovosTaxRequest(updateRequest, _sovosSettings); taxRequest.TransactionSource = "OVER_" + taxRequest.TransactionSource; try { var response = await _client.GetTaxDeterminationAsync(taxRequest); var taxResponse = TaxRelayMapper.CreateTaxResponseFromSovos(response, updateRequest.SaleDate); return(taxResponse); } catch (Refit.ApiException ex) { var response = new TaxResponse(); return((TaxResponse)response.CreateErrorResponse(ex.Content)); } }
public TaxResponse getTaxes(List <ProductInfo> products) { TaxResponse taxes = null; if (products != null) { taxes = new TaxResponse(); decimal monthlytotal = products.Sum(prod => prod.Rate); decimal firstBill = monthlytotal + (products.Sum(prod => prod.Rate) / 2); //monthly taxes => 10% taxes.MonthlyTaxes = monthlytotal / 100 * 10; //FirstBill taxes => 10% taxes.FirstBillTaxes = firstBill / 100 * 10; } return(taxes); }
public void SetState(Order order) { TaxManager taxManager = TaxFactory.Create(); while (true) { Console.Clear(); Console.WriteLine("State Choices: "); foreach (Tax t in taxManager.GetTaxes()) { Console.WriteLine($"{t.StateAbbreviation},{t.StateName},Tax Rate: {t.TaxRate}"); } Console.Write($"Enter State: "); string state = (Console.ReadLine()).ToUpper(); TaxResponse taxResponse = taxManager.TaxRate(state); if (string.IsNullOrEmpty(state)) { Console.WriteLine("The entry was null or empty"); ConsoleIO.PressAnyKey(); continue; } else { if (taxResponse.Success) { order.State = taxResponse.Tax.StateAbbreviation; //set state order.TaxRate = taxResponse.Tax.TaxRate; //make sure the new tax goes through break; } else { Console.WriteLine(taxResponse.Message); ConsoleIO.PressAnyKey(); continue; //Console.Clear(); } } } }
public TaxResponse GetTaxByState(string stateAbbr) { TaxResponse response = new TaxResponse(); //Find matching record, or return null //return StateTax lookedupTax = _taxes.Find(t => t.StateCode.ToUpper() == stateAbbr.ToUpper()); if (lookedupTax != null && lookedupTax.StateCode.ToUpper() == stateAbbr.ToUpper()) { response.Success = true; response.StateTax = lookedupTax; return(response); } else { response.Message = $"Could not find a tax rate for the state: {stateAbbr}!"; response.StateTax = lookedupTax; return(response); } }