public override IEnumerable<TaxRate> CalculateRates(Domain.Common.IEvaluationContext context) { var taxEvalContext = context as TaxEvaluationContext; if (taxEvalContext == null) { throw new NullReferenceException("taxEvalContext"); } var retVal = new List<TaxRate>(); if (taxEvalContext.TaxRequest != null) { foreach (var line in taxEvalContext.TaxRequest.Lines) { var rate = new TaxRate { Rate = line.Amount * Rate * 0.01m, Currency = taxEvalContext.TaxRequest.Currency, TaxProvider = this, Line = line }; retVal.Add(rate); } } return retVal; }
public void Update(TaxRate taxRate) { taxRate = Validate(taxRate); _taxRates.Attach(taxRate); _repository.Entry(taxRate).State = EntityState.Modified; _repository.SaveChanges(); }
private TaxRate Validate(TaxRate taxRate) { if (!string.IsNullOrWhiteSpace(taxRate.Description)) taxRate.Description = taxRate.Description.Trim(); else throw new BusinessLogicException("A name or description is required for all tax rates."); return taxRate; }
public void Insert(TaxRate taxRate) { taxRate = Validate(taxRate); if (_taxRates.Any(i => i.Description.Equals(taxRate.Description, StringComparison.InvariantCultureIgnoreCase))) throw new BusinessLogicException("A tax rate with that name already exists."); _taxRates.Add(taxRate); _repository.SaveChanges(); }
public ATaxConfiguration() { taxConfiguration = new Mock <IRepository <Tax> >(); var reducedTax = new Tax("RED", new List <TaxRate>()); var reducedTaxRate = new TaxRate("RED-1", reducedTax, 0.10m, DateTime.MinValue, DateTime.MaxValue); reducedTax.TaxConfiguration.Add(reducedTaxRate); var regularTax = new Tax("REG", new List <TaxRate>()); var regularTaxRate = new TaxRate("REG-1", regularTax, 0.20m, DateTime.MinValue, DateTime.MaxValue); regularTax.TaxConfiguration.Add(regularTaxRate); taxConfiguration.Setup(t => t.Get("RED")).Returns(reducedTax); taxConfiguration.Setup(t => t.Get("REG")).Returns(regularTax); }
public async Task <ICollection <TaxRate> > GetByLocationAsync(TaxRate taxRate) { using (var scope = ServiceScopeFactory.CreateScope()) { var dbContext = GetDatabaseContext(scope); var results = await dbContext.TaxRates .Where(t => t.Active && t.Country == taxRate.Country && t.PostalCode == taxRate.PostalCode) .ToListAsync(); return(Mapper.Map <List <TableModel.TaxRate> >(results)); } }
public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + (ModifiedDate == default(DateTime) ? 0 : ModifiedDate.GetHashCode()); hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode()); hash = hash * 23 + (Rowguid == default(Guid) ? 0 : Rowguid.GetHashCode()); hash = hash * 23 + (StateProvinceId == default(int) ? 0 : StateProvinceId.GetHashCode()); hash = hash * 23 + (TaxRate == default(decimal) ? 0 : TaxRate.GetHashCode()); hash = hash * 23 + (TaxType == default(byte) ? 0 : TaxType.GetHashCode()); return(hash); } }
public ActionResult Edit(TaxRate taxRate) { try { DocumentSession.Store(taxRate); ShowInfoMessage("Tax rate saved successfully"); } catch (Exception ex) { ShowErrorMessage(ex.Message); } return(View(taxRate)); }
public override bool StoreToXml(XmlNode node) { if (!base.StoreToXml(node)) { return(false); } XmlDocument doc = node.OwnerDocument; XmlAttribute attribute = doc.CreateAttribute("taxRate"); NumberFormatInfo numberFormat = CultureInfo.CurrentCulture.NumberFormat; numberFormat.NumberDecimalSeparator = "."; attribute.Value = TaxRate.ToString(numberFormat); return(true); }
public void tax_rate_description_must_not_be_empty() { //arrange var taxRate = new TaxRate(); var validatonContext = new ValidationContext(taxRate, null, null); var validationResults = new Collection <ValidationResult>(); //act var isValid = Validator.TryValidateObject(taxRate, validatonContext, validationResults); //assert Assert.IsFalse(isValid); CollectionAssert.Contains(validationResults.Select(r => r.ErrorMessage), "The Description field is required."); }
/// <summary> /// Deletes a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual async Task DeleteTaxRate(TaxRate taxRate) { if (taxRate == null) { throw new ArgumentNullException("taxRate"); } await _taxRateRepository.DeleteAsync(taxRate); await _cacheManager.RemoveByPattern(TAXRATE_PATTERN_KEY); //event notification await _mediator.EntityDeleted(taxRate); }
/// <summary> /// Updates the tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual async Task UpdateTaxRate(TaxRate taxRate) { if (taxRate == null) { throw new ArgumentNullException("taxRate"); } await _taxRateRepository.UpdateAsync(taxRate); await _cacheBase.RemoveByPrefix(TAXRATE_PATTERN_KEY); //event notification await _mediator.EntityUpdated(taxRate); }
/// <summary> /// Inserts a tax rate /// </summary> /// <param name="taxRate">Tax rate</param> public virtual void InsertTaxRate(TaxRate taxRate) { if (taxRate == null) { throw new ArgumentNullException("taxRate"); } _taxRateRepository.Insert(taxRate); _cacheManager.RemoveByPattern(TAXRATE_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(taxRate); }
/// <summary> /// Tax calculation /// </summary> /// <param name="employee">Individual employee detail</param> /// <param name="taxRate">Tax Slab/Rate of the employee</param> /// <returns>Payslip - Response payload</returns> public Payslip Calculation(Employee employee, TaxRate taxRate) { Payslip payslip = new Payslip(); payslip.EmployeeName = employee.FirstName + " " + employee.LastName; payslip.PayPeriod = employee.PaymentStartDate.ToString("dd/MM/yyyy"); payslip.GrossIncome = Math.Round(employee.AnnualSalary / 12); payslip.IncomeTax = Math.Round((taxRate.baseTaxAmount + (employee.AnnualSalary - taxRate.notTaxableAmount) * (taxRate.increaseTaxAmountBy / 100)) / 12); payslip.NetIncome = Math.Round(payslip.GrossIncome - payslip.IncomeTax); payslip.SuperRateAmount = Math.Round(payslip.GrossIncome * (employee.SuperRate / 100)); return(payslip); }
public async Task <IActionResult> Create([Bind("Id,TaxItemSettingId,HoldingTypeId,HoldingCategoryId,Rate")] TaxRate taxRate) { if (ModelState.IsValid) { _context.Add(taxRate); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["HoldingCategoryId"] = new SelectList(_context.HoldingCategory, "Id", "TypeName", taxRate.HoldingCategoryId); ViewData["HoldingTypeId"] = new SelectList(_context.HoldingType, "Id", "TypeName", taxRate.HoldingTypeId); ViewData["TaxItemSettingId"] = new SelectList(_context.TaxItemSetting, "Id", "ItemName", taxRate.TaxItemSettingId); return(View(taxRate)); }
public TaxRateResponseModel(TaxRate taxRate) : base("profile") { if (taxRate == null) { throw new ArgumentNullException(nameof(taxRate)); } Id = taxRate.Id; Country = taxRate.Country; State = taxRate.State; PostalCode = taxRate.PostalCode; Rate = taxRate.Rate; }
public ActionResult Add(TaxRate taxRate) { try { DocumentSession.Store(taxRate); taxRate.CreateAt = DateTime.Now; return(RedirectToAction("Index")); } catch (Exception ex) { ShowErrorMessage(ex.Message); return(View()); } }
public PayslipCollections CalculatePaySlipForAllEmployees([FromBody] EmployeeCollections employees) { PayslipCollections payslips = new PayslipCollections(); payslips.Payslips = new List <Payslip>(); foreach (Employee employee in employees.Employees) { TaxRate taxRate = _taxRates.GetTaxRate(employee); Payslip payslip = _payslipCalculation.Calculation(employee, taxRate); payslips.Payslips.Add(payslip); } return(payslips); }
public static TaxRate ToWebModel(this VirtoCommerceDomainTaxModelTaxRate serviceModel, Currency currency) { var retVal = new TaxRate(currency); retVal.Rate = new Money(serviceModel.Rate.Value, currency); if (serviceModel.Line != null) { retVal.Line = new TaxLine(currency); retVal.Line.InjectFrom(serviceModel.Line); retVal.Line.Amount = new Money(serviceModel.Line.Amount.Value, currency); retVal.Line.Price = new Money(serviceModel.Line.Price.Value, currency); } return(retVal); }
public decimal Calculate(TaxRate taxRate, decimal taxableIncome) { var currentMedicareLevyTaxSlab = taxRate.MedicareLevyIncomeRange.Find(x => x.Lower <= taxableIncome && (!x.Upper.HasValue || x.Upper >= taxableIncome)); var medicareLevy = new decimal(0.00); if (!currentMedicareLevyTaxSlab.Upper.HasValue) { medicareLevy = Math.Round(((taxableIncome * currentMedicareLevyTaxSlab.Rate) / 100)); } else { medicareLevy = Math.Round((((taxableIncome - (currentMedicareLevyTaxSlab.Lower - 1)) * currentMedicareLevyTaxSlab.Rate) / 100)); } return(medicareLevy); }
public void TaxRateUpdatedAsyncTestsUsingoAuth() { //Creating the TaxRate for Adding //TaxRate entity = QBOHelper.CreateTaxRate(qboContextoAuth); //Adding the TaxRate TaxRate added = Helper.FindOrAdd <TaxRate>(qboContextoAuth, new TaxRate()); //Update the TaxRate TaxRate updated = QBOHelper.UpdateTaxRate(qboContextoAuth, added); //Call the service TaxRate updatedReturned = Helper.UpdateAsync <TaxRate>(qboContextoAuth, updated); //Verify updated TaxRate QBOHelper.VerifyTaxRate(updated, updatedReturned); }
public async Task <IActionResult> AddTaxRate(TaxRateListModel model) { var taxRate = new TaxRate { StoreId = model.AddStoreId, TaxCategoryId = model.AddTaxCategoryId, CountryId = model.AddCountryId, StateProvinceId = model.AddStateProvinceId, Zip = model.AddZip, Percentage = model.AddPercentage }; await _taxRateService.InsertTaxRate(taxRate); return(Json(new { Result = true })); }
public ActionResult AddTaxRate(TaxRateListModel model) { var taxRate = new TaxRate() { TaxCategoryId = model.AddTaxCategoryId, CountryId = model.AddCountryId, StateProvinceId = model.AddStateProvinceId, Zip = model.AddZip, Percentage = model.AddPercentage }; _taxRateService.InsertTaxRate(taxRate); return(Json(new { Result = true })); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (Name != null) { hashCode = hashCode * 59 + Name.GetHashCode(); } if (Description != null) { hashCode = hashCode * 59 + Description.GetHashCode(); } if (MerchantSuppliedId != null) { hashCode = hashCode * 59 + MerchantSuppliedId.GetHashCode(); } if (Active != null) { hashCode = hashCode * 59 + Active.GetHashCode(); } if (Price != null) { hashCode = hashCode * 59 + Price.GetHashCode(); } if (BasePrice != null) { hashCode = hashCode * 59 + BasePrice.GetHashCode(); } if (Default != null) { hashCode = hashCode * 59 + Default.GetHashCode(); } if (SortId != null) { hashCode = hashCode * 59 + SortId.GetHashCode(); } if (TaxRate != null) { hashCode = hashCode * 59 + TaxRate.GetHashCode(); } if (Extras != null) { hashCode = hashCode * 59 + Extras.GetHashCode(); } return(hashCode); } }
protected void SaveButton_Click(object sender, EventArgs e) { if (Page.IsValid) { try { int taxRateId = 0; int.TryParse(lblTaxRateId.Text, out taxRateId); int taxCategoryId = int.Parse(this.ddlTaxCategory.SelectedItem.Value); int countryId = int.Parse(this.ddlCountry.SelectedItem.Value); int stateProvinceId = int.Parse(this.ddlStateProvince.SelectedItem.Value); string zipPostalCode = txtZip.Text; decimal percentage = txtPercentage.Value; TaxRate taxRate = this.TaxRateService.GetTaxRateById(taxRateId); if (taxRate != null) { taxRate.TaxCategoryId = taxCategoryId; taxRate.CountryId = countryId; taxRate.StateProvinceId = stateProvinceId; taxRate.Zip = zipPostalCode; taxRate.Percentage = percentage; this.TaxRateService.UpdateTaxRate(taxRate); } else { taxRate = new TaxRate() { TaxCategoryId = taxCategoryId, CountryId = countryId, StateProvinceId = stateProvinceId, Zip = zipPostalCode, Percentage = percentage }; this.TaxRateService.InsertTaxRate(taxRate); } BindGrid(); ToggleGrid(true); } catch (Exception exc) { ProcessException(exc); } } }
private Money?ConvertAmount(decimal?amount, CalculatorContext context, TaxRate taxRate, bool isFinalPrice, out Tax?tax) { tax = null; if (amount == null) { return(null); } var options = context.Options; // A product price cannot be less than zero. if (amount < 0) { amount = 0; } if (amount != 0) { tax = options.IsGrossPrice ? _taxCalculator.CalculateTaxFromGross(amount.Value, taxRate, options.TaxInclusive, options.RoundingCurrency) : _taxCalculator.CalculateTaxFromNet(amount.Value, taxRate, options.TaxInclusive, options.RoundingCurrency); amount = tax.Value.Price; } var money = _currencyService.ConvertFromPrimaryCurrency(amount.Value, options.TargetCurrency); if (amount != 0 && options.TaxFormat != null) { money = money.WithPostFormat(options.TaxFormat); } if (isFinalPrice && context.HasPriceRange) { var finalPricePostFormat = money.PostFormat; finalPricePostFormat = finalPricePostFormat == null ? options.PriceRangeFormat : string.Format(options.PriceRangeFormat, finalPricePostFormat); if (money.PostFormat != finalPricePostFormat) { money = money.WithPostFormat(finalPricePostFormat); } } return(money); }
public void RemoveRule(TaxRate taxRate) { foreach (var item in driver.FindElements(By.CssSelector("select[name$='[tax_rate_id]']"))) { SelectElement Select = new SelectElement(item); string Text = Select.SelectedOption.Text; string Name; if (Text == taxRate.Name) { Name = item.GetAttribute("name"); string quiery = "//select[@name='" + Name + "']/parent::td/following-sibling::td/button[@data-original-title='Remove']"; driver.FindElement(By.XPath(quiery)).Click(); } } ClickSaveButton(); }
public async Task Can_I_Get_Tax_Rate_By_Wrong_ZipCode() { //arrange int zipCode = -4; TaxRate data = new TaxRate(); Rate r = new Rate(); data.rate = r; data.rate.county = "dummy"; //act data = await _fixture._taxhttpClient.GetTaxRatesAsync(zipCode); //assert Assert.Null(data); }
public ActionResult Create([Bind(Include = "Id,TaxRateName,TaxRateValue,TaxRateDescription")] TaxRate taxRate) { if (ModelState.IsValid) { taxRate.CreatedBy = User.Identity.GetUserId <int>(); taxRate.IsDeleted = false; taxRate.CreatedAt = DateTime.Now; taxRate.IsActive = true; db.TaxRates.Add(taxRate); db.SaveChanges(); Session["success"] = "Tax Rate Created"; return(RedirectToAction("Index")); } return(View(taxRate)); }
protected override void OnDeleteToolBarItem() { if (MessageBoxService.AskForDelete(_activeTaxRate.Title) == true) { using (var dbContext = new FarnahadManufacturingDbContext()) { var taxRateInDb = dbContext.TaxRates.Find(_activeTaxRate.Id); dbContext.TaxRates.Remove(taxRateInDb); dbContext.SaveChanges(); } LoadSearchGridControl(); _activeTaxRate = new TaxRate(); IsNotEditingAndAdding(); } }
public async void Get_ThrowsTaxRateNotFoundException_WhenZipNotProvided() { //Arrange TaxRate taxRate = null; var serviceMock = new Mock <ITaxCalculatorService>(); serviceMock.Setup(o => o.GetTaxRateForLocation(It.IsAny <Location>())).ReturnsAsync(taxRate); var appSettingsMock = new Mock <IOptions <AppSettings> >(); TaxRateController controller = new TaxRateController(_mockLogger.Object, _mapper, serviceMock.Object, appSettingsMock.Object); // Act + Assert await Assert.ThrowsAsync <TaxRateNotFoundException>(() => controller.GetTaxRate(new TaxRateRequestDto())); }
private static string PromptForValidState(string prompt, bool extraInfo = false) { string state = ""; bool validState = false; bool error = false; while (!validState) { OffsetTop(); DisplayValidStates(); if (error) { Console.ForegroundColor = ErrorColor; Console.WriteLine("\tInvalid State."); Console.WriteLine(); } Console.ForegroundColor = PromptColor; Console.Write("\t" + prompt); Console.ForegroundColor = EmphasisColor; state = Console.ReadLine().Trim().ToUpper(); Console.Clear(); Console.ResetColor(); if (TaxRateOperations.IsAllowedState(state)) { if (extraInfo) { TaxRate rate = TaxRateOperations.GetTaxRateFor(state); OffsetTop(); Console.WriteLine("\tThe tax rate for {0} is {1:p}", rate.State, rate.TaxPercent * 0.01M); Console.WriteLine("\t----------------------------------------"); Console.WriteLine(); } validState = true; } else { error = true; } } return(state); }
private void grdTaxRate_RowEditing(object sender, GridViewEditEventArgs e) { if (ddGeoZones.SelectedIndex > -1) { geoZoneGuid = new Guid(ddGeoZones.SelectedValue); } GridView grid = (GridView)sender; grid.EditIndex = e.NewEditIndex; Guid guid = new Guid(grid.DataKeys[grid.EditIndex].Value.ToString()); BindGrid(); Button btnDelete = (Button)grid.Rows[e.NewEditIndex].Cells[0].FindControl("btnGridDelete"); if (btnDelete != null) { btnDelete.Attributes.Add("OnClick", "return confirm('" + Resource.TaxRateGridDeleteWarning + "');"); } DropDownList ddTaxClass = (DropDownList)grid.Rows[grid.EditIndex].Cells[0].FindControl("ddTaxClass"); if (ddTaxClass != null) { using (IDataReader reader = TaxClass.GetBySite(siteSettings.SiteGuid)) { ddTaxClass.DataSource = reader; ddTaxClass.DataBind(); } if (guid != Guid.Empty) { TaxRate taxRate = new TaxRate(guid); ListItem listItem = ddTaxClass.Items.FindByValue(taxRate.TaxClassGuid.ToString()); if (listItem != null) { ddTaxClass.ClearSelection(); listItem.Selected = true; } } } ddCountry.Enabled = false; ddGeoZones.Enabled = false; }
public void CalculateTax(Cart cart) { // TODO: this doesn't take into account discounts decimal taxAmount = 0; if (cart.OrderInfo.TaxZoneGuid == Guid.Empty) { GeoCountry country = new GeoCountry(cart.OrderInfo.BillingCountry); GeoZone taxZone = GeoZone.GetByCode(country.Guid, cart.OrderInfo.BillingState); if (taxZone != null) { cart.OrderInfo.TaxZoneGuid = taxZone.Guid; } } if (cart.OrderInfo.TaxZoneGuid != Guid.Empty) { Collection <TaxRate> taxRates = TaxRate.GetTaxRates(this.SiteGuid, cart.OrderInfo.TaxZoneGuid); if (taxRates.Count > 0) { foreach (CartOffer offer in cart.CartOffers) { offer.Tax = 0; foreach (TaxRate taxRate in taxRates) { if (offer.TaxClassGuid == taxRate.TaxClassGuid) { offer.Tax += (taxRate.Rate * (offer.OfferPrice * offer.Quantity)); offer.Save(); taxAmount += offer.Tax; //break; } } } } } cart.TaxTotal = Math.Round(taxAmount, this.RoundingDecimalPlaces, this.RoundingMode); if (cart.TaxTotal < 0) { cart.TaxTotal = 0; } cart.Save(); }
/// <summary> /// maps <paramref name="rate"/> from enum to 0..1 /// </summary> /// <param name="rate"></param> /// <returns></returns> public static double GetTaxValue(TaxRate rate) { double num = Enum.GetValues(typeof(TaxRate)).Length; int index = 0; foreach (TaxRate r in Enum.GetValues(typeof(TaxRate))) { if (r == rate) return index / num; index++; } return 0; }
public bool ChangeTndn(int tndnRate, DateTime beginDate) { TaxRate currentTndnTaxRate = db.TaxRates.FirstOrDefault( m => m.TaxTypeId == 2 && DateTime.Now >= m.BeginDate && DateTime.Now <= m.EndDate); if (currentTndnTaxRate == null || currentTndnTaxRate.TaxRateValue == tndnRate) { return false; } currentTndnTaxRate.EndDate = beginDate.AddDays(-1); TaxRate taxRate = new TaxRate(); taxRate.TaxTypeId = 2; taxRate.TaxRateValue = tndnRate; taxRate.BeginDate = beginDate; taxRate.EndDate = new DateTime(9999, 12, 31); db.TaxRates.Add(taxRate); try { db.SaveChanges(); } catch (Exception) { return false; } return true; }
public void Initialization() { _taxRate = new TaxRate(0.23m); }
public void Delete(TaxRate taxRate) { _taxRates.Attach(taxRate); _repository.Entry(taxRate).State = EntityState.Deleted; _repository.SaveChanges(); }
private List<TaxRate> GetTaxRates(TaxEvaluationContext evalContext) { 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 = evalContext.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 = evalContext.Currency, TaxProvider = this, Line = evalContext.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 void Initialization() { _taxRate = new TaxRate(0.23m); _product = new global::Domain.Assortment.Product(new ProductId(Guid.NewGuid()), "P1", "Product 1", _taxRate); }