From a4ee4efd6f6bd634a9e30c88671bf6854f898d7e Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sat, 30 Dec 2017 15:06:26 +0100 Subject: [PATCH] Refactor: Centralize double-to-cents parsing in one place --- Logic/Financial/BitcoinUtility.cs | 4 +- Logic/Financial/ExchangeRateSnapshot.cs | 2 +- Logic/Support/Formatting.cs | 77 +++++++++++++++++++ Site/Automation/FieldValidation.aspx.cs | 2 +- Site/Automation/FinancialFunctions.aspx.cs | 34 ++++---- Site/Automation/Formatting.aspx.cs | 17 ++-- .../v5/Financial/CurrencyTextBox.ascx.cs | 38 +++------ Site/Pages/v5/Financial/AttestCosts.aspx.cs | 8 +- .../v5/Financial/ListInvoicesInbound.aspx.cs | 8 +- Site/Pages/v5/Ledgers/AccountPlan.aspx.cs | 6 +- .../Pages/v5/Ledgers/BalanceTransactions.aspx | 27 ++++++- .../v5/Ledgers/BalanceTransactions.aspx.cs | 31 ++++++++ Site/Pages/v5/Ledgers/InspectLedgers.aspx.cs | 6 +- 13 files changed, 173 insertions(+), 87 deletions(-) diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index 95407919..523b3632 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -867,8 +867,8 @@ namespace Swarmops.Logic.Financial JObject feeData = JObject.Parse( new WebClient().DownloadString("https://blockexplorer.com/api/utils/estimatefee?nbBlocks=" + blocksWait.ToString(CultureInfo.InvariantCulture))); - double feeWholeCoins = Double.Parse((string)feeData[blocksWait.ToString(CultureInfo.InvariantCulture)], NumberStyles.AllowDecimalPoint); - satoshisPerThousandBytes = (Int64)(feeWholeCoins * _satoshisPerBitcoin); + double feeWholeCoins = Double.Parse((string)feeData[blocksWait.ToString(CultureInfo.InvariantCulture)], NumberStyles.AllowDecimalPoint); // rounding errors are okay, don't use Formatting fn + satoshisPerThousandBytes = Convert.ToInt64(feeWholeCoins * _satoshisPerBitcoin); } _lastFeeSatoshisLookup[chain] = satoshisPerThousandBytes; diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs index dffa6ed5..311035a8 100644 --- a/Logic/Financial/ExchangeRateSnapshot.cs +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -96,7 +96,7 @@ namespace Swarmops.Logic.Financial string currencyCode = match.Groups[1].Value; string currencyName = match.Groups[2].Value; double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint, - CultureInfo.InvariantCulture); + CultureInfo.InvariantCulture); // rounding errors and loss of precision ok, don't use Formatting fn btcRate /= 1000000.0; // We're operating in microbitcoin, so adjust the stored exchange rate accordingly (right-shift six decimal places) diff --git a/Logic/Support/Formatting.cs b/Logic/Support/Formatting.cs index a419a9d6..52c5359d 100644 --- a/Logic/Support/Formatting.cs +++ b/Logic/Support/Formatting.cs @@ -136,6 +136,83 @@ namespace Swarmops.Logic.Support } + public enum ParsingScale + { + Unknown = 0, + Cents, + Metacents + } + + + public static Int64 ParseDoubleStringAsCents (string input, CultureInfo culture = null, ParsingScale scale = ParsingScale.Cents) + { + // Parses first according to culture, and if fails, according to neutral culture + // Throws ArgumentException if fails + + double outputHolder; + bool success = false; + input = input.Trim(); + + if (culture == null) + { + culture = CultureInfo.CurrentCulture; + } + + // Try current or provided culture first + + success = Double.TryParse(input, + NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, + culture, out outputHolder); + + if (success) + { + return DoubleRoundToCents(outputHolder, scale); + } + + // Try invariant (US) culture as fallback + + success = Double.TryParse(input, + NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture, out outputHolder); + + if (success) + { + return DoubleRoundToCents(outputHolder, scale); + } + + // No joy, could not convert, so throw + + throw new ArgumentException("Could not parse input as cents: " + input); + } + + private static Int64 DoubleRoundToCents(double input, ParsingScale scale) + { + double epsilonLimit = 0.004; + double scalingFactor = 100.0; + + if (scale == ParsingScale.Metacents) // factor 10,000 instead of 100 + { + epsilonLimit /= 100.0; + scalingFactor *= 100.0; + } + + // Epsilon and true-zero values + if (input > -epsilonLimit && input < epsilonLimit) + { + return 0; + } + + // Positive values + if (input > 0.0) + { + return Convert.ToInt64(input * scalingFactor + 0.2); // +0.2 avoids rounding errors from epsilon losses of precision + } + + // Negative values + + return Convert.ToInt64(input * scalingFactor - 0.2); // -0.2 avoids rounding errors from epsilon losses of precision + } + public static string GeneratePassword (int length) { return Authentication.CreateWeakSecret (length); diff --git a/Site/Automation/FieldValidation.aspx.cs b/Site/Automation/FieldValidation.aspx.cs index 6f28b8fa..6e7966a9 100644 --- a/Site/Automation/FieldValidation.aspx.cs +++ b/Site/Automation/FieldValidation.aspx.cs @@ -41,7 +41,7 @@ namespace Swarmops.Frontend.Automation try { - Double.Parse(amount, NumberStyles.Number); + Swarmops.Logic.Support.Formatting.ParseDoubleStringAsCents(amount); return true; } catch (Exception) diff --git a/Site/Automation/FinancialFunctions.aspx.cs b/Site/Automation/FinancialFunctions.aspx.cs index 0b8e26bb..68f87867 100644 --- a/Site/Automation/FinancialFunctions.aspx.cs +++ b/Site/Automation/FinancialFunctions.aspx.cs @@ -89,33 +89,25 @@ namespace Swarmops.Frontend.Automation return new InterpretedCurrencyResult { Success = false, DisplayMessage = "Cannot interpret currency" }; } - Int64 amountCents = 0; - double amountDouble = 0.0; - bool amountInterpreted = false; - - if (Double.TryParse(currencyStrings[1], NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out amountDouble)) + try { - amountInterpreted = true; - } - else if (Double.TryParse(currencyStrings[1], NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out amountDouble)) - { - amountInterpreted = true; - } + Int64 parsedCents = Swarmops.Logic.Support.Formatting.ParseDoubleStringAsCents(input); - if (!amountInterpreted) + Money money = new Money(parsedCents, currencyUsed); + + return new InterpretedCurrencyResult + { + Success = true, + EnteredAmount = (parsedCents / 100.0).ToString("N2"), + CurrencyCode = money.Currency.Code, + DisplayAmount = (money.ToCurrency(authData.CurrentOrganization.Currency).Cents / 100.0).ToString("N2") + }; + } + catch (ArgumentException) { return new InterpretedCurrencyResult { Success = false, DisplayMessage = "Cannot interpret amount" }; } - Money money = new Money((long) (amountDouble * 100.0 + 0.5), currencyUsed); - - return new InterpretedCurrencyResult - { - Success = true, - EnteredAmount = amountDouble.ToString("N2"), - CurrencyCode = money.Currency.Code, - DisplayAmount = (money.ToCurrency(authData.CurrentOrganization.Currency).Cents/100.0).ToString("N2") - }; } diff --git a/Site/Automation/Formatting.aspx.cs b/Site/Automation/Formatting.aspx.cs index eb7dac79..352f7db6 100644 --- a/Site/Automation/Formatting.aspx.cs +++ b/Site/Automation/Formatting.aspx.cs @@ -43,24 +43,19 @@ namespace Swarmops.Frontend.Automation [WebMethod] public static AjaxInputCallResult FormatCurrencyString(string input) { - double outParse = 0.0; bool success = false; + Int64 cents = 0; - if (Double.TryParse(input, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out outParse)) + try { - success = true; + cents = Swarmops.Logic.Support.Formatting.ParseDoubleStringAsCents(input); } - else if (Double.TryParse(input, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out outParse)) + catch (ArgumentException) { - success = true; + return new AjaxInputCallResult { Success = false }; } - if (!success) - { - return new AjaxInputCallResult {Success = false}; - } - - return new AjaxInputCallResult {Success = true, NewValue = outParse.ToString("N2")}; + return new AjaxInputCallResult {Success = true, NewValue = (cents / 100.0).ToString("N2")}; } } } \ No newline at end of file diff --git a/Site/Controls/v5/Financial/CurrencyTextBox.ascx.cs b/Site/Controls/v5/Financial/CurrencyTextBox.ascx.cs index 936b0772..29efc29b 100644 --- a/Site/Controls/v5/Financial/CurrencyTextBox.ascx.cs +++ b/Site/Controls/v5/Financial/CurrencyTextBox.ascx.cs @@ -3,6 +3,8 @@ using System.Globalization; using Swarmops.Common.Enums; using System.Web.UI; using Swarmops.Logic.Financial; +using Swarmops.Logic.Support; +using Swarmops.Logic.Support.Formatting; namespace Swarmops.Frontend.Controls.Financial { @@ -29,8 +31,10 @@ namespace Swarmops.Frontend.Controls.Financial public Int64 Cents { get - { - return (Int64) (InternalValue * 100.0 + 0.5); // the +0.5 is to compensate for floating point errors. And yes, THEY HAPPEN. + { + string contents = this.TextInput.Text; + return Formatting.ParseDoubleStringAsCents(contents); + } set { @@ -48,7 +52,8 @@ namespace Swarmops.Frontend.Controls.Financial { get { - return (Int64)(InternalValue * 10000.0 + 0.5); // the +0.5 is to compensate for floating point errors. And yes, THEY HAPPEN. + string contents = this.TextInput.Text; + return Formatting.ParseDoubleStringAsCents(contents, null, Formatting.ParsingScale.Metacents); } set { this.TextInput.Text = (value / 10000.0).ToString("N4", CultureInfo.CurrentCulture); } } @@ -59,31 +64,6 @@ namespace Swarmops.Frontend.Controls.Financial get { throw new NotImplementedException(); } } - internal double InternalValue - { - get - { - // Try to parse the Double in two steps: first as a Culture.CurrentCulture, and if that doesn't work out, as a Culture.InvariantCulture. - - double outParse = 0.0; - string contents = this.TextInput.Text; - - if (Double.TryParse (contents, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out outParse)) - { - return outParse; - } - if (Double.TryParse(contents, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out outParse)) - { - return outParse; - } - - // Unparsable. Sorry. - - throw new InvalidCastException("The text field cannot be parsed to a Double: \"" + contents + "\""); - - } - } - // TODO: Add other-currency parsing public LayoutDirection Layout { get; set; } @@ -102,7 +82,7 @@ namespace Swarmops.Frontend.Controls.Financial { get { - return new Money((long) (Double.Parse(this.EnteredAmount.Value, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture) * 100.0 + 0.5), Currency.FromCode(this.EnteredCurrency.Value)); + return new Money(Swarmops.Logic.Support.Formatting.ParseDoubleStringAsCents (this.EnteredAmount.Value), Currency.FromCode(this.EnteredCurrency.Value)); } } } diff --git a/Site/Pages/v5/Financial/AttestCosts.aspx.cs b/Site/Pages/v5/Financial/AttestCosts.aspx.cs index e68d07de..86a8b113 100644 --- a/Site/Pages/v5/Financial/AttestCosts.aspx.cs +++ b/Site/Pages/v5/Financial/AttestCosts.aspx.cs @@ -231,11 +231,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial public static AjaxCallResult AttestCorrectedItem(string recordId, string amountString) { AuthenticationData authData = GetAuthenticationDataAndCulture(); - double amount = 0.0; + Int64 amountCents = 0; try { - amount = Double.Parse (amountString, NumberStyles.Currency, Thread.CurrentThread.CurrentCulture); + amountCents = Formatting.ParseDoubleStringAsCents(amountString); } catch (Exception) { @@ -246,8 +246,6 @@ namespace Swarmops.Frontend.Pages.v5.Financial }; } - Int64 amountCents = (Int64) (amount*100); - if (amountCents < 0) { return new AjaxCallResult @@ -277,7 +275,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial Int64 centsRemaining = budget.GetBudgetCentsRemaining(); - if (centsRemaining/100.0 < amount) + if (centsRemaining < amountCents) { // TODO: Handle the special case where the IPayable is not on current year, so against another (last) year's budget diff --git a/Site/Pages/v5/Financial/ListInvoicesInbound.aspx.cs b/Site/Pages/v5/Financial/ListInvoicesInbound.aspx.cs index 94b3a658..7303a213 100644 --- a/Site/Pages/v5/Financial/ListInvoicesInbound.aspx.cs +++ b/Site/Pages/v5/Financial/ListInvoicesInbound.aspx.cs @@ -217,11 +217,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial public static AjaxCallResult AttestCorrectedItem(string recordId, string amountString) { AuthenticationData authData = GetAuthenticationDataAndCulture(); - double amount = 0.0; + Int64 amountCents = 0; try { - amount = Double.Parse (amountString, NumberStyles.Currency, Thread.CurrentThread.CurrentCulture); + amountCents = Formatting.ParseDoubleStringAsCents (amountString); } catch (Exception) { @@ -232,8 +232,6 @@ namespace Swarmops.Frontend.Pages.v5.Financial }; } - Int64 amountCents = (Int64) (amount*100); - if (amountCents < 0) { return new AjaxCallResult @@ -263,7 +261,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial Int64 centsRemaining = budget.GetBudgetCentsRemaining(); - if (centsRemaining/100.0 < amount) + if (centsRemaining < amountCents) { // TODO: Handle the special case where the IPayable is not on current year, so against another (last) year's budget diff --git a/Site/Pages/v5/Ledgers/AccountPlan.aspx.cs b/Site/Pages/v5/Ledgers/AccountPlan.aspx.cs index c9161bb8..912a775c 100644 --- a/Site/Pages/v5/Ledgers/AccountPlan.aspx.cs +++ b/Site/Pages/v5/Ledgers/AccountPlan.aspx.cs @@ -298,11 +298,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers }; } - Int64 desiredInitialBalanceCents = - (Int64) - (Double.Parse (newInitialBalanceString, - NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, - CultureInfo.CurrentCulture)*100.0); + Int64 desiredInitialBalanceCents = Formatting.ParseDoubleStringAsCents(newInitialBalanceString); Int64 currentInitialBalanceCents = account.GetDeltaCents (new DateTime (1900, 1, 1), new DateTime (authData.CurrentOrganization.FirstFiscalYear, 1, 1)); diff --git a/Site/Pages/v5/Ledgers/BalanceTransactions.aspx b/Site/Pages/v5/Ledgers/BalanceTransactions.aspx index 6fe87dbd..180279b2 100644 --- a/Site/Pages/v5/Ledgers/BalanceTransactions.aspx +++ b/Site/Pages/v5/Ledgers/BalanceTransactions.aspx @@ -211,11 +211,32 @@ alert("BudgetId: " + budgetId + "\r\nVAT amount: " + vatAmount + "\r\nDescription: " + txDescription); + if (budgetId > 0) { + SwarmopsJS.ajaxCall( + "/Pages/v5/Ledgers/BalanceTransactions.aspx/MarkDirectPurchase", + { + transactionId: transactionId, + budgetId: budgetId, + vatAmountString: vatAmount, + newDescription: txDescription + }, + function(result) { + if (result.Success) { + // close dialog, clear fields, reload + // Keep the budget selection + <%=this.UploadPurchase.ClientID%>_clear(); + <%=this.CurrencyPurchaseVat.ClientID%>_setValue(""); + + $('#gridTransactions').datagrid('reload'); + + } else { + alertify.error(result.DisplayMessage); + } + }); + } + // TODO HERE: AJAX CALL - <%=this.UploadPurchase.ClientID%>_clear(); - <%=this.CurrencyPurchaseVat.ClientID%>_val(""); - // Keep the budget selection } var buttonBalanceValue = SwarmopsJS.unescape('<%=this.Localized_ButtonBalance%>'); diff --git a/Site/Pages/v5/Ledgers/BalanceTransactions.aspx.cs b/Site/Pages/v5/Ledgers/BalanceTransactions.aspx.cs index 0ddf8f9b..a1ece2dc 100644 --- a/Site/Pages/v5/Ledgers/BalanceTransactions.aspx.cs +++ b/Site/Pages/v5/Ledgers/BalanceTransactions.aspx.cs @@ -6,6 +6,7 @@ using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; +using Newtonsoft.Json; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; @@ -520,6 +521,36 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers } + [WebMethod] + public static AjaxCallResult MarkDirectPurchase(int transactionId, int budgetId, string vatAmountString, + string newDescription) + { + if (transactionId == 0 | budgetId == 0) + { + return new AjaxCallResult {Success = false}; + } + + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + if ( + !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, + AccessAspect.BookkeepingDetails))) + { + throw new UnauthorizedAccessException(); + } + + Int64 vatCents = 0; + bool vatEnabled = authData.CurrentOrganization.VatEnabled; + + if (vatEnabled) + { + double vatDouble; + + + } + } + + [WebMethod] public static string GetTransactionDisplayIdentity(int transactionId) { diff --git a/Site/Pages/v5/Ledgers/InspectLedgers.aspx.cs b/Site/Pages/v5/Ledgers/InspectLedgers.aspx.cs index 990d538f..35c06dec 100644 --- a/Site/Pages/v5/Ledgers/InspectLedgers.aspx.cs +++ b/Site/Pages/v5/Ledgers/InspectLedgers.aspx.cs @@ -155,8 +155,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers FinancialAccount account = FinancialAccount.FromIdentity (accountId); - Double amountFloat = Double.Parse (amountString); - Int64 amountCents = (Int64) (amountFloat*100.0); + Int64 amountCents = Formatting.ParseDoubleStringAsCents(amountString); if (account.OrganizationId != authData.CurrentOrganization.Identity) { @@ -473,8 +472,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers throw new UnauthorizedAccessException(); } - double amount = Double.Parse(amountString); - Int64 amountCents = (Int64) (amount *100); + Int64 amountCents = Formatting.ParseDoubleStringAsCents(amountString); DateTime txTime = DateTime.Parse(dateTimeString);