Refactor: Centralize double-to-cents parsing in one place
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace Swarmops.Frontend.Automation
|
||||
|
||||
try
|
||||
{
|
||||
Double.Parse(amount, NumberStyles.Number);
|
||||
Swarmops.Logic.Support.Formatting.ParseDoubleStringAsCents(amount);
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
|
||||
@@ -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")
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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")};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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%>');
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user