diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index 8be86998..50af2d1a 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -233,6 +233,7 @@ + diff --git a/Logic/Support/AsyncProcesses.cs b/Logic/Support/AsyncProcesses.cs new file mode 100644 index 00000000..44ef5126 --- /dev/null +++ b/Logic/Support/AsyncProcesses.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Common; +using Swarmops.Logic.Cache; +using Swarmops.Logic.Financial; +using Swarmops.Logic.Security; +using Swarmops.Logic.Structure; +using Swarmops.Logic.Swarm; + +namespace Swarmops.Logic.Support +{ + public class AsyncProcesses + { + public static ImportExternalTransactionDataResults ImportExternalTransactionData(ExternalBankData import, ImportExternalTransactionDataArgs args) + { + FinancialAccount assetAccount = args.Account; + FinancialAccount autoDepositAccount = args.Organization.FinancialAccounts.IncomeDonations; + int autoDepositLimit = 0; // Disabled; TODO: this.CurrentOrganization.Parameters.AutoDonationLimit; + + bool autosetInitialBalance = false; + ImportExternalTransactionDataResults result = new ImportExternalTransactionDataResults(); + int count = 0; + int progressUpdateInterval = import.Records.Length/40; + Int64 importedCentsTotal = 0; + + if (progressUpdateInterval > 100) + { + progressUpdateInterval = 100; + } + + ProgressBarBackend progressDisplay = new ProgressBarBackend(args.Guid); + + Currency organizationCurrency = assetAccount.Organization.Currency; + Currency accountCurrency = assetAccount.ForeignCurrency; + + if (accountCurrency == null) + { + accountCurrency = organizationCurrency; + } + + FinancialAccountRows existingRows = assetAccount.GetRows(Constants.DateTimeLow, Constants.DateTimeHigh); + // gets all + if (existingRows.Count == 0) + { + autosetInitialBalance = true; + } + + + foreach (ExternalBankDataRecord row in import.Records) + { + // Update progress. + + count++; + if (progressUpdateInterval < 2 || count%progressUpdateInterval == 0) + { + int percent = (count*99)/import.Records.Length; + + progressDisplay.Set(percent); + } + + // Update high- and low-water marks. + + if (row.DateTime < result.EarliestTransaction) + { + result.EarliestTransaction = row.DateTime; + } + + if (row.DateTime > result.LatestTransaction) + { + result.LatestTransaction = row.DateTime; + } + + + string importKey = row.ImportHash; + + Int64 amountCents = row.TransactionNetCents; + + if (amountCents == 0) + // defensive programming - these _should_ be duplicated in the interpreter if no "fee" field + { + amountCents = row.TransactionGrossCents; + } + + Int64 foreignCents = amountCents; + importedCentsTotal += amountCents; + + if (accountCurrency.Identity != organizationCurrency.Identity) + { + amountCents = + new Money(amountCents, accountCurrency, row.DateTime).ToCurrency(organizationCurrency).Cents; + } + + FinancialTransaction transaction = FinancialTransaction.ImportWithStub(args.Organization.Identity, + row.DateTime, + assetAccount.Identity, amountCents, + row.Description, importKey, Sha256.Compute(row.RawData), + args.CurrentUser.Identity); + + if (transaction != null) + { + // The transaction was created. + + result.TransactionsImported++; + + // If non-presentation currency, log the account currency amount as well. + + if (accountCurrency.Identity != organizationCurrency.Identity) + { + transaction.Rows[0].AmountForeignCents = new Money(foreignCents, accountCurrency); + } + + if (row.Description.ToLowerInvariant().StartsWith(args.Organization.IncomingPaymentTag)) + { + // Check for previously imported payment group + + // TODO: MAKE FLEXIBLE - CALL PAYMENTREADERINTERFACE! + // HACK HACK HACK HACK + + PaymentGroup group = PaymentGroup.FromTag(args.Organization, + "SEBGM" + DateTime.Today.Year + // TODO: Get tags from org + row.Description.Substring(args.Organization.IncomingPaymentTag.Length).Trim()); + + if (group != null && group.Open) + { + // There was a previously imported and not yet closed payment group matching this transaction + // Close the payment group and match the transaction against accounts receivable + + transaction.Dependency = group; + group.Open = false; + transaction.AddRow(args.Organization.FinancialAccounts.AssetsOutboundInvoices, -amountCents, + args.CurrentUser); + } + } + else if (amountCents < 0) + { + // Autowithdrawal mechanisms removed, condition kept because of downstream else-if conditions + } + else if (amountCents > 0) + { + if (row.FeeCents < 0) + { + // This is always an autodeposit, if there is a fee (which is never > 0.0) + + transaction.AddRow(args.Organization.FinancialAccounts.CostsBankFees, -row.FeeCents, + args.CurrentUser); + transaction.AddRow(autoDepositAccount, -row.TransactionGrossCents, args.CurrentUser); + } + else if (amountCents < autoDepositLimit*100) + { + // Book against autoDeposit account. + + transaction.AddRow(autoDepositAccount, -amountCents, args.CurrentUser); + } + } + } + else + { + // Transaction was not imported; assume duplicate + + result.DuplicateTransactions++; + } + } + + // Import complete. Return true if the bookkeeping account matches the bank data. + + Int64 databaseAccountBalanceCents; + + if (accountCurrency.Identity == organizationCurrency.Identity) + { + databaseAccountBalanceCents = assetAccount.BalanceTotalCents; + } + else + { + // foreign-currency account + databaseAccountBalanceCents = assetAccount.ForeignCurrencyBalance.Cents; + } + + + // Subtract any transactions made after the most recent imported transaction. + // This is necessary in case of Paypal and others which continuously feed the + // bookkeeping account with new transactions; it will already have fed transactions + // beyond the end-of-file. + + Int64 beyondEofCents = assetAccount.GetDeltaCents(result.LatestTransaction.AddSeconds(1), + DateTime.Now.AddDays(2)); + // Caution: the "AddSeconds(1)" is not foolproof, there may be other new txs on the same second. + + if (databaseAccountBalanceCents - beyondEofCents == import.LatestAccountBalanceCents) + { + Payouts.AutomatchAgainstUnbalancedTransactions(args.Organization); + OutboundInvoices.AutomatchAgainstUnbalancedTransactions(args.Organization, args.CurrentUser); + result.AccountBalanceMatchesBank = true; + result.BalanceMismatchCents = 0; + } + else + { + result.AccountBalanceMatchesBank = false; + result.BalanceMismatchCents = (databaseAccountBalanceCents - beyondEofCents) - + import.LatestAccountBalanceCents; + + if (autosetInitialBalance) + { + Int64 newInitialBalanceCents = -result.BalanceMismatchCents; + Money initialBalance = new Money(newInitialBalanceCents, accountCurrency); + + assetAccount.InitialBalance = initialBalance; + result.InitialBalanceCents = newInitialBalanceCents; + result.InitialBalanceCurrencyCode = accountCurrency.Code; + + // make an approximation of conversion rate set for initial balance in presentation to tell user + initialBalance.ValuationDateTime = new DateTime(assetAccount.Organization.FirstFiscalYear, 1, 1); + result.BalanceMismatchCents = initialBalance.ToCurrency(assetAccount.Organization.Currency).Cents; + } + } + + result.CurrencyCode = args.Organization.Currency.Code; + GuidCache.Set(args.Guid + "-Results", result); + return result; + } + + public class ImportExternalTransactionDataArgs + { + public string Guid { get; set; } + public Organization Organization { get; set; } + public FinancialAccount Account { get; set; } + public Person CurrentUser { get; set; } + } + } + + [Serializable] + public class ImportExternalTransactionDataResults + { + public bool AccountBalanceMatchesBank; + public long BalanceMismatchCents; + public string CurrencyCode; + public int DuplicateTransactions; + public DateTime EarliestTransaction; + public DateTime LatestTransaction; + public int TransactionsImported; + public Int64 InitialBalanceCents; + public string InitialBalanceCurrencyCode; + + public ImportExternalTransactionDataResults() + { + this.EarliestTransaction = Constants.DateTimeHigh; + this.LatestTransaction = Constants.DateTimeLow; + } + } +} diff --git a/Site/Pages/v5/Ledgers/EndOfMonth.aspx b/Site/Pages/v5/Ledgers/EndOfMonth.aspx index eff5eed8..7277f894 100644 --- a/Site/Pages/v5/Ledgers/EndOfMonth.aspx +++ b/Site/Pages/v5/Ledgers/EndOfMonth.aspx @@ -243,6 +243,20 @@ $(".group-status-icon[data-group='" + groupId + "']").fadeIn(); } + // If there are items that depend on this one, + // disable their "skip" option now (because there's + // a first document in the series) + + var itemIterator = $('.action-list-item[data-dependson="' + itemId + '"]'); + + while (itemIterator.length > 0) { + // We're only supporting a 1:1 chain at this time, no 1:n dependencies + + var localItemId = $(itemIterator).attr('data-item'); + $('span.action-list-item[data-item="' + itemId + '"] span.action-skip').addClass('action-skip-disabled'); + itemIterator = $('.action-list-item[data-dependson="' + localItemId + '"]'); + } + } function clientStartedUpload() { @@ -306,20 +320,6 @@ markItemCompleted(activeUpload); - // If there are items that depend on this one, - // disable their "skip" option now (because there's - // a first document in the series) - - var itemIterator = $('.action-list-item[data-dependson="' + activeUpload + '"]'); - - while (itemIterator.length > 0) { - // We're only supporting a 1:1 chain at this time, no 1:n dependencies - - var itemId = $(itemIterator).attr('data-item'); - $('span.action-list-item[data-item="' + itemId + '"] span.action-skip').addClass('action-skip-disabled'); - itemIterator = $('.action-list-item[data-dependson="' + itemId + '"]'); - } - activeUpload = null; } else { diff --git a/Site/Pages/v5/Ledgers/EndOfMonth.aspx.cs b/Site/Pages/v5/Ledgers/EndOfMonth.aspx.cs index 79aab04c..a5f47b20 100644 --- a/Site/Pages/v5/Ledgers/EndOfMonth.aspx.cs +++ b/Site/Pages/v5/Ledgers/EndOfMonth.aspx.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.Linq; using System.Resources; using System.Text; +using System.Threading; using System.Web; using System.Web.Services; using System.Web.UI; @@ -343,7 +344,7 @@ namespace Swarmops.Frontend.Pages.Ledgers [WebMethod] - public static AjaxCallResult UploadBankStatement(string guid, string itemId) + public static AjaxUploadCallResult UploadBankStatement(string guid, string itemId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); if (!authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails))) @@ -368,11 +369,11 @@ namespace Swarmops.Frontend.Pages.Ledgers documents.SetForeignObjectForAll(accountDoc); - return new AjaxCallResult {Success = true}; + return new AjaxUploadCallResult {Success = true, StillProcessing = false}; } [WebMethod] - public static AjaxCallResult UploadTransactionData(string guid, string itemId) + public static AjaxUploadCallResult UploadTransactionData(string guid, string itemId) { AuthenticationData authData = GetAuthenticationDataAndCulture(); if (!authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails))) @@ -412,18 +413,35 @@ namespace Swarmops.Frontend.Pages.Ledgers } catch (Exception) { - return new AjaxCallResult {Success = false, DisplayMessage = "ERROR_FILEDATAFORMAT"}; + return new AjaxUploadCallResult {Success = false, DisplayMessage = "ERROR_FILEDATAFORMAT"}; } // Start async thread to import the data to the SQL database; the caller must // check the status of the import - // Continue here + string identifier = guid + "-" + itemId + "-" + Guid.NewGuid().ToString(); + + Thread processThread = new Thread((ThreadStart) AsyncProcesses.ImportExternalTransactionDataThreadStart); + processThread.Start(new AsyncProcesses.ImportExternalTransactionDataArgs {}); + + return new AjaxUploadCallResult + { + Success = true, + StillProcessing = true, + Identifier = identifier + }; } - return new AjaxCallResult {Success = true, DisplayMessage = "SUCCESS_UPLOAD_PROCESSING"}; + return new AjaxUploadCallResult {Success = true, StillProcessing = true}; } + private static void ProcessUploadTransactionDataThread(object args) + { + + } + + + [WebMethod] public static AjaxCallResult ResyncSatoshisInLedger(string itemId) { @@ -481,6 +499,12 @@ namespace Swarmops.Frontend.Pages.Ledgers private List ItemGroups { get; set; } + public class AjaxUploadCallResult: AjaxCallResult + { + public bool StillProcessing { get; set; } + public string Identifier { get; set; } + } + public string Localized_SkipPrompt_BankStatement { diff --git a/Site/Pages/v5/Ledgers/UploadBankFiles.aspx.cs b/Site/Pages/v5/Ledgers/UploadBankFiles.aspx.cs index fd6821e1..38f88369 100644 --- a/Site/Pages/v5/Ledgers/UploadBankFiles.aspx.cs +++ b/Site/Pages/v5/Ledgers/UploadBankFiles.aspx.cs @@ -289,7 +289,7 @@ namespace Swarmops.Site.Pages.Ledgers ReportedImportResults results = new ReportedImportResults(); ImportResultsCategory category = (ImportResultsCategory)GuidCache.Get(guid + "-Result"); - ImportResults resultDetail = GuidCache.Get(guid + "-ResultDetails") as ImportResults; + ImportExternalTransactionDataResults resultDetail = GuidCache.Get(guid + "-ResultDetails") as ImportExternalTransactionDataResults; ImportedPaymentData paymentsDetail = GuidCache.Get(guid + "-ResultDetails") as ImportedPaymentData; string exceptionText = GuidCache.Get(guid + "-Exception") as string; @@ -394,7 +394,7 @@ namespace Swarmops.Site.Pages.Ledgers { externalData.LoadData(reader, organization, accountCurrency); // catch here and set result to BAD - ImportResults results = ProcessImportedData(externalData, (ProcessThreadArguments)args); + ImportExternalTransactionDataResults results = Swarmops.Logic.Support.AsyncProcesses.ImportExternalTransactionData(externalData, new AsyncProcesses.ImportExternalTransactionDataArgs { Account = account, CurrentUser = currentUser, Guid = guid, Organization = organization }); GuidCache.Set(guid + "-ResultDetails", results); if (results.AccountBalanceMatchesBank || results.InitialBalanceCents != 0) @@ -436,7 +436,7 @@ namespace Swarmops.Site.Pages.Ledgers { externalData.LoadData(reader, organization, accountCurrency); // catch here and set result to BAD - ImportResults results = ProcessImportedData(externalData, (ProcessThreadArguments)args); + ImportExternalTransactionDataResults results = Swarmops.Logic.Support.AsyncProcesses.ImportExternalTransactionData(externalData, new AsyncProcesses.ImportExternalTransactionDataArgs {Account = account, CurrentUser = currentUser, Guid = guid, Organization = organization}); GuidCache.Set(guid + "-ResultDetails", results); if (results.AccountBalanceMatchesBank) @@ -622,215 +622,14 @@ namespace Swarmops.Site.Pages.Ledgers }*/ + + [WebMethod] public static string GetImportResults(string guid) { return string.Empty; } - private static ImportResults ProcessImportedData(ExternalBankData import, ProcessThreadArguments args) - { - FinancialAccount assetAccount = args.Account; - FinancialAccount autoDepositAccount = args.Organization.FinancialAccounts.IncomeDonations; - int autoDepositLimit = 0; // Disabled; TODO: this.CurrentOrganization.Parameters.AutoDonationLimit; - - bool autosetInitialBalance = false; - ImportResults result = new ImportResults(); - int count = 0; - int progressUpdateInterval = import.Records.Length / 40; - Int64 importedCentsTotal = 0; - - if (progressUpdateInterval > 100) - { - progressUpdateInterval = 100; - } - - Currency organizationCurrency = assetAccount.Organization.Currency; - Currency accountCurrency = assetAccount.ForeignCurrency; - - if (accountCurrency == null) - { - accountCurrency = organizationCurrency; - } - - FinancialAccountRows existingRows = assetAccount.GetRows(Constants.DateTimeLow, Constants.DateTimeHigh); // gets all - if (existingRows.Count == 0) - { - autosetInitialBalance = true; - } - - - foreach (ExternalBankDataRecord row in import.Records) - { - // Update progress. - - count++; - if (progressUpdateInterval < 2 || count % progressUpdateInterval == 0) - { - int percent = (count * 99) / import.Records.Length; - - GuidCache.Set(args.Guid + "-Progress", percent); - } - - // Update high- and low-water marks. - - if (row.DateTime < result.EarliestTransaction) - { - result.EarliestTransaction = row.DateTime; - } - - if (row.DateTime > result.LatestTransaction) - { - result.LatestTransaction = row.DateTime; - } - - - string importKey = row.ImportHash; - - Int64 amountCents = row.TransactionNetCents; - - if (amountCents == 0) - // defensive programming - these _should_ be duplicated in the interpreter if no "fee" field - { - amountCents = row.TransactionGrossCents; - } - - Int64 foreignCents = amountCents; - importedCentsTotal += amountCents; - - if (accountCurrency.Identity != organizationCurrency.Identity) - { - amountCents = - new Money(amountCents, accountCurrency, row.DateTime).ToCurrency(organizationCurrency).Cents; - } - - FinancialTransaction transaction = FinancialTransaction.ImportWithStub(args.Organization.Identity, - row.DateTime, - assetAccount.Identity, amountCents, - row.Description, importKey, Sha256.Compute (row.RawData), - args.CurrentUser.Identity); - - if (transaction != null) - { - // The transaction was created. - - result.TransactionsImported++; - - // If non-presentation currency, log the account currency amount as well. - - if (accountCurrency.Identity != organizationCurrency.Identity) - { - transaction.Rows[0].AmountForeignCents = new Money(foreignCents, accountCurrency); - } - - if (row.Description.ToLowerInvariant().StartsWith(args.Organization.IncomingPaymentTag)) - { - // Check for previously imported payment group - - // TODO: MAKE FLEXIBLE - CALL PAYMENTREADERINTERFACE! - // HACK HACK HACK HACK - - PaymentGroup group = PaymentGroup.FromTag(args.Organization, - "SEBGM" + DateTime.Today.Year + // TODO: Get tags from org - row.Description.Substring(args.Organization.IncomingPaymentTag.Length).Trim()); - - if (group != null && group.Open) - { - // There was a previously imported and not yet closed payment group matching this transaction - // Close the payment group and match the transaction against accounts receivable - - transaction.Dependency = group; - group.Open = false; - transaction.AddRow(args.Organization.FinancialAccounts.AssetsOutboundInvoices, -amountCents, - args.CurrentUser); - } - } - else if (amountCents < 0) - { - // Autowithdrawal mechanisms removed, condition kept because of downstream else-if conditions - } - else if (amountCents > 0) - { - if (row.FeeCents < 0) - { - // This is always an autodeposit, if there is a fee (which is never > 0.0) - - transaction.AddRow(args.Organization.FinancialAccounts.CostsBankFees, -row.FeeCents, - args.CurrentUser); - transaction.AddRow(autoDepositAccount, -row.TransactionGrossCents, args.CurrentUser); - } - else if (amountCents < autoDepositLimit * 100) - { - // Book against autoDeposit account. - - transaction.AddRow(autoDepositAccount, -amountCents, args.CurrentUser); - } - } - } - else - { - // Transaction was not imported; assume duplicate - - result.DuplicateTransactions++; - } - } - - // Import complete. Return true if the bookkeeping account matches the bank data. - - Int64 databaseAccountBalanceCents; - - if (accountCurrency.Identity == organizationCurrency.Identity) - { - databaseAccountBalanceCents = assetAccount.BalanceTotalCents; - } - else - { - // foreign-currency account - databaseAccountBalanceCents = assetAccount.ForeignCurrencyBalance.Cents; - } - - - // Subtract any transactions made after the most recent imported transaction. - // This is necessary in case of Paypal and others which continuously feed the - // bookkeeping account with new transactions; it will already have fed transactions - // beyond the end-of-file. - - Int64 beyondEofCents = assetAccount.GetDeltaCents(result.LatestTransaction.AddSeconds(1), - DateTime.Now.AddDays(2)); - // Caution: the "AddSeconds(1)" is not foolproof, there may be other new txs on the same second. - - if (databaseAccountBalanceCents - beyondEofCents == import.LatestAccountBalanceCents) - { - Payouts.AutomatchAgainstUnbalancedTransactions(args.Organization); - OutboundInvoices.AutomatchAgainstUnbalancedTransactions(args.Organization, args.CurrentUser); - result.AccountBalanceMatchesBank = true; - result.BalanceMismatchCents = 0; - } - else - { - result.AccountBalanceMatchesBank = false; - result.BalanceMismatchCents = (databaseAccountBalanceCents - beyondEofCents) - - import.LatestAccountBalanceCents; - - if (autosetInitialBalance) - { - Int64 newInitialBalanceCents = -result.BalanceMismatchCents; - Money initialBalance = new Money(newInitialBalanceCents, accountCurrency); - - assetAccount.InitialBalance = initialBalance; - result.InitialBalanceCents = newInitialBalanceCents; - result.InitialBalanceCurrencyCode = accountCurrency.Code; - - // make an approximation of conversion rate set for initial balance in presentation to tell user - initialBalance.ValuationDateTime = new DateTime(assetAccount.Organization.FirstFiscalYear, 1, 1); - result.BalanceMismatchCents = initialBalance.ToCurrency(assetAccount.Organization.Currency).Cents; - } - } - - result.CurrencyCode = args.Organization.Currency.Code; - return result; - } - protected static ImportedPaymentData ImportBankgiroSE(StreamReader reader, Person currentUser, Organization organization) { @@ -1049,26 +848,17 @@ namespace Swarmops.Site.Pages.Ledgers PaymentDetails } - [Serializable] - public class ImportResults - { - public bool AccountBalanceMatchesBank; - public long BalanceMismatchCents; - public string CurrencyCode; - public int DuplicateTransactions; - public DateTime EarliestTransaction; - public DateTime LatestTransaction; - public int TransactionsImported; - public Int64 InitialBalanceCents; - public string InitialBalanceCurrencyCode; - public ImportResults() - { - this.EarliestTransaction = Constants.DateTimeHigh; - this.LatestTransaction = Constants.DateTimeLow; - } + private class ProcessThreadArguments + { + public string Guid { get; set; } + public Organization Organization { get; set; } + public FinancialAccount Account { get; set; } + public Person CurrentUser { get; set; } + public BankFileType FileType { get; set; } } + /* protected void UpdateImportProgressBar (int percentDone) { @@ -1120,15 +910,6 @@ namespace Swarmops.Site.Pages.Ledgers } } - private class ProcessThreadArguments - { - public string Guid { get; set; } - public Organization Organization { get; set; } - public FinancialAccount Account { get; set; } - public Person CurrentUser { get; set; } - public BankFileType FileType { get; set; } - } - public class ReportedImportResults { public string Category { get; set; } diff --git a/Site/Scripts/Swarmops-v5.js b/Site/Scripts/Swarmops-v5.js index ca7efc0f..d7001598 100644 --- a/Site/Scripts/Swarmops-v5.js +++ b/Site/Scripts/Swarmops-v5.js @@ -137,6 +137,11 @@ function _masterInitializeSocket(authenticationTicket) { if (updateFunction != undefined) { updateFunction(message.Progress); } + + else if (typeof progressUpdateCallback === "function") // if a function for catchall progress has been defined + { + progressUpdateCallback(message); + } } }; }