diff --git a/Backend/Program.cs b/Backend/Program.cs index cb0784a0..e29bb1ab 100644 --- a/Backend/Program.cs +++ b/Backend/Program.cs @@ -219,6 +219,11 @@ namespace Swarmops.Backend { OnTuesdayMorning(); } + + if (DateTime.Now.Hour == 7 && DateTime.Today.DayOfWeek == DayOfWeek.Monday) + { + OnMondayMorning(); + } } if (cycleStartTime.Hour >= 12 && lastHour < 12) @@ -664,6 +669,15 @@ namespace Swarmops.Backend Payroll.ProcessMonthly(); // will only actually run on the 1st, but no harm in testing every noon } + // Check all bitcoin accounts for previously-unseen transactions once a day + + Organizations allOrganizations = Organizations.GetAll(); + foreach (Organization organization in allOrganizations) + { + // this actually checks hot storage too, but that's supposed + // to be up to date since we're the ones handling it + BitcoinUtility.CheckColdStorageForOrganization (organization); + } if (!testMode) { @@ -717,6 +731,34 @@ namespace Swarmops.Backend BotLog.Write (0, "MainCycle", "Noon exit"); } + private static void OnMondayMorning() + { + try + { + // Detect and log any forex difference exceeding 100 cents. + + FinancialAccounts allAccounts = FinancialAccounts.GetAll(); // across ALL ORGS! + + foreach (FinancialAccount account in allAccounts) + { + // For every account, if it's based on foreign currency, check for forex gains/losses + + if (account.ForeignCurrency != null) + { + account.CheckForexProfitLoss(); + } + } + } + catch (Exception e) + { + ExceptionMail.Send(e, true); + if (testMode) + { + Console.WriteLine(e.ToString()); + } + } + } + private static void OnTuesdayMorning() { try diff --git a/Database/Database-Financials.cs b/Database/Database-Financials.cs index 8e7b3c38..bd2602de 100644 --- a/Database/Database-Financials.cs +++ b/Database/Database-Financials.cs @@ -68,7 +68,7 @@ namespace Swarmops.Database // this structure, call them GetDatabaseObject and GetDatabaseCollection, and pass the query, // the reader delegate, and the expected type? - public BasicFinancialAccount[] GetFinancialAccountsForOrganization (int organizationId) + public BasicFinancialAccount[] GetFinancialAccountsAll() { List result = new List(); @@ -77,15 +77,15 @@ namespace Swarmops.Database connection.Open(); DbCommand command = - GetDbCommand ( - "SELECT " + financialAccountFieldSequence + " WHERE OrganizationId=" + - organizationId + " ORDER BY AccountType, Name;", connection); + GetDbCommand( + "SELECT " + financialAccountFieldSequence + + " ORDER BY AccountType, Name;", connection); using (DbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { - result.Add (ReadFinancialAccountFromDataReader (reader)); + result.Add(ReadFinancialAccountFromDataReader(reader)); } return result.ToArray(); @@ -93,7 +93,32 @@ namespace Swarmops.Database } } - public BasicFinancialAccount[] GetFinancialAccountsOwnedByPerson (int ownerPersonId) + public BasicFinancialAccount[] GetFinancialAccountsForOrganization(int organizationId) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT " + financialAccountFieldSequence + " WHERE OrganizationId=" + + organizationId + " ORDER BY AccountType, Name;", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadFinancialAccountFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + public BasicFinancialAccount[] GetFinancialAccountsOwnedByPerson(int ownerPersonId) { List result = new List(); @@ -1115,6 +1140,37 @@ namespace Swarmops.Database + public Int64 GetFinancialAccountForeignCentsBalance (int financialAccountId) + { + // This gets the balance across the entire ledger history, so it's only for asset or liability accounts + // (not for P&L). + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + using (DbCommand command = + GetDbCommand( + "SELECT SUM(NativeAmountCents) FROM FinancialTransactionRowsNativeCurrency " + + " JOIN FinancialTransactionRows USING (FinancialTransactionRowId) " + + " WHERE FinancialAccountId =" + financialAccountId + ";", connection)) + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return reader.GetInt64(0); + } + + return 0; // zero balance, apparently. + } + } + + + } + + + public DateTime GetFinancialAccountFirstTransactionDate(int financialAccountId) { using (DbConnection connection = GetMySqlDbConnection()) diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index 8017155d..37b82142 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -31,4 +31,4 @@ 0031 - Added foreign ID tables, procs for transactions, to track blockchain [RF] 0032 - Added native currency to transaction rows, for multi-currency accounting [RF] 0033 - Added transaction row identity return, necessary for 0032 [RF] -0034 - Fix for SetFinancialTransactionRowNativeCurrency \ No newline at end of file +0034 - Fix for SetFinancialTransactionRowNativeCurrency diff --git a/Logic/Financial/BitcoinUtility.cs b/Logic/Financial/BitcoinUtility.cs index 4fbd985e..44e86f62 100644 --- a/Logic/Financial/BitcoinUtility.cs +++ b/Logic/Financial/BitcoinUtility.cs @@ -387,6 +387,12 @@ namespace Swarmops.Logic.Financial if (!addressAccountLookup.ContainsValue (row.FinancialAccountId)) // not optimal but n is small { // This is not a bitcoin address account, so note it for reconstruction + + if (!transactionReconstructedRows.ContainsKey (row.FinancialAccountId)) + { + transactionReconstructedRows[row.FinancialAccountId] = 0; // init + } + transactionReconstructedRows[row.FinancialAccountId] += row.AmountCents; } else @@ -563,7 +569,7 @@ namespace Swarmops.Logic.Financial GetAddressAccountLookupRecurse (child, result); } - if (IsValidBitcoinAddress (account.Name)) // TODO: Add a special property for the address instead of using name + if (!string.IsNullOrEmpty(account.BitcoinAddress) || IsValidBitcoinAddress (account.Name)) // TODO: Add a special property for the address instead of using name { result [account.Name] = account.Identity; } diff --git a/Logic/Financial/FinancialAccount.cs b/Logic/Financial/FinancialAccount.cs index 281b50e4..1df509c9 100644 --- a/Logic/Financial/FinancialAccount.cs +++ b/Logic/Financial/FinancialAccount.cs @@ -129,6 +129,17 @@ namespace Swarmops.Logic.Financial } + public Money ForeignBalanceTotalCents + { + get + { + Int64 foreignCents = + SwarmDb.GetDatabaseForReading().GetFinancialAccountForeignCentsBalance (this.Identity); + return new Money (foreignCents, ForeignCurrency); // default to now + } + } + + public string BitcoinAddress { get @@ -142,6 +153,39 @@ namespace Swarmops.Logic.Financial } + public void CheckForexProfitLoss() + { + // Compare current balance in native currency with the current balance in foreign currency. If off by more than 100 cents, + // log a corrective transaction to account for exchange rate fluctuations. + + DateTime compareDateTime = DateTime.UtcNow; + + Int64 nativeCents = BalanceTotalCents; + Money foreignCents = new Money(ForeignBalanceTotalCents.Cents, ForeignCurrency, compareDateTime); + + Int64 currentNativeValueOfForeignCents = foreignCents.ToCurrency (Organization.Currency).Cents; + + if (nativeCents - 100 > currentNativeValueOfForeignCents) + { + // log a loss + + Int64 lossCents = nativeCents - currentNativeValueOfForeignCents; + FinancialTransaction lossTx = FinancialTransaction.Create (Organization, DateTime.UtcNow, "Forex Loss"); + lossTx.AddRow (this, -lossCents, null); + lossTx.AddRow (Organization.FinancialAccounts.CostsCurrencyFluctuations, lossCents, null); + } + else if (nativeCents + 100 < currentNativeValueOfForeignCents) + { + // log a profit + + Int64 profitCents = currentNativeValueOfForeignCents - nativeCents; + FinancialTransaction profitTx = FinancialTransaction.Create(Organization, DateTime.UtcNow, "Forex Gains"); + profitTx.AddRow(this, profitCents, null); + profitTx.AddRow(Organization.FinancialAccounts.IncomeCurrencyFluctuations, -profitCents, null); + } + } + + public ExternalBankDataProfile ExternalBankDataProfile { get diff --git a/Logic/Financial/FinancialAccounts.cs b/Logic/Financial/FinancialAccounts.cs index 76c9ba0d..20023a8c 100644 --- a/Logic/Financial/FinancialAccounts.cs +++ b/Logic/Financial/FinancialAccounts.cs @@ -14,6 +14,11 @@ namespace Swarmops.Logic.Financial { public class FinancialAccounts : PluralBase { + public static FinancialAccounts GetAll() + { + return FromArray (SwarmDb.GetDatabaseForReading().GetFinancialAccountsAll()); + } + public static FinancialAccounts ForOrganization (Organization organization) { return diff --git a/Site5/Master-v5.master.cs b/Site5/Master-v5.master.cs index c5a1cba3..996b320e 100644 --- a/Site5/Master-v5.master.cs +++ b/Site5/Master-v5.master.cs @@ -38,14 +38,7 @@ namespace Swarmops // BEGIN TEST CODE - // HotBitcoinAddresses testAddresses = HotBitcoinAddresses.ForOrganization (Organization.FromIdentity (2)); - // testAddresses.UpdateBalances(); - // BitcoinUtility.CheckColdStorageForOrganization (Organization.FromIdentity (7)); - - // BitcoinUtility.TestMultisigPayout(); - - // Payouts.PerformAutomated(); // END TEST CODE