diff --git a/Backend/Program.cs b/Backend/Program.cs index 59725aa5..bcdf3e87 100644 --- a/Backend/Program.cs +++ b/Backend/Program.cs @@ -526,6 +526,8 @@ namespace Swarmops.Backend RosterHousekeeping.ChurnExpiredMembers(); TestTrace(" done.\r\n");*/ } + + ExchangeRateSnapshot.Create(); } catch (Exception e) { diff --git a/Basic/Basic.csproj b/Basic/Basic.csproj index 96e78554..7c76b7f8 100644 --- a/Basic/Basic.csproj +++ b/Basic/Basic.csproj @@ -68,6 +68,7 @@ + diff --git a/Basic/Types/Financial/BasicExchangeRateSnapshot.cs b/Basic/Types/Financial/BasicExchangeRateSnapshot.cs new file mode 100644 index 00000000..a8e7ca38 --- /dev/null +++ b/Basic/Types/Financial/BasicExchangeRateSnapshot.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Swarmops.Basic.Interfaces; + +namespace Swarmops.Basic.Types.Financial +{ + [Serializable] + public class BasicExchangeRateSnapshot: IHasIdentity + { + [Obsolete("Do not call the default constructor directly. It is reserved for serialization.", true)] + public BasicExchangeRateSnapshot() + { + // do not call + } + + public BasicExchangeRateSnapshot (int identity, DateTime dateTime) + { + this.ExchangeRateSnapshotId = identity; + this.DateTime = dateTime; + } + + public BasicExchangeRateSnapshot (BasicExchangeRateSnapshot original) : + this (original.Identity, original.DateTime) + { + // empty copy ctor + } + + public int ExchangeRateSnapshotId { get; private set; } + public DateTime DateTime { get; private set; } + public List Datapoints { get; protected set; } + + public int Identity { get { return ExchangeRateSnapshotId; }} + } + + [Serializable] + public class BasicExchangeRateSnapshotDatapoint + { + public string CurrencyCodeA { get; set; } + public string CurrencyCodeB { get; set; } + public double APerB { get; set; } + } +} diff --git a/Database/Configuration.cs b/Database/Configuration.cs index 820ce141..0b3eed30 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -14,7 +14,7 @@ namespace Swarmops.Database /// public static int DbVersionExpected { - get { return 8; } + get { return 10; } } diff --git a/Database/Database-Currencies.cs b/Database/Database-Currencies.cs index e887f937..875a35fe 100644 --- a/Database/Database-Currencies.cs +++ b/Database/Database-Currencies.cs @@ -121,26 +121,6 @@ namespace Swarmops.Database } } - - public int SetCurrencyExchangeRate (DateTime date, int currencyId, double eur100) - { - DateTime now = DateTime.Now; - - using (DbConnection connection = GetMySqlDbConnection()) - { - connection.Open(); - - DbCommand command = GetDbCommand ("SetCurrencyExchangeRate", connection); - command.CommandType = CommandType.StoredProcedure; - - AddParameterWithName (command, "currencyId", currencyId); - AddParameterWithName (command, "date", date.Date); - AddParameterWithName (command, "eur100", eur100); - - return Convert.ToInt32 (command.ExecuteScalar()); - } - } - /* public void SetSalaryNetPaid(int salaryId, bool netPaid) diff --git a/Database/Database-ExchangeRates.cs b/Database/Database-ExchangeRates.cs new file mode 100644 index 00000000..7a598fca --- /dev/null +++ b/Database/Database-ExchangeRates.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using Swarmops.Basic.Types; + +namespace Swarmops.Database +{ + public partial class SwarmDb + { + #region Field reading code + + private const string exchangeRateSnapshotFieldSequence = + " CurrencyId,Code,Name,Sign " + // 0-3 + "FROM Currencies "; + + private const string exchangeRateDatapointSequence = + " ..."; + + /* + private static BasicCurrency ReadCurrencyFromDataReader(IDataRecord reader) + { + int currencyId = reader.GetInt32(0); + string code = reader.GetString(1); + string name = reader.GetString(2); + string sign = reader.GetString(3); + + return new BasicCurrency(currencyId, code, name, sign); + }*/ + + #endregion + + #region Record reading - SELECT statements + /* + public BasicCurrency GetCurrency(int currencyId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT" + currencyFieldSequence + "WHERE CurrencyId=" + currencyId + ";", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return ReadCurrencyFromDataReader(reader); + } + + throw new ArgumentException("Unknown Currency Id: " + currencyId); + } + } + } + + public BasicCurrency GetCurrency(string currencyCode) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT" + currencyFieldSequence + "WHERE Code='" + + currencyCode.Replace("'", "''").ToUpperInvariant() + "';", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return ReadCurrencyFromDataReader(reader); + } + + throw new ArgumentException("Unknown Currency Code: " + currencyCode); + } + } + } + + + public BasicCurrency[] GetCurrencies(params object[] conditions) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT" + currencyFieldSequence + ConstructWhereClause("Currencies", conditions), connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadCurrencyFromDataReader(reader)); + } + + return result.ToArray(); + } + } + }*/ + + #endregion + + #region Creation and manipulation - stored procedures + + public int CreateExchangeRateSnapshot() + { + DateTime now = DateTime.UtcNow; + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("CreateExchangeRateSnapshot", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "dateTimeUtc", now); + + return Convert.ToInt32(command.ExecuteScalar()); + } + } + + + public int CreateExchangeRateDatapoint (int exchangeRateSnapshotId, int currencyAId, int currencyBId, double aPerB) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("CreateExchangeRateDatapoint", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName (command, "exchangeRateSnapshotId", exchangeRateSnapshotId); + AddParameterWithName (command, "currencyAId", currencyAId); + AddParameterWithName (command, "currencyBId", currencyBId); + AddParameterWithName (command, "aPerB", aPerB); + + return Convert.ToInt32(command.ExecuteScalar()); + } + } + + /* + + public void SetSalaryNetPaid(int salaryId, bool netPaid) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetSalaryNetPaid", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "salaryId", salaryId); + AddParameterWithName(command, "netPaid", netPaid); + + command.ExecuteNonQuery(); + + // "Open" is set in the stored procedure to "NOT (TaxPaid AND NetPaid)". + // So if both are paid, Open is set to false. + } + } + + + public void SetSalaryNetSalary(int salaryId, double netSalary) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetSalaryNetSalary", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "salaryId", salaryId); + AddParameterWithName(command, "netSalary", netSalary); + + command.ExecuteNonQuery(); + + // "Open" is set in the stored procedure to "NOT (TaxPaid AND NetPaid)". + // So if both are paid, Open is set to false. + } + } + + + public void SetSalaryTaxPaid(int salaryId, bool taxPaid) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetSalaryTaxPaid", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "salaryId", salaryId); + AddParameterWithName(command, "taxPaid", taxPaid); + + command.ExecuteNonQuery(); + + // "Open" is set in the stored procedure to "NOT (TaxPaid AND NetPaid)". + // So if both are paid, Open is set to false. + } + } + + + public void SetSalaryAttested(int salaryId, bool attested) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetSalaryAttested", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "salaryId", salaryId); + AddParameterWithName(command, "attested", attested); + + command.ExecuteNonQuery(); + } + } + */ + + #endregion + } +} \ No newline at end of file diff --git a/Database/Database.csproj b/Database/Database.csproj index 577ba67d..818c1778 100644 --- a/Database/Database.csproj +++ b/Database/Database.csproj @@ -58,6 +58,7 @@ + diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index b0a3ef81..c25f00d5 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -1,4 +1,4 @@ -0001 - Initial baseline. [Rick Falkvinge] +0001 - Initial baseline, in 'initialize.sql' [Rick Falkvinge] 0002 - Added functions for account plan maintenance and back/forward links to FinancialAccounts. [Rick Falkvinge] 0003 - Added 'Year' field for salary tax data. [Rick Falkvinge] 0004 - Added BankProfile tables and stored procs to insert/update. [Rick Falkvinge] @@ -6,3 +6,5 @@ 0006 - Added Memberships.LocalNumber and .FamilyNumber; added CurrencyExchangeRate tables/procs. [Rick Falkvinge] 0007 - NL update; added Lat/Long to PostalCodes and to People, indexed [RF] 0008 - GeographyUpdate updates ahead of deploying: added country, Guid [RF] +0009 - Fixed SalaryTaxLevels and CreateExchangeRateDataPoint [RF] +0010 - Fix for CurrencyExchangeRateSnapshotData [RF] \ No newline at end of file diff --git a/Database/Schemata/upgrade-0009.sql b/Database/Schemata/upgrade-0009.sql new file mode 100644 index 00000000..8dd3c022 --- /dev/null +++ b/Database/Schemata/upgrade-0009.sql @@ -0,0 +1,26 @@ +ALTER TABLE `SalaryTaxLevels` +DROP PRIMARY KEY, +ADD PRIMARY KEY (`TaxLevelId`, `BracketLow`, `CountryId`, `Year`) + + +# + + +DROP PROCEDURE `InsertExchangeRateSnapshotData` + + +# + + +CREATE PROCEDURE `CreateExchangeRateDatapoint`( + IN exchangeRateSnapshotId INTEGER, + IN currencyAId INTEGER, + IN currencyBId INTEGER, + IN aPerB DOUBLE +) +BEGIN + + INSERT INTO CurrencyExchangeRateSnapshotData (CurrencyExchangeRateSnapshotId,CurrencyAId,CurrencyBId,APerB) + VALUES (exchangeRateSnapshotId,currencyAId,currencyBId,aPerB); + +END \ No newline at end of file diff --git a/Database/Schemata/upgrade-0010.sql b/Database/Schemata/upgrade-0010.sql new file mode 100644 index 00000000..5af4d909 --- /dev/null +++ b/Database/Schemata/upgrade-0010.sql @@ -0,0 +1,6 @@ +ALTER TABLE `CurrencyExchangeRateSnapshotData` +DROP PRIMARY KEY, +ADD PRIMARY KEY (`CurrencyExchangeRateSnapshotId`, `CurrencyBId`, `CurrencyAId`), +ADD INDEX `Index_SnapshotId` (`CurrencyExchangeRateSnapshotId` ASC), +ADD INDEX `Index_CurrencyA` (`CurrencyAId` ASC), +ADD INDEX `Index_CurrencyB` (`CurrencyBId` ASC) diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs new file mode 100644 index 00000000..36c48ba3 --- /dev/null +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web.Script.Serialization; +using System.Xml.Serialization; +using Swarmops.Basic.Types.Financial; +using Swarmops.Database; +using Swarmops.Logic.Support; + +namespace Swarmops.Logic.Financial +{ + [Serializable] + public class ExchangeRateSnapshot: BasicExchangeRateSnapshot + { + [Obsolete ("Do not call this ctor directly. Intended for serialization only.", true)] + public ExchangeRateSnapshot() + { + // do not call + } + + private ExchangeRateSnapshot (BasicExchangeRateSnapshot basic) + : base (basic) + { + // private ctor + + // TODO: Verify that data is in, or load it + } + + public static ExchangeRateSnapshot FromBasic (BasicExchangeRateSnapshot basic) + { + return new ExchangeRateSnapshot (basic); + } + + + public static void Create() + { + using(WebClient client = new WebClient()) + { + SupportFunctions.DisableSslCertificateChecks(); // MONO BUG/MISFEATURE: Mono has no root certificates, so can't verify cert + + client.Encoding = Encoding.UTF8; + string rateDataRaw = client.DownloadString("https://bitpay.com/api/rates"); + + // BitPay doesn't provide valid JSON - the rate field isn't enclosed in quotes - so we can't use JSON Deserialization; we'll + // have to use Regex matching instead. + + string regexPattern = @"\{\""code\"":\""([A-Z]+)\"",\""name\"":\""([^\""]+)\"",\""rate\"":([0-9\.]+)\}"; + Regex regex = new Regex (regexPattern); + Match match = regex.Match (rateDataRaw); + + int exchangeRateSnapshotId = 0; + int bitcoinId = GetOrCreateCurrency ("BTC", "Bitcoin"); + + if (match.Success) + { + // We have at least one match, so prepare a new ExchangeRate snapshot + + exchangeRateSnapshotId = SwarmDb.GetDatabaseForWriting().CreateExchangeRateSnapshot(); + } + + while (match.Success) + { + string currencyCode = match.Groups[1].Value; + string currencyName = match.Groups[2].Value; + double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture); + + btcRate /= 1000000.0; // We're operating in microbitcoin, so adjust the stored exchange rate accordingly (right-shift six decimal places) + + int currencyId = GetOrCreateCurrency (currencyCode, currencyName); + + SwarmDb.GetDatabaseForWriting() + .CreateExchangeRateDatapoint (exchangeRateSnapshotId, currencyId, bitcoinId, btcRate); + + match = match.NextMatch(); + } + + JavaScriptSerializer serializer = new JavaScriptSerializer(); + BitpayRateDatapoint[] rates = (BitpayRateDatapoint[]) serializer.Deserialize (rateDataRaw); + } + } + + private static int GetOrCreateCurrency (string currencyCode, string currencyName) + { + try + { + return Currency.FromCode (currencyCode).Identity; + } + catch (ArgumentException) + { + return Currency.Create (currencyCode, currencyName, string.Empty).Identity; + } + } + + } + + [Serializable] + public class BitpayRateDatapoint + { + string code { get; set; } + string name { get; set; } + string rate { get; set; } + } +} diff --git a/Logic/Financial/ExchangeRateSnapshots.cs b/Logic/Financial/ExchangeRateSnapshots.cs new file mode 100644 index 00000000..5d5f4b24 --- /dev/null +++ b/Logic/Financial/ExchangeRateSnapshots.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Basic.Types.Financial; +using Swarmops.Logic.Support; + +namespace Swarmops.Logic.Financial +{ + public class ExchangeRateSnapshots: PluralBase + { + // the templated base takes care of most stuff + } +} diff --git a/Logic/Financial/FinancialAccountRows.cs b/Logic/Financial/FinancialAccountRows.cs index ba7708a2..3bb14f80 100644 --- a/Logic/Financial/FinancialAccountRows.cs +++ b/Logic/Financial/FinancialAccountRows.cs @@ -1,5 +1,8 @@ +using System; using System.Collections.Generic; using Swarmops.Basic.Types.Financial; +using Swarmops.Database; +using Swarmops.Logic.Structure; namespace Swarmops.Logic.Financial { @@ -16,5 +19,15 @@ namespace Swarmops.Logic.Financial return result; } + + public static FinancialAccountRows ForOrganization(Organization organization, DateTime fromDate, + DateTime toDate) + { + FinancialAccounts orgAccounts = FinancialAccounts.ForOrganization (organization); + orgAccounts.GetRows (fromDate, toDate); + return + FromArray (SwarmDb.GetDatabaseForReading() + .GetFinancialAccountRows (orgAccounts.Identities, fromDate, toDate, false)); + } } } \ No newline at end of file diff --git a/Logic/Financial/FinancialTransaction.cs b/Logic/Financial/FinancialTransaction.cs index 61eaeb08..5ab255ea 100644 --- a/Logic/Financial/FinancialTransaction.cs +++ b/Logic/Financial/FinancialTransaction.cs @@ -327,11 +327,26 @@ namespace Swarmops.Logic.Financial } + public Dictionary GetRecalculationBase() + { + Dictionary currentTransaction = new Dictionary(); + + foreach (FinancialTransactionRow row in Rows) + { + if (!currentTransaction.ContainsKey(row.FinancialAccountId)) + { + currentTransaction[row.FinancialAccountId] = 0; + } + + currentTransaction[row.FinancialAccountId] += row.AmountCents; + } + + return currentTransaction; + } + + public bool RecalculateTransaction (Dictionary nominalTransaction, Person loggingPerson) { - // TODO: Update dimension 2 with dimension 1 P&L accounts as template - - bool changedTransaction = false; // We need to create a delta. This is... somewhat complicated. @@ -340,17 +355,7 @@ namespace Swarmops.Logic.Financial // 2) Create a "should-look-like" transaction record. (done in calling routine, already). // 3) Apply the delta, in two steps. - Dictionary currentTransaction = new Dictionary(); - - foreach (FinancialTransactionRow row in Rows) - { - if (!currentTransaction.ContainsKey (row.FinancialAccountId)) - { - currentTransaction[row.FinancialAccountId] = 0; - } - - currentTransaction[row.FinancialAccountId] += row.AmountCents; - } + Dictionary currentTransaction = GetRecalculationBase(); FinancialTransaction continuedTransaction = ContinuedTransaction; @@ -395,9 +400,6 @@ namespace Swarmops.Logic.Financial } } - // TODO: Dimension 2 - - return changedTransaction; } diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index 3ec05bf3..038a2df7 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -67,6 +67,7 @@ + @@ -119,6 +120,8 @@ + + @@ -249,6 +252,7 @@ + diff --git a/Logic/Support/General.cs b/Logic/Support/General.cs new file mode 100644 index 00000000..4be36ddd --- /dev/null +++ b/Logic/Support/General.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace Swarmops.Logic.Support +{ + public class SupportFunctions + { + public static void DisableSslCertificateChecks() + { + // X.509 is SO SO SO broken. The reason we do this, btw, is that mono doesn't come with root certs. At all. + + // This disables certificate checking completely and accepts ALL certificates. + + System.Net.ServicePointManager.ServerCertificateValidationCallback += + (sender, certificate, chain, sslPolicyErrors) => true; + } + } +} diff --git a/Site5/App_GlobalResources/Pages.Ledgers.resx b/Site5/App_GlobalResources/Pages.Ledgers.resx index 8d1f09e1..b84176fc 100644 --- a/Site5/App_GlobalResources/Pages.Ledgers.resx +++ b/Site5/App_GlobalResources/Pages.Ledgers.resx @@ -400,6 +400,7 @@ Amount + keep short Description @@ -469,14 +470,10 @@ Daily Operations - - Initial Value - For asset and liability accounts - the value going into Swarmops first ledger year - Parent account or group - + This is an Expenses account. Such accounts normally have a budget in the negative, since they drain assets from the organization. Your proposed budget was changed to negative. Displayed as a message box @@ -558,4 +555,11 @@ New Account the name of newly-created accounts, before rename + + This is a Liabilities account. Such accounts normally have a balance in the negative, since they represent negative assets in the organization. Your entered initial balance was changed to negative. + + + Initial Balance (inbound into {0}), {1} + {0} is the first ledger year in Swarmops. {1} is the currency code. + \ No newline at end of file diff --git a/Site5/Automation/GetFinancialData.asmx b/Site5/Automation/GetFinancialData.asmx new file mode 100644 index 00000000..4e4e445d --- /dev/null +++ b/Site5/Automation/GetFinancialData.asmx @@ -0,0 +1,44 @@ +<%@ WebService Language="C#" Class="GetFinancialData" %> + +using System; +using System.Web; +using System.Web.Services; +using System.Web.Services.Protocols; +using Swarmops.Logic.Financial; + +[WebService(Namespace = "http://swarmops.com/")] +[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] +// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. +// [System.Web.Script.Services.ScriptService] +public class GetFinancialData : System.Web.Services.WebService { + + /* + [WebMethod] + public ExchangeRateSnapshots GetExhangeRateDataSince(DateTime dateTimeSince) + { + return ExchangeRateSnapshots.GetSince (dateTimeSince); + } + + [WebMethod] + public double GetExchangeRate (string currencyCodeA, string currencyCodeB) + { + return ExchangeRateSnapshot.Latest.GetExchangeRate (currencyCodeA, currencyCodeB); + } + + [WebMethod] + public double GetExchangeRate (string currencyCodeA, string currencyCodeB, DateTime onDate) + { + return ExchangeRateSnapshot.FromDate (onDate).GetExchangeRate (currencyCodeA, currencyCodeB); + }*/ + + [WebMethod] + public Currency GetCurrency (string currencyCode) + { + return Currency.FromCode (currencyCode); + } + + public Currencies GetCurrencies() + { + return Currencies.GetAll(); + } +} \ No newline at end of file diff --git a/Site5/Automation/GetGeographyData.asmx b/Site5/Automation/GetGeographyData.asmx index 938aed00..f08466b8 100644 --- a/Site5/Automation/GetGeographyData.asmx +++ b/Site5/Automation/GetGeographyData.asmx @@ -1,5 +1,6 @@ <%@ WebService Language="C#" Class="GetGeographyData" %> +using System; using System.Web.Services; using Swarmops.Logic.Structure; @@ -44,4 +45,16 @@ public class GetGeographyData : System.Web.Services.WebService { return Country.FromCode(countryCode).Geography; } + + [WebMethod] + public GeographyUpdates GetGeographyUpdatesSince (DateTime dateTime) + { + return GeographyUpdates.GetCreatedSince (dateTime); + } + + [WebMethod] + public GeographyUpdates GetGeographyUpdates() + { + return GeographyUpdates.GetCreatedSince (new DateTime (1900, 1, 1)); + } } \ No newline at end of file diff --git a/Site5/Automation/Json-FinancialAccountsTree.aspx.cs b/Site5/Automation/Json-FinancialAccountsTree.aspx.cs index d955dc19..cc74a6b7 100644 --- a/Site5/Automation/Json-FinancialAccountsTree.aspx.cs +++ b/Site5/Automation/Json-FinancialAccountsTree.aspx.cs @@ -55,28 +55,28 @@ namespace Swarmops.Frontend.Automation if (accountType == FinancialAccountType.Asset || accountType == FinancialAccountType.Balance || accountType == FinancialAccountType.All) { - response += GetAccountGroup (FinancialAccountType.Asset, Ledgers.BalanceSheet_Assets) + + response += GetAccountGroup (FinancialAccountType.Asset, Resources.Global.Financial_Asset) + ","; } if (accountType == FinancialAccountType.Debt || accountType == FinancialAccountType.Balance || accountType == FinancialAccountType.All) { - response += GetAccountGroup (FinancialAccountType.Debt, Ledgers.BalanceSheet_Debt) + ","; + response += GetAccountGroup (FinancialAccountType.Debt, Resources.Global.Financial_Debt) + ","; } if (accountType == FinancialAccountType.Income || accountType == FinancialAccountType.Result || accountType == FinancialAccountType.All) { response += - GetAccountGroup (FinancialAccountType.Income, Ledgers.ProfitLossStatement_Income) + + GetAccountGroup(FinancialAccountType.Income, Resources.Global.Financial_Income) + ","; } if (accountType == FinancialAccountType.Cost || accountType == FinancialAccountType.Result || accountType == FinancialAccountType.All) { - response += GetAccountGroup (FinancialAccountType.Cost, Ledgers.ProfitLossStatement_Costs); + response += GetAccountGroup(FinancialAccountType.Cost, Resources.Global.Financial_Cost); } response = response.TrimEnd (','); diff --git a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx index 87e23c61..8e5b0585 100644 --- a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx +++ b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx @@ -1 +1,5 @@ <%@ Control Language="C#" AutoEventWireup="true" CodeFile="CurrencyTextBox.ascx.cs" Inherits="Swarmops.Frontend.Controls.v5.Financial.CurrencyTextBox" %> + + + + \ No newline at end of file diff --git a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs index 65ac1e09..c9d88ac7 100644 --- a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs +++ b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Web.UI; namespace Swarmops.Frontend.Controls.v5.Financial @@ -12,5 +13,33 @@ namespace Swarmops.Frontend.Controls.v5.Financial protected void Page_Load (object sender, EventArgs e) { } + + public double Value + { + 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 = Input.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 + "\""); + + } + set { this.Input.Text = value.ToString ("N2", CultureInfo.CurrentCulture); } + } + + // TODO: Add other-currency parsing } } \ No newline at end of file diff --git a/Site5/Default.aspx.cs b/Site5/Default.aspx.cs index 18921d9d..726975d1 100644 --- a/Site5/Default.aspx.cs +++ b/Site5/Default.aspx.cs @@ -1,5 +1,6 @@ using System; using Resources; +using Swarmops.Logic.Financial; public partial class Default : PageV5Base { diff --git a/Site5/Pages/v5/Financial/CreateInboundInvoice.aspx.cs b/Site5/Pages/v5/Financial/CreateInboundInvoice.aspx.cs index 2c10e459..dcaf0a67 100644 --- a/Site5/Pages/v5/Financial/CreateInboundInvoice.aspx.cs +++ b/Site5/Pages/v5/Financial/CreateInboundInvoice.aspx.cs @@ -139,7 +139,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial double amount = Double.Parse (this.TextAmount.Text, NumberStyles.Number); // parses in current culture - intentional - Int64 amountCents = (Int64) amount*100; + Int64 amountCents = (Int64) (amount*100); string description = this.TextPurpose.Text; diff --git a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs index bb2527f4..c377d7b0 100644 --- a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs +++ b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs @@ -146,7 +146,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial double amount = Double.Parse (this.TextAmount.Text, NumberStyles.Number); // parses in current culture - intentional - Int64 amountCents = (Int64) amount*100; + Int64 amountCents = (Int64) (amount*100.0); string description = this.TextPurpose.Text; diff --git a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx index e9d14c1e..84edabd4 100644 --- a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx +++ b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx @@ -1,5 +1,6 @@ <%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="RequestCashAdvance.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.RequestCashAdvance" %> <%@ Register TagPrefix="Swarmops5" TagName="ComboBudgets" Src="~/Controls/v5/Financial/ComboBudgets.ascx" %> +<%@ Register TagPrefix="Swarmops5" TagName="CurrencyTextBox" Src="~/Controls/v5/Financial/CurrencyTextBox.ascx" %> @@ -20,7 +21,7 @@ isValid = validateTextField('#<%=this.TextPurpose.ClientID %>', "") && isValid; var jsonData = {}; - jsonData.amount = $('#<%=this.TextAmount.ClientID %>').val(); + jsonData.amount = $('#<%=this.TextAmount.ClientID %>_Input').val(); $.ajax({ type: "POST", @@ -33,7 +34,7 @@ if (msg.d != true) { isValid = false; alertify.error(""); - $('#<%=this.TextAmount.ClientID %>').addClass("entryError").focus(); + $('#<%=this.TextAmount.ClientID %>_Input').addClass("entryError").focus(); } } }); @@ -59,7 +60,7 @@

- ​
+ ​
​
 
 
diff --git a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs index 7165d0e4..f1890847 100644 --- a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs +++ b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs @@ -26,7 +26,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial this.TextBank.Text = CurrentUser.BankName; this.TextClearing.Text = CurrentUser.BankClearing; this.TextAccount.Text = CurrentUser.BankAccount; - this.TextAmount.Text = 0.ToString ("N2"); + this.TextAmount.Value = 0.0; this.TextAmount.Focus(); Localize(); @@ -62,9 +62,8 @@ namespace Swarmops.Frontend.Pages.v5.Financial { // The data has been validated client-side already. We'll throw unfriendly exceptions if invalid data is passed here. - double amount = Double.Parse (this.TextAmount.Text, NumberStyles.Number); - // parses in current culture - intentional - Int64 amountCents = (Int64) amount*100; + double amount = this.TextAmount.Value; + Int64 amountCents = (Int64) (amount*100.0); string description = this.TextPurpose.Text; diff --git a/Site5/Pages/v5/Ledgers/AccountPlan.aspx b/Site5/Pages/v5/Ledgers/AccountPlan.aspx index 6d4634f9..63f52257 100644 --- a/Site5/Pages/v5/Ledgers/AccountPlan.aspx +++ b/Site5/Pages/v5/Ledgers/AccountPlan.aspx @@ -1,6 +1,8 @@ <%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="AccountPlan.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Ledgers.AccountPlan" %> +<%@ Import Namespace="Swarmops.Logic.Financial" %> <%@ Register TagPrefix="Swarmops5" TagName="ComboBudgets" Src="~/Controls/v5/Financial/ComboBudgets.ascx" %> <%@ Register TagPrefix="Swarmops5" TagName="ComboPeople" Src="~/Controls/v5/Swarm/ComboPeople.ascx" %> +<%@ Register TagPrefix="Swarmops5" TagName="TextCurrency" Src="~/Controls/v5/Financial/CurrencyTextBox.ascx" %> @@ -147,6 +149,51 @@ }); }); + $('#<%=CurrencyInitialBalance.ClientID%>_Input').blur(function() { + var newAccountInitialBalance = $(this).val(); + + if (modalAccountInitialBalance == newAccountInitialBalance) { + return; // nothing changed, nothing to do + } + + if (accountType == 'D' && newAccountInitialBalance[0] != '-') { + alertify.alert(''); + newAccountInitialBalance = "-" + newAccountInitialBalance; + } + + var jsonData = {}; + jsonData.accountId = accountId; + jsonData.newInitialBalanceString = newAccountInitialBalance; + + $(this).css('background-color', '#FFFFE0'); + $.ajax({ + type: "POST", + url: "AccountPlan.aspx/SetAccountInitialBalance", + data: $.toJSON(jsonData), + contentType: "application/json; charset=utf-8", + dataType: "json", + success: $.proxy(function(msg) { + if (msg.d.Result == 3 || msg.d.Result == 4) { // Invalid or NoPermission + $(this).css('background-color', '#FFA0A0'); + alertify.error("There was an error attempting to set your initial balance."); // TODO: Localize + } else { // msg.d.Result should be Changed here + $(this).css('background-color', '#E0FFE0'); + modalAccountInitialBalance = msg.d.NewData; + accountDirty = true; + } + $(this).val(modalAccountInitialBalance); + $(this).animate({ backgroundColor: "#FFFFFF" }, 250); + }, this), + error: $.proxy(function(msg) { + alertify.error("There was an error calling the server to set your initial balance. Is the server reachable?"); // TODO: Localize + $(this).val(modalAccountInitialBalance); + $(this).css('background-color', '#FFA0A0'); + $(this).animate({ backgroundColor: "#FFFFFF" }, 250); + }, this) + }); + }); + + }); @@ -176,6 +223,14 @@ accountTreeLoaded = false; accountTree.combotree('setText', ''); + if ((accountType == 'A' || accountType == 'D') && firstFiscalYear > ledgersClosedUntil) { + $('#DivEditInitLabels').show(); + $('#DivEditInitControls').show(); + } else { + $('#DivEditInitLabels').hide(); + $('#DivEditInitControls').hide(); + } + if (accountType == 'A') { $('#DivEditAssetLabels').show(); $('#DivEditAssetControls').show(); @@ -207,6 +262,7 @@ $('span#<%= DropOwner.ClientID %>_SpanPeople span input.combo-text').css('background-color', '#DDD'); $('#TextAccountBudget').val('...').css('background-color', '#DDD'); $('#TextAccountName').val('...').css('background-color', '#DDD'); + $('#<%=CurrencyInitialBalance.ClientID%>_Input').val('...').css('background-color', '#DDD'); $('span#<%= DropOwner.ClientID %>_SpanPeople span input.combo-text').attr('placeholder', '...'); accountTree.combotree('setText', '...'); @@ -327,6 +383,9 @@ modalAccountBudget = msg.d.Budget; $('#TextAccountBudget').val(msg.d.Budget).css('background-color', '#FFF'); + modalAccountInitialBalance = msg.d.InitialBalance; + $('#<%=CurrencyInitialBalance.ClientID%>_Input').val(msg.d.InitialBalance).css('background-color', '#FFF'); + $('#SpanTextCurrency').text(msg.d.CurrencyCode); $('#SpanEditBalance').text(msg.d.Balance); parentAccountName = msg.d.ParentAccountName; @@ -432,10 +491,13 @@ } - var currentYear = <%=DateTime.Today.Year %>; + var currentYear = <%=DateTime.Today.Year %>; + var firstFiscalYear = <%=CurrentOrganization.FirstFiscalYear %>; + var ledgersClosedUntil = <%=CurrentOrganization.Parameters.FiscalBooksClosedUntilYear %>; var modalAccountName = ""; var modalAccountBudget = ""; + var modalAccountInitialBalance = ""; var accountId = 0; var accountType = ''; var accountDirty = false; @@ -492,16 +554,20 @@

 
 
-  
-
 
+
 
+  
 
 


 
-
-  
+
 
+
+  
+ +  
+
+


Upload parameter, if any
diff --git a/Site5/Pages/v5/Ledgers/AccountPlan.aspx.cs b/Site5/Pages/v5/Ledgers/AccountPlan.aspx.cs index 7e8196bc..b71a7128 100644 --- a/Site5/Pages/v5/Ledgers/AccountPlan.aspx.cs +++ b/Site5/Pages/v5/Ledgers/AccountPlan.aspx.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Globalization; using System.Web; using System.Web.Services; @@ -7,6 +8,7 @@ using Swarmops.Basic.Enums; using Swarmops.Database; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; +using Swarmops.Logic.Structure; using Swarmops.Logic.Swarm; namespace Swarmops.Frontend.Pages.v5.Ledgers @@ -56,7 +58,9 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers this.BoxTitle.Text = PageTitle = Resources.Pages.Ledgers.AccountPlan_PageTitle; InfoBoxLiteral = Resources.Pages.Ledgers.AccountPlan_Info; this.LiteralExpensesBudgetsAreNegative.Text = - Resources.Pages.Ledgers.AccountPlan_ExpensesBudgetsAreNegaive; + Resources.Pages.Ledgers.AccountPlan_ExpensesBudgetsAreNegative; + this.LiteralDebtBalancesAreNegative.Text = + Resources.Pages.Ledgers.AccountPlan_DebtBalancesAreNegative; this.LiteralHeaderAccountName.Text = Resources.Pages.Ledgers.AccountPlan_Header_AccountName; this.LiteralHeaderBalance.Text = Resources.Pages.Ledgers.AccountPlan_Header_Balance; this.LiteralHeaderBudget.Text = Resources.Pages.Ledgers.AccountPlan_Header_Budget; @@ -79,6 +83,10 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers Resources.Pages.Ledgers.AccountPlan_Edit_HeaderDailyOperations; this.LiteralLabelOwner.Text = Global.Global_Owner; this.LiteralLabelParent.Text = Resources.Pages.Ledgers.AccountPlan_Edit_Parent; + + this.LiteralLabelInitialAmount.Text = + String.Format (Resources.Pages.Ledgers.AccountPlan_Edit_InitialBalance, + CurrentOrganization.FirstFiscalYear, CurrentOrganization.Currency.DisplayCode); } PageAccessRequired = new Access (CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write); DbVersionRequired = 2; // Account reparenting @@ -127,6 +135,9 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers (accountTree.GetDeltaCents (new DateTime (1900, 1, 1), new DateTime (year + 1, 1, 1))/100L).ToString ( "N0"); + result.InitialBalance = + (accountTree.GetDeltaCents (new DateTime (1900, 1, 1), + new DateTime (authData.CurrentOrganization.FirstFiscalYear, 1, 1)).ToString ("N2")); } else { @@ -134,6 +145,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers (-accountTree.GetDeltaCents (new DateTime (year, 1, 1), new DateTime (year + 1, 1, 1))/100L) .ToString ( "N0"); + result.InitialBalance = "N/A"; // unused } result.CurrencyCode = account.Organization.Currency.DisplayCode; @@ -255,6 +267,87 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers return true; } + [WebMethod] + public static ChangeAccountDataResult SetAccountInitialBalance (int accountId, string newInitialBalanceString) + { + try + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + FinancialAccount account = FinancialAccount.FromIdentity (accountId); + + if (!PrepareAccountChange (account, authData, false) || authData.CurrentOrganization.Parameters.FiscalBooksClosedUntilYear >= authData.CurrentOrganization.FirstFiscalYear) + { + return new ChangeAccountDataResult + { + Result = ChangeAccountDataOperationsResult.NoPermission + }; + } + + Int64 desiredInitialBalanceCents = + (Int64) + (Double.Parse (newInitialBalanceString, + NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, + CultureInfo.CurrentCulture)*100.0); + + Int64 currentInitialBalanceCents = account.GetDeltaCents (new DateTime (1900, 1, 1), + new DateTime (authData.CurrentOrganization.FirstFiscalYear, 1, 1)); + + Int64 deltaCents = desiredInitialBalanceCents - currentInitialBalanceCents; + + // Find or create "Initial Balances" transaction + + FinancialAccountRows testRows = FinancialAccountRows.ForOrganization (authData.CurrentOrganization, + new DateTime (1900, 1, 1), new DateTime (authData.CurrentOrganization.FirstFiscalYear, 1, 1)); + + FinancialTransaction initialBalancesTransaction = null; + + foreach (FinancialAccountRow row in testRows) + { + if (row.Transaction.Description == "Initial Balances") + { + initialBalancesTransaction = row.Transaction; + break; + } + } + + if (initialBalancesTransaction == null) + { + // create transaction + + initialBalancesTransaction = FinancialTransaction.Create (authData.CurrentOrganization.Identity, + new DateTime (authData.CurrentOrganization.FirstFiscalYear - 1, 12, 31), "Initial Balances"); + } + + Dictionary recalcBase = initialBalancesTransaction.GetRecalculationBase(); + int equityAccountId = authData.CurrentOrganization.FinancialAccounts.DebtsEquity.Identity; + + if (!recalcBase.ContainsKey (accountId)) + { + recalcBase[accountId] = 0; + } + if (!recalcBase.ContainsKey (equityAccountId)) + { + recalcBase[equityAccountId] = 0; + } + + recalcBase[accountId] += deltaCents; + recalcBase[equityAccountId] -= deltaCents; + initialBalancesTransaction.RecalculateTransaction (recalcBase, authData.CurrentUser); + return new ChangeAccountDataResult + { + Result = ChangeAccountDataOperationsResult.Changed, + NewData = (desiredInitialBalanceCents / 100.0).ToString("N2", CultureInfo.CurrentCulture) + }; + } + catch (Exception weirdException) + { + SwarmDb.GetDatabaseForWriting() + .CreateExceptionLogEntry(DateTime.UtcNow, "AccountPlan-SetInitBalance", weirdException); + + throw; + } + } + [WebMethod] public static ChangeAccountDataResult SetAccountBudget (int accountId, string budget) { @@ -357,6 +450,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers public string AccountOwnerName; public bool Active; public bool Administrative; + public string InitialBalance; public string Balance; public string Budget; public string ClosedYear; diff --git a/Site5/Pages/v5/Ledgers/Json-AccountPlanData.aspx.cs b/Site5/Pages/v5/Ledgers/Json-AccountPlanData.aspx.cs index 17e1de3b..4f4c559b 100644 --- a/Site5/Pages/v5/Ledgers/Json-AccountPlanData.aspx.cs +++ b/Site5/Pages/v5/Ledgers/Json-AccountPlanData.aspx.cs @@ -41,11 +41,11 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers PopulateLookups (FinancialAccounts.ForOrganization (this._authenticationData.CurrentOrganization)); this._hashedAccounts = FinancialAccounts.GetHashedAccounts (this._authenticationData.CurrentOrganization); - response += GetAccountGroup (FinancialAccountType.Asset, Resources.Pages.Ledgers.BalanceSheet_Assets) + ","; - response += GetAccountGroup (FinancialAccountType.Debt, Resources.Pages.Ledgers.BalanceSheet_Debt) + ","; + response += GetAccountGroup (FinancialAccountType.Asset, Resources.Global.Financial_Asset) + ","; + response += GetAccountGroup (FinancialAccountType.Debt, Resources.Global.Financial_Debt) + ","; response += - GetAccountGroup (FinancialAccountType.Income, Resources.Pages.Ledgers.ProfitLossStatement_Income) + ","; - response += GetAccountGroup (FinancialAccountType.Cost, Resources.Pages.Ledgers.ProfitLossStatement_Costs); + GetAccountGroup (FinancialAccountType.Income, Resources.Global.Financial_Income) + ","; + response += GetAccountGroup (FinancialAccountType.Cost, Resources.Global.Financial_Cost); Response.Output.WriteLine ("[" + response + "]"); Response.End();