From 41949bbc1c40e48cf4da540dcd0c4ec4f1d1ff94 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sat, 27 Dec 2014 20:21:35 +0100 Subject: [PATCH 01/14] Adding currency exchange rate handling --- Basic/Basic.csproj | 1 + .../Financial/BasicExchangeRateSnapshot.cs | 44 ++++++++++ Database/Configuration.cs | 2 +- Database/Schemata/revisions.txt | 1 + Database/Schemata/upgrade-0009.sql | 26 ++++++ Logic/Financial/ExchangeRateSnapshot.cs | 82 +++++++++++++++++++ Logic/Financial/ExchangeRateSnapshots.cs | 15 ++++ Logic/Logic.csproj | 3 + Site5/Automation/GetFinancialData.asmx | 44 ++++++++++ Site5/Automation/GetGeographyData.asmx | 13 +++ Site5/Default.aspx.cs | 3 + 11 files changed, 233 insertions(+), 1 deletion(-) create mode 100644 Basic/Types/Financial/BasicExchangeRateSnapshot.cs create mode 100644 Database/Schemata/upgrade-0009.sql create mode 100644 Logic/Financial/ExchangeRateSnapshot.cs create mode 100644 Logic/Financial/ExchangeRateSnapshots.cs create mode 100644 Site5/Automation/GetFinancialData.asmx 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..c6d001d9 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 9; } } diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index b0a3ef81..9b8a0953 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -6,3 +6,4 @@ 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] \ 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..de993b1a --- /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 `CreateExchangeRateDatapoint`( + IN currencyExchangeRateSnapshotId INTEGER, + IN currencyAId INTEGER, + IN currencyBId INTEGER, + IN aPerB DOUBLE +) +BEGIN + + INSERT INTO CurrencyExchangeRateSnapshotData (CurrencyExchangeRateSnapshotId,CurrencyAId,CurrencyBId,APerB) + VALUES (currencyExchangeRateSnapshotId,currencyAId,currencyBId,aPerB); + +END \ No newline at end of file diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs new file mode 100644 index 00000000..b4d3f154 --- /dev/null +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -0,0 +1,82 @@ +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; + +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()) + { + 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); + + if (match.Success) + { + // We have at least one match, so prepare a new ExchangeRate snapshot + } + + while (match.Success) + { + string currencyCode = match.Groups[0].Value; + string currencyName = match.Groups[1].Value; + double btcRate = Double.Parse (match.Groups[2].Value, NumberStyles.AllowDecimalPoint, + CultureInfo.InvariantCulture); + + + match = match.NextMatch(); + } + + JavaScriptSerializer serializer = new JavaScriptSerializer(); + BitpayRateDatapoint[] rates = (BitpayRateDatapoint[]) serializer.Deserialize (rateDataRaw); + } + } + + } + + [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/Logic.csproj b/Logic/Logic.csproj index 3ec05bf3..c22c8963 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -67,6 +67,7 @@ + @@ -119,6 +120,8 @@ + + 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/Default.aspx.cs b/Site5/Default.aspx.cs index 18921d9d..c0577f4c 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 { @@ -14,5 +15,7 @@ public partial class Default : PageV5Base InfoBoxLiteral = "This is a Dashboard placeholder. It will contain a snapshot of the state of things as soon as the basic functions are re-implemented in the new interface."; + + ExchangeRateSnapshot.Create(); } } \ No newline at end of file From 6ee42d278768348d5ea2267d2c640e5735ecfffc Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sat, 27 Dec 2014 21:06:02 +0100 Subject: [PATCH 02/14] Mono has no root certs! Uglyhacking. --- Logic/Financial/ExchangeRateSnapshot.cs | 3 +++ Logic/Logic.csproj | 1 + Logic/Support/General.cs | 23 +++++++++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 Logic/Support/General.cs diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs index b4d3f154..f1c623c9 100644 --- a/Logic/Financial/ExchangeRateSnapshot.cs +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Xml.Serialization; using Swarmops.Basic.Types.Financial; +using Swarmops.Logic.Support; namespace Swarmops.Logic.Financial { @@ -39,6 +40,8 @@ namespace Swarmops.Logic.Financial { 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"); diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index c22c8963..038a2df7 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -252,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; + } + } +} From 4b3de70c59573ce7127ab6620c09322c86a75a88 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sat, 27 Dec 2014 21:26:13 +0100 Subject: [PATCH 03/14] Fix for group counts - new test on Mono --- Logic/Financial/ExchangeRateSnapshot.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs index f1c623c9..30350bcb 100644 --- a/Logic/Financial/ExchangeRateSnapshot.cs +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -59,9 +59,9 @@ namespace Swarmops.Logic.Financial while (match.Success) { - string currencyCode = match.Groups[0].Value; - string currencyName = match.Groups[1].Value; - double btcRate = Double.Parse (match.Groups[2].Value, NumberStyles.AllowDecimalPoint, + string currencyCode = match.Groups[1].Value; + string currencyName = match.Groups[2].Value; + double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); From e84ea3f931e969c594a68e463ce1dd63ac24924e Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 02:24:23 +0100 Subject: [PATCH 04/14] Fix for Db0009 --- Database/Schemata/upgrade-0009.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Database/Schemata/upgrade-0009.sql b/Database/Schemata/upgrade-0009.sql index de993b1a..2d22dad7 100644 --- a/Database/Schemata/upgrade-0009.sql +++ b/Database/Schemata/upgrade-0009.sql @@ -12,7 +12,7 @@ DROP PROCEDURE `InsertExchangeRateSnapshotData` # -CREATE `CreateExchangeRateDatapoint`( +CREATE PROCEDURE `CreateExchangeRateDatapoint`( IN currencyExchangeRateSnapshotId INTEGER, IN currencyAId INTEGER, IN currencyBId INTEGER, From a3d23af1f0cc2eed0ed9b701e4998a58136a1dc0 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 02:27:59 +0100 Subject: [PATCH 05/14] Fix for Db0009 --- Database/Schemata/upgrade-0009.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Database/Schemata/upgrade-0009.sql b/Database/Schemata/upgrade-0009.sql index 2d22dad7..8dd3c022 100644 --- a/Database/Schemata/upgrade-0009.sql +++ b/Database/Schemata/upgrade-0009.sql @@ -13,7 +13,7 @@ DROP PROCEDURE `InsertExchangeRateSnapshotData` CREATE PROCEDURE `CreateExchangeRateDatapoint`( - IN currencyExchangeRateSnapshotId INTEGER, + IN exchangeRateSnapshotId INTEGER, IN currencyAId INTEGER, IN currencyBId INTEGER, IN aPerB DOUBLE @@ -21,6 +21,6 @@ CREATE PROCEDURE `CreateExchangeRateDatapoint`( BEGIN INSERT INTO CurrencyExchangeRateSnapshotData (CurrencyExchangeRateSnapshotId,CurrencyAId,CurrencyBId,APerB) - VALUES (currencyExchangeRateSnapshotId,currencyAId,currencyBId,aPerB); + VALUES (exchangeRateSnapshotId,currencyAId,currencyBId,aPerB); END \ No newline at end of file From a944b1c8f403dabbb58506aaebd0edd7f968b933 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 03:05:51 +0100 Subject: [PATCH 06/14] DbVersion 0010; exchange rates --- Database/Configuration.cs | 2 +- Database/Database-Currencies.cs | 20 --- Database/Database-ExchangeRates.cs | 226 ++++++++++++++++++++++++ Database/Database.csproj | 1 + Database/Schemata/revisions.txt | 5 +- Database/Schemata/upgrade-0010.sql | 6 + Logic/Financial/ExchangeRateSnapshot.cs | 22 +++ 7 files changed, 259 insertions(+), 23 deletions(-) create mode 100644 Database/Database-ExchangeRates.cs create mode 100644 Database/Schemata/upgrade-0010.sql diff --git a/Database/Configuration.cs b/Database/Configuration.cs index c6d001d9..0b3eed30 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -14,7 +14,7 @@ namespace Swarmops.Database /// public static int DbVersionExpected { - get { return 9; } + 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 9b8a0953..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,4 +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] \ No newline at end of file +0009 - Fixed SalaryTaxLevels and CreateExchangeRateDataPoint [RF] +0010 - Fix for CurrencyExchangeRateSnapshotData [RF] \ 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 index 30350bcb..1ed67b3d 100644 --- a/Logic/Financial/ExchangeRateSnapshot.cs +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -9,6 +9,7 @@ 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 @@ -52,9 +53,14 @@ namespace Swarmops.Logic.Financial 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) @@ -64,6 +70,10 @@ namespace Swarmops.Logic.Financial double btcRate = Double.Parse (match.Groups[3].Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + int currencyId = GetOrCreateCurrency (currencyCode, currencyName); + + SwarmDb.GetDatabaseForWriting() + .CreateExchangeRateDatapoint (exchangeRateSnapshotId, currencyId, bitcoinId, btcRate); match = match.NextMatch(); } @@ -73,6 +83,18 @@ namespace Swarmops.Logic.Financial } } + 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] From e66e1907db84fda17d5c942aeb392d364165de32 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 03:22:54 +0100 Subject: [PATCH 07/14] Enabled daily exchange rate snapshots --- Backend/Program.cs | 2 ++ Site5/Default.aspx.cs | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) 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/Site5/Default.aspx.cs b/Site5/Default.aspx.cs index c0577f4c..726975d1 100644 --- a/Site5/Default.aspx.cs +++ b/Site5/Default.aspx.cs @@ -15,7 +15,5 @@ public partial class Default : PageV5Base InfoBoxLiteral = "This is a Dashboard placeholder. It will contain a snapshot of the state of things as soon as the basic functions are re-implemented in the new interface."; - - ExchangeRateSnapshot.Create(); } } \ No newline at end of file From 19f73cca0bb9568fb228d81ef2f12b921e7bd237 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 13:26:32 +0100 Subject: [PATCH 08/14] Deployed CurrencyTextBox; testing on Mono --- .../v5/Financial/CurrencyTextBox.ascx | 4 +++ .../v5/Financial/CurrencyTextBox.ascx.cs | 27 +++++++++++++++++++ .../v5/Financial/RequestCashAdvance.aspx | 7 ++--- .../v5/Financial/RequestCashAdvance.aspx.cs | 5 ++-- 4 files changed, 37 insertions(+), 6 deletions(-) diff --git a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx index 87e23c61..84c0bcf5 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..e507e18b 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,31 @@ 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.Currency, CultureInfo.CurrentCulture, out outParse)) + { + return outParse; + } + if (Double.TryParse (contents, NumberStyles.Currency, 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); } + } } } \ No newline at end of file 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..88232c01 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,8 +62,7 @@ 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 + double amount = this.TextAmount.Value; Int64 amountCents = (Int64) amount*100; string description = this.TextPurpose.Text; From 6ef1239b41dfec207fe7f2992008d52dd6663992 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 13:48:02 +0100 Subject: [PATCH 09/14] Debugging an elusive Mono bug in Double.Parse --- Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs | 4 ++-- Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs index e507e18b..22afdfe3 100644 --- a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs +++ b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs @@ -23,11 +23,11 @@ namespace Swarmops.Frontend.Controls.v5.Financial double outParse = 0.0; string contents = Input.Text; - if (Double.TryParse (contents, NumberStyles.Currency, CultureInfo.CurrentCulture, out outParse)) + if (Double.TryParse (contents, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out outParse)) { return outParse; } - if (Double.TryParse (contents, NumberStyles.Currency, CultureInfo.InvariantCulture, out outParse)) + if (Double.TryParse(contents, NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out outParse)) { return outParse; } diff --git a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs index 88232c01..f43d6161 100644 --- a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs +++ b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs @@ -62,6 +62,10 @@ 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. + // MONO BUG: Need to re-set the current culture for parsing to work properly. + + AuthenticationData authData = CommonV5.GetAuthenticationDataAndCulture (HttpContext.Current); + double amount = this.TextAmount.Value; Int64 amountCents = (Int64) amount*100; From ec1be71be46768be5e4f136ce3d333d4d3f9f137 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 14:00:16 +0100 Subject: [PATCH 10/14] Debugging an elusive Mono bug in Double.Parse (2) --- Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs index f43d6161..f1890847 100644 --- a/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs +++ b/Site5/Pages/v5/Financial/RequestCashAdvance.aspx.cs @@ -62,12 +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. - // MONO BUG: Need to re-set the current culture for parsing to work properly. - - AuthenticationData authData = CommonV5.GetAuthenticationDataAndCulture (HttpContext.Current); - double amount = this.TextAmount.Value; - Int64 amountCents = (Int64) amount*100; + Int64 amountCents = (Int64) (amount*100.0); string description = this.TextPurpose.Text; From 23728953253aa3da8b2976fdca7ca33855799918 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 14:13:44 +0100 Subject: [PATCH 11/14] Fixes horrible Double.Parse bug that wasn't --- Site5/Pages/v5/Financial/CreateInboundInvoice.aspx.cs | 2 +- Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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; From 793f6c8f4ccc0918a17d195648f7414565623f05 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 14:34:22 +0100 Subject: [PATCH 12/14] Added hidden fields for future expansion --- Site5/Controls/v5/Financial/CurrencyTextBox.ascx | 2 +- Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx index 84c0bcf5..8e5b0585 100644 --- a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx +++ b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx @@ -2,4 +2,4 @@ - \ No newline at end of file + \ 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 22afdfe3..c9d88ac7 100644 --- a/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs +++ b/Site5/Controls/v5/Financial/CurrencyTextBox.ascx.cs @@ -39,5 +39,7 @@ namespace Swarmops.Frontend.Controls.v5.Financial } set { this.Input.Text = value.ToString ("N2", CultureInfo.CurrentCulture); } } + + // TODO: Add other-currency parsing } } \ No newline at end of file From 4627715cddaadd4d6ceb9ab47ff89ada39b11823 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 15:43:25 +0100 Subject: [PATCH 13/14] Adjust for operating in microbitcoin --- Logic/Financial/ExchangeRateSnapshot.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Logic/Financial/ExchangeRateSnapshot.cs b/Logic/Financial/ExchangeRateSnapshot.cs index 1ed67b3d..36c48ba3 100644 --- a/Logic/Financial/ExchangeRateSnapshot.cs +++ b/Logic/Financial/ExchangeRateSnapshot.cs @@ -70,6 +70,8 @@ namespace Swarmops.Logic.Financial 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() From 47157ca7ee5a63492a6d803dfd76594a2c13fbd0 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Sun, 28 Dec 2014 19:50:14 +0100 Subject: [PATCH 14/14] Inbound Balances in Account Plan works. This completes the Swarmops Red feature set. --- Logic/Financial/FinancialAccountRows.cs | 13 +++ Logic/Financial/FinancialTransaction.cs | 36 +++---- Site5/App_GlobalResources/Pages.Ledgers.resx | 14 ++- .../Json-FinancialAccountsTree.aspx.cs | 8 +- Site5/Pages/v5/Ledgers/AccountPlan.aspx | 77 ++++++++++++++- Site5/Pages/v5/Ledgers/AccountPlan.aspx.cs | 96 ++++++++++++++++++- .../v5/Ledgers/Json-AccountPlanData.aspx.cs | 8 +- 7 files changed, 216 insertions(+), 36 deletions(-) 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/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/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/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();