using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Web; using System.Web.Services; using System.Web.UI.WebControls; using Resources; using Swarmops.Basic.Types; using Swarmops.Basic.Types.Financial; using Swarmops.Common; using Swarmops.Common.Enums; using Swarmops.Frontend; using Swarmops.Logic.Cache; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Support; using Swarmops.Logic.Swarm; using Swarmops.Interface.Support; // TODO: There are significant remnants in this file from the old Telerik-based upload code. When Account Automation is complete and the user can select a bank profile // for an account, uploading payment files as well as bank statements, remove that dead code as its templates won't be needed after that. // ReSharper disable CheckNamespace namespace Swarmops.Site.Pages.Ledgers // ReSharper restore CheckNamespace { public partial class UploadBankFiles : PageV5Base { public enum ImportResultsCategory { Unknown = 0, Good, Questionable, Bad, Payments } protected void Page_Load (object sender, EventArgs e) { PageTitle = Resources.Pages.Ledgers.UploadBankFiles_PageTitle; PageIcon = "iconshock-bank"; PageAccessRequired = new Access (CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write); if (!IsPostBack) { // Localize InfoBoxLiteral = Resources.Pages.Ledgers.UploadBankFiles_Info; this.LabelBankAccount.Text = Resources.Pages.Ledgers.UploadBankFiles_BankAccount; this.LabelProfile.Text = Resources.Pages.Ledgers.UploadBankFiles_AccountAutomationProfile; this.LabelProcessing.Text = Resources.Pages.Ledgers.UploadBankFiles_Processing; this.LabelProcessingComplete.Text = Resources.Pages.Ledgers.UploadBankFiles_ProcessingComplete; this.LabelUploadBankFile.Text = Resources.Pages.Ledgers.UploadBankFiles_UploadBankFile; this.LabelUploadMore.Text = Resources.Pages.Ledgers.UploadBankFiles_UploadAnother; this.LabelUploadBankFileHeader.Text = Resources.Pages.Ledgers.UploadBankFiles_UploadBankFile; // Populate the asset account dropdown, if needed for file type PopulateAccountDropDown(); if (this.DropAccounts.Items.Count < 2) { DashboardMessage.Set(Resources.Pages.Ledgers.UploadBankFiles_Error_NoAutomationProfiles); Response.Redirect("/", true); } } if (!IsPostBack) { // there used to be some Telerik junk here } } /* protected void ButtonSebAccountFile_Click(object sender, ImageClickEventArgs e) { OnSelectedFileType(); this.HiddenFileType.Value = "Seb"; this.ButtonSebFile.CssClass = "FileTypeImage FileTypeImageSelected"; this.ImageDownloadInstructions.ImageUrl = "~/Images/Ledgers/uploadbankfiles-seb-kontoutdrag-small.png"; this.ImageDownloadInstructionsFull.ImageUrl = "~/Images/Ledgers/uploadbankfiles-seb-kontoutdrag-full.png"; this.LiteralDownloadInstructions.Text = this.LiteralDownloadInstructionsModal.Text = Resources.Pages.Ledgers.UploadBankFiles_DownloadInstructions_SebAccountFile; } protected void ButtonBankgiroSEFile_Click(object sender, ImageClickEventArgs e) { OnSelectedFileType(); this.HiddenFileType.Value = "BankgiroSE"; this.ButtonBankgiroSEFile.CssClass = "FileTypeImage FileTypeImageSelected"; this.ImageDownloadInstructions.ImageUrl = "~/Images/Ledgers/uploadbankfiles-bankgirose-small.png"; this.ImageDownloadInstructionsFull.ImageUrl = "~/Images/Ledgers/uploadbankfiles-bankgirose-full.png"; this.LiteralDownloadInstructions.Text = this.LiteralDownloadInstructionsModal.Text = Resources.Pages.Ledgers.UploadBankFiles_DownloadInstructions_BankgiroSEFile; this.LiteralLastAccountRecord.Visible = false; } protected void ButtonPaypalFile_Click(object sender, ImageClickEventArgs e) { OnSelectedFileType(); this.HiddenFileType.Value = "PayPal"; this.ButtonPaypalFile.CssClass = "FileTypeImage FileTypeImageSelected"; this.ImageDownloadInstructions.ImageUrl = "~/Images/Ledgers/uploadbankfiles-paypal-small.png"; this.ImageDownloadInstructionsFull.ImageUrl = "~/Images/Ledgers/uploadbankfiles-paypal-full.png"; this.LiteralDownloadInstructions.Text = this.LiteralDownloadInstructionsModal.Text = Resources.Pages.Ledgers.UploadBankFiles_DownloadInstructions_PaypalFile; this.LiteralLastAccountRecord.Visible = false; } protected void ButtonPaysonFile_Click(object sender, ImageClickEventArgs e) { OnSelectedFileType(); this.HiddenFileType.Value = "Payson"; this.ButtonPaysonFile.CssClass = "FileTypeImage FileTypeImageSelected"; this.ImageDownloadInstructions.ImageUrl = "~/Images/Ledgers/uploadbankfiles-payson-small.png"; this.ImageDownloadInstructionsFull.ImageUrl = "~/Images/Ledgers/uploadbankfiles-payson-full.png"; this.LiteralDownloadInstructions.Text = this.LiteralDownloadInstructionsModal.Text = Resources.Pages.Ledgers.UploadBankFiles_DownloadInstructions_PaysonFile; this.LiteralLastAccountRecord.Visible = true; } private void OnSelectedFileType() { this.ButtonPaypalFile.CssClass = this.ButtonSebFile.CssClass = this.ButtonBankgiroSEFile.CssClass = this.ButtonPaysonFile.CssClass = "FileTypeImage UnselectedType"; ScriptManager.RegisterClientScriptBlock(this.PanelFileTypeAccount, this.PanelFileTypeAccount.GetType(), "FadeType", "$(\".UnselectedType\").fadeTo('fast',0.2);", true); ScriptManager.RegisterClientScriptBlock(this.PanelFileTypeAccount, this.PanelFileTypeAccount.GetType(), "FadeAccount1", "$(\"#DivSelectAccount\").fadeTo('slow', 1.0);", true); ScriptManager.RegisterClientScriptBlock(this.PanelFileTypeAccount, this.PanelFileTypeAccount.GetType(), "FadeAccount2", "$(\"#DivSelectAccount\").css('display','inline');", true); this.LiteralLastAccountRecord.Visible = true; }*/ private void PopulateAccountDropDown() { FinancialAccounts accounts = CurrentOrganization.FinancialAccountsExternal; this.DropAccounts.Items.Clear(); this.DropAccounts.Items.Add (new ListItem (Global.Global_DropInits_SelectFinancialAccount, "0")); foreach (FinancialAccount account in accounts) { if (account.AccountType == FinancialAccountType.Asset) { if (account.AutomationProfile.CanManualUpload) { this.DropAccounts.Items.Add(new ListItem(account.Name, account.Identity.ToString())); } } } } [WebMethod (true)] public static AjaxCallResult InitializeProcessing (string guid, int accountId) { // Start an async thread that does all the work, then return AuthenticationData authData = GetAuthenticationDataAndCulture(); BankFileType fileType = BankFileType.Unknown; if (accountId < 0) { accountId = -accountId; fileType = BankFileType.PaymentDetails; } FinancialAccount account = FinancialAccount.FromIdentity (accountId); if (account.Organization.Identity != authData.CurrentOrganization.Identity || !authData.Authority.HasAccess (new Access (authData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Write))) { throw new UnauthorizedAccessException(); } Thread initThread = new Thread (ProcessUploadThread); ProcessThreadArguments args = new ProcessThreadArguments { Guid = guid, Organization = authData.CurrentOrganization, Account = account, CurrentUser = authData.CurrentUser, FileType = fileType }; initThread.Start (args); return new AjaxCallResult {Success = true}; } [WebMethod] public static AjaxCallResult GetAutomationProfileName (string guid, int accountId) { FinancialAccount account = FinancialAccount.FromIdentity(accountId); AuthenticationData authData = GetAuthenticationDataAndCulture(); if ( !authData.Authority.HasAccess(new Access(authData.CurrentOrganization, AccessAspect.BookkeepingDetails, AccessType.Write))) { throw new UnauthorizedAccessException(); } FinancialAccountAutomationProfile profile = FinancialAccountAutomationProfile.FromIdentity(account.AutomationProfileId); if (profile == null) { return new AjaxCallResult { Success = true, DisplayMessage = string.Empty }; } if (profile.CurrencyId == 0 || profile.CurrencyId == authData.CurrentOrganization.Currency.Identity) // uses presentation currency { return new AjaxCallResult { Success = true, DisplayMessage = profile.Name }; } return new AjaxCallResult { Success = true, DisplayMessage = profile.Name + " (" + Currency.FromIdentity(profile.CurrencyId).DisplayCode + ")" }; } [WebMethod] public static ReportedImportResults GetReportedImportResults (string guid) { AuthenticationData authData = GetAuthenticationDataAndCulture(); ReportedImportResults results = new ReportedImportResults(); ImportResultsCategory category = (ImportResultsCategory) GuidCache.Get (guid + "-Result"); ImportResults resultDetail = GuidCache.Get (guid + "-ResultDetails") as ImportResults; ImportedPaymentData paymentsDetail = GuidCache.Get (guid + "-ResultDetails") as ImportedPaymentData; string exceptionText = GuidCache.Get(guid + "-Exception") as string; string html = string.Empty; switch (category) { case ImportResultsCategory.Good: html = String.Format (Resources.Pages.Ledgers.UploadBankFiles_ResultsGood, resultDetail.TransactionsImported, resultDetail.DuplicateTransactions, resultDetail.EarliestTransaction, resultDetail.LatestTransaction); if (resultDetail.InitialBalanceCents != 0) { html += "
" + String.Format(Resources.Pages.Ledgers.UploadBankFiles_ResultsInitialBalanceSet, Currency.FromCode(resultDetail.InitialBalanceCurrencyCode).DisplayCode, resultDetail.InitialBalanceCents/100.0, authData.CurrentOrganization.FirstFiscalYear); if (resultDetail.CurrencyCode != resultDetail.InitialBalanceCurrencyCode) { // nonpresentation currency html += " " + String.Format( Resources.Pages.Ledgers.UploadBankFiles_ResultsInitialBalanceSetForeignCurrency, Currency.FromCode(resultDetail.CurrencyCode).DisplayCode, resultDetail.BalanceMismatchCents / 100.0); } html += ".
"; } break; case ImportResultsCategory.Questionable: html = String.Format (Resources.Pages.Ledgers.UploadBankFiles_ResultsQuestionable, resultDetail.TransactionsImported, resultDetail.DuplicateTransactions, Math.Abs (resultDetail.BalanceMismatchCents/100.0), resultDetail.CurrencyCode); break; case ImportResultsCategory.Bad: html = Resources.Pages.Ledgers.UploadBankFiles_ResultsBad + ""; break; case ImportResultsCategory.Payments: if (paymentsDetail.DuplicatePaymentCount > 0) { html = String.Format (Resources.Pages.Ledgers.UploadBankFiles_ResultsPaymentsWithDupes, paymentsDetail.PaymentGroupCount, paymentsDetail.PaymentCount, paymentsDetail.PaymentCentsTotal/100.0, paymentsDetail.Currency.Code, paymentsDetail.DuplicatePaymentGroupCount, paymentsDetail.DuplicatePaymentCount); } else { html = String.Format (Resources.Pages.Ledgers.UploadBankFiles_ResultsPayments, paymentsDetail.PaymentGroupCount, paymentsDetail.PaymentCount, paymentsDetail.PaymentCentsTotal/100.0, paymentsDetail.Currency.Code); } break; default: throw new NotImplementedException ("Unhandled ImportResultCategory"); } results.Html = html; results.Category = category.ToString(); return results; } private static void ProcessUploadThread (object args) { string guid = ((ProcessThreadArguments) args).Guid; BankFileType fileType = ((ProcessThreadArguments) args).FileType; Person currentUser = ((ProcessThreadArguments) args).CurrentUser; Organization organization = ((ProcessThreadArguments)args).Organization; FinancialAccount account = ((ProcessThreadArguments)args).Account; Documents documents = Documents.RecentFromDescription (guid); GuidCache.Set (guid + "-Progress", 1); // to make sure results aren't repeated from last file GuidCache.Set (guid + "-Result", ImportResultsCategory.Bad); // default - this is what happens if exception if (documents.Count != 1) { return; // abort } Document uploadedDoc = documents[0]; Currency accountCurrency = account.ForeignCurrency; Currency presentationCurrency = organization.Currency; try { ExternalBankData externalData = new ExternalBankData(); externalData.Profile = account.ExternalBankDataProfile; if (fileType == BankFileType.Unknown) { using (StreamReader reader = CreateReader(uploadedDoc, externalData.Profile.Encoding)) // Guarantees disposal of reader { try { throw new NotImplementedException(); // externalData.LoadData (reader, organization, accountCurrency); // catch here and set result to BAD ImportResults results = ProcessImportedData (externalData, (ProcessThreadArguments) args); GuidCache.Set (guid + "-ResultDetails", results); if (results.AccountBalanceMatchesBank || results.InitialBalanceCents != 0) { GuidCache.Set (guid + "-Result", ImportResultsCategory.Good); } else { GuidCache.Set (guid + "-Result", ImportResultsCategory.Questionable); } } catch (Exception e) { try { reader.BaseStream.Position = 0; // rewind stream to retry parse with different file type // Try a payment file instead ImportedPaymentData paymentData = ImportBankgiroSE(reader, currentUser, organization); // Apparently, we were successful GuidCache.Set(guid + "-Result", ImportResultsCategory.Payments); GuidCache.Set(guid + "-ResultDetails", paymentData); } catch (Exception innerException) { // rethrow the original exception throw e; } } } } if (fileType == BankFileType.AccountStatement) { using (TextReader reader = CreateReader(uploadedDoc, externalData.Profile.Encoding)) // Guarantees disposal of reader { throw new NotImplementedException(); // externalData.LoadData (reader, organization, accountCurrency); // catch here and set result to BAD ImportResults results = ProcessImportedData (externalData, (ProcessThreadArguments) args); GuidCache.Set (guid + "-ResultDetails", results); if (results.AccountBalanceMatchesBank) { GuidCache.Set (guid + "-Result", ImportResultsCategory.Good); } else { GuidCache.Set (guid + "-Result", ImportResultsCategory.Questionable); } } } else if (fileType == BankFileType.PaymentDetails) { // Get reader factory from ExternalBankData throw new NotImplementedException ("Need to implement new flexible payment reader structure"); // IBankDataPaymentsReader paymentsReader = externalData.GetPaymentsReader(); // then read } } catch (Exception e) { GuidCache.Set (guid + "-Exception", e.ToString()); } finally { GuidCache.Set (guid + "-Progress", 100); // only here may the caller fetch the results uploadedDoc.Delete(); // document no longer needed after processing, no matter the result } } static private StreamReader CreateReader(Document document, string encoding = "") { switch (encoding) { case "UTF-8": case "UTF8": return document.GetReader(Encoding.UTF8); default: // none specified return document.GetReader(1252); // Windows western 1 as default } } /* private void Submit_Click(object sender, EventArgs e) { bool fileWasUploaded = false; foreach (string fileInputID in Request.Files)F { UploadedFile file = UploadedFile.FromHttpPostedFile(Request.Files[fileInputID]); if (file.ContentLength > 0) { // TODO: PROCESS // file.SaveAs("c:\\temp\\" + file.GetName()); this.PanelFileTypeAccount.Visible = false; this.PanelResults.Visible = true; fileWasUploaded = true; // Interpret and then import the data ExternalBankData bankData = new ExternalBankData(); try { // Set initial progress to light up progress box. UpdateImportProgressBar(1); switch(this.HiddenFileType.Value) { case "Seb": bankData.Profile = ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); bankData.LoadData(new StreamReader(file.InputStream, Encoding.GetEncoding(1252)), this.CurrentOrganization); break; case "PayPal": bankData.Profile = ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.PaypalId); bankData.LoadData(new StreamReader(file.InputStream, Encoding.GetEncoding(1252)), this.CurrentOrganization); break; case "Payson": throw new NotImplementedException("Won't reimplement"); break; case "BankgiroSE": // Payment file, not transaction file ImportedPaymentData paymentData = ImportBankgiroSE(file.InputStream); PresentPaymentFileResults(paymentData); return; // Exit function here -- shortcut for when there's payment data and no transaction data default: throw new InvalidOperationException("File type value not set to a valid filter name"); } this.LabelProcessing.Text = bankData.Records.ToString(); ImportResults results = ProcessImportedData(bankData); if (results.AccountBalanceMatchesBank) { this.LiteralImportResults.Text = String.Format(Resources.Pages.Ledgers.UploadBankFiles_ImportResults, results.DuplicateTransactions + results.TransactionsImported, results.TransactionsImported, FinancialAccount.FromIdentity(Int32.Parse(this.DropAccounts.SelectedValue)) .Name, results.DuplicateTransactions); this.LabelImportResultsHeader.Text = Resources.Pages.Ledgers.UploadBankFiles_FileImportedHeader; } else { this.LiteralImportResults.Text = String.Format(Resources.Pages.Ledgers.UploadBankFiles_ErrorBalance, results.DuplicateTransactions + results.TransactionsImported, results.TransactionsImported, FinancialAccount.FromIdentity(Int32.Parse(this.DropAccounts.SelectedValue)) .Name, results.DuplicateTransactions); this.LabelImportResultsHeader.Text = Resources.Pages.Ledgers.UploadBankFiles_FileImportedHeader_ErrorBalance; } } catch (InvalidOperationException exception) { this.LiteralDownloadInstructionsModal.Text = exception.ToString(); // For debug purposes -- will not be shown to user this.PanelErrorImage.Visible = true; this.LabelImportResultsHeader.Text = Resources.Pages.Ledgers.UploadBankFiles_ImportError; this.LiteralImportResults.Text = Resources.Pages.Ledgers.UploadBankFiles_ErrorInterpretation; } } } if (!fileWasUploaded) { // If no file was uploaded, re-show the instructions div this.LabelNoFileUploaded.Text = Resources.Global.Global_Upload_ErrorSelectFile; this.LiteralDivInstructionsStyle.Text = @"style='display:inline'"; } else { this.LabelNoFileUploaded.Text = string.Empty; this.LiteralDivInstructionsStyle.Text = @"style='display:none'"; } }*/ /* private void PresentPaymentFileResults (ImportedPaymentData data) { string literalResult = String.Format(Resources.Pages.Ledgers.UploadBankFiles_PaymentSummary1, LocalizeCount(Resources.Pages.Ledgers.UploadBankFiles_PaymentCount, data.DuplicatePaymentCount + data.PaymentCount)) + " "; if (data.PaymentCount == 0 && data.DuplicatePaymentCount > 0) { literalResult += Resources.Pages.Ledgers.UploadBankFiles_PaymentAllDuplicates; } else if (data.PaymentCount > 0) { literalResult += String.Format(Resources.Pages.Ledgers.UploadBankFiles_PaymentSummary2, data.Currency.Code, data.PaymentCentsTotal/100.0, LocalizeCount(Resources.Pages.Ledgers.UploadBankFiles_PaymentCount, data.PaymentCount), LocalizeCount(Resources.Pages.Ledgers.UploadBankFiles_PaymentGroupCount, data.PaymentGroupCount)); if (data.DuplicatePaymentCount > 0) { literalResult += " " + String.Format(Resources.Pages.Ledgers.UploadBankFiles_PaymentSummaryDuplicates, LocalizeCount(Resources.Pages.Ledgers.UploadBankFiles_PaymentCount, data.DuplicatePaymentCount), LocalizeCount( Resources.Pages.Ledgers.UploadBankFiles_PaymentGroupCount, data.DuplicatePaymentGroupCount)); } } this.LiteralImportResults.Text = @"" + literalResult + @"
"; this.LabelImportResultsHeader.Text = Resources.Pages.Ledgers.UploadBankFiles_PaymentFileUploadedHeader; }*/ [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, "" /* new SHA256 field */, 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) { string contents = reader.ReadToEnd(); string[] lines = contents.Split ('\n'); DateTime timestamp = Constants.DateTimeLow; int bgMaxVersion = 0; ImportedPaymentData result = new ImportedPaymentData(); Currency currency = null; List