From 365daaf3b2a1e4c555f27c438ba8a6c65d700fed Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Wed, 16 Apr 2014 09:15:15 +0000 Subject: [PATCH] Committing pre-Easter work on resync --- Logic/Financial/ExternalBankData.cs | 27 ++ Logic/Financial/ExternalBankDataProfile.cs | 18 ++ Logic/Financial/ExternalBankDataRecord.cs | 5 +- .../Pages/v5/Ledgers/Json-ResyncPreview.aspx | 1 + .../v5/Ledgers/Json-ResyncPreview.aspx.cs | 247 ++++++++++++++++++ .../v5/Ledgers/ResyncExternalAccount.aspx | 62 +++-- .../v5/Ledgers/ResyncExternalAccount.aspx.cs | 43 ++- .../Pages/v5/Ledgers/UploadBankFiles.aspx.cs | 73 +++--- 8 files changed, 390 insertions(+), 86 deletions(-) create mode 100644 Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx create mode 100644 Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx.cs diff --git a/Logic/Financial/ExternalBankData.cs b/Logic/Financial/ExternalBankData.cs index 8e88f71a..272e5a61 100644 --- a/Logic/Financial/ExternalBankData.cs +++ b/Logic/Financial/ExternalBankData.cs @@ -180,6 +180,19 @@ namespace Swarmops.Logic.Financial recordList.Add(newRecord); } + if (Profile.LatestTransactionLocation == LatestTransactionLocation.Top) + { + LatestAccountBalanceCents = recordList[0].AccountBalanceCents; + } + else if (Profile.LatestTransactionLocation == LatestTransactionLocation.Bottom) + { + LatestAccountBalanceCents = recordList [recordList.Count- 1].AccountBalanceCents; + } + else + { + throw new ArgumentException("LatestTransactionLocation is undefined"); + } + recordList.Sort(new ExternalBankDataRecord()); this.Records = recordList.ToArray(); @@ -187,5 +200,19 @@ namespace Swarmops.Logic.Financial public ExternalBankDataProfile Profile { get; set; } public ExternalBankDataRecord[] Records { get; private set; } + public long LatestAccountBalanceCents; + } + + + // Helper datakeeping classes for frontend below + + + public class ExternalBankMismatchingDateTime + { + public DateTime DateTime; + public int MasterTransactionCount; + public long MasterDeltaCents; + public int SwarmopsTransactionCount; + public long SwarmopsDeltaCents; } } diff --git a/Logic/Financial/ExternalBankDataProfile.cs b/Logic/Financial/ExternalBankDataProfile.cs index 3de98daf..8f7fd2a7 100644 --- a/Logic/Financial/ExternalBankDataProfile.cs +++ b/Logic/Financial/ExternalBankDataProfile.cs @@ -31,6 +31,8 @@ namespace Swarmops.Logic.Financial result.FieldNames[ExternalBankDataFieldName.AccountBalance] = "Saldo"; result.FieldNames[ExternalBankDataFieldName.NotUniqueId] = "Verifikationsnummer"; + result.LatestTransactionLocation = LatestTransactionLocation.Top; + return result; } @@ -51,6 +53,8 @@ namespace Swarmops.Logic.Financial result.FieldNames[ExternalBankDataFieldName.AccountBalance] = "Balance"; result.FieldNames[ExternalBankDataFieldName.UniqueId] = "Transaction ID"; + result.LatestTransactionLocation = LatestTransactionLocation.Top; + return result; } @@ -64,6 +68,7 @@ namespace Swarmops.Logic.Financial public Country Country { get; set; } public string Culture { get; set; } public string Currency { get; set; } + public LatestTransactionLocation LatestTransactionLocation; public Dictionary FieldNames { get; private set; } } @@ -84,4 +89,17 @@ namespace Swarmops.Logic.Financial TimeZone, Currency } + + public enum LatestTransactionLocation + { + Unknown = 0, + /// + /// Latest transaction is at the top of the file (the first record, meaning reverse chrono order). + /// + Top, + /// + /// Latest transaction is at the bottom of the file (last record, chrono order). + /// + Bottom + } } diff --git a/Logic/Financial/ExternalBankDataRecord.cs b/Logic/Financial/ExternalBankDataRecord.cs index 30cf4238..56b18429 100644 --- a/Logic/Financial/ExternalBankDataRecord.cs +++ b/Logic/Financial/ExternalBankDataRecord.cs @@ -44,11 +44,8 @@ namespace Swarmops.Logic.Financial string commentKey = Description.ToLowerInvariant(); string hashKey = NotUniqueId + commentKey + (TransactionNetCents / 100.0).ToString(CultureInfo.InvariantCulture) + (AccountBalanceCents / 100.0).ToString(CultureInfo.InvariantCulture) + - DateTime.ToString("yyyy-MM-dd-00-00-00"); + DateTime.ToString("yyyy-MM-dd-HH-mm-ss"); - // the 00-00-00 used to be hh-mm-ss but is replaced this way for backward hash compatibility - // maybe replace cleanly at a certain year to include seconds in hash or so - importKey = SHA1.Hash(hashKey).Replace(" ", ""); } diff --git a/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx b/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx new file mode 100644 index 00000000..527a8719 --- /dev/null +++ b/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx @@ -0,0 +1 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-ResyncPreview.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Ledgers.ResyncDataPreview" %> diff --git a/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx.cs b/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx.cs new file mode 100644 index 00000000..167505ac --- /dev/null +++ b/Site5/Pages/v5/Ledgers/Json-ResyncPreview.aspx.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using Swarmops.Basic.Enums; +using Swarmops.Logic.Financial; +using Swarmops.Logic.Security; + +namespace Swarmops.Frontend.Pages.v5.Ledgers +{ + public partial class ResyncDataPreview : DataV5Base + { + protected void Page_Load(object sender, EventArgs e) + { + _authenticationData = GetAuthenticationDataAndCulture(); + _year = DateTime.Today.Year; + + string guid = Request.QueryString["Guid"]; + + ExternalBankMismatchingDateTime[] mismatchArray = + (ExternalBankMismatchingDateTime[]) Session["LedgersResync" + guid + "MismatchArray"]; + + if (!_authenticationData.CurrentUser.HasAccess(new Access(_authenticationData.CurrentOrganization, AccessAspect.Bookkeeping, AccessType.Read))) + { + throw new UnauthorizedAccessException(); + } + + // TODO: Get and cache account tree and account balances + + Response.ContentType = "application/json"; + + string currentOrganizationCurrency = this.CurrentOrganization.Currency.Code; + + string response = string.Empty; + List items = new List(); + + foreach (ExternalBankMismatchingDateTime mismatch in mismatchArray) + { + string childrenString = string.Empty; // Room for next step here + + string rowId = mismatch.DateTime.ToString("yyyyMMddHHmmss"); + string rowName = mismatch.DateTime.ToString("yyyy-MMM-dd HH:mm:ss"); + + string swarmopsData = ((double) mismatch.SwarmopsDeltaCents/100.0).ToString("N2") + " " + + currentOrganizationCurrency; + + string masterData = ((double)mismatch.MasterDeltaCents / 100.0).ToString("N2") + " " + + currentOrganizationCurrency; + + string notes = "Diff: " + ((double)(mismatch.MasterDeltaCents - mismatch.SwarmopsDeltaCents) / 100.0).ToString("N2"); + + items.Add("{\"id\":\"" + rowId + "\",\"rowName\":\"" + rowName + "\",\"swarmopsData\":\"" + JsonSanitize(swarmopsData) + "\",\"masterData\":\"" + JsonSanitize(masterData) + "\",\"notes\":\"" + JsonSanitize(notes) + "\",\"state\":\"closed\",\"children\":[" + childrenString + "]}"); + } + + Response.Output.WriteLine("[" + String.Join(",", items.ToArray()) + "]"); + Response.End(); + } + + private int _year = 2012; + private CultureInfo _renderCulture; + private AuthenticationData _authenticationData; + private Dictionary _hashedAccounts; + + + private string GetAccountGroup (FinancialAccountType type, string localizedGroupName) + { + string childrenString = GetAccountsRecurse(type, 0); + + return "{\"id\":\"" + -((int) type) + "\",\"accountName\":\"" + JsonSanitize(localizedGroupName) + + "\",\"state\":\"open\",\"children\":[" + childrenString + "]}"; + } + + private string GetAccountsRecurse (FinancialAccountType accountType, int rootNodeId) + { + List childStrings = new List(); + + if (!_hashedAccounts.ContainsKey(rootNodeId)) + { + return string.Empty; + } + + if (_hashedAccounts [rootNodeId].Count == 1) + { + // No children + + return string.Empty; + } + + foreach (FinancialAccount account in _hashedAccounts[rootNodeId]) + { + if (account.Identity == rootNodeId || account.AccountType != accountType) + { + continue; + } + + string ownerString = " "; + if (account.AccountType == FinancialAccountType.Income || account.AccountType == FinancialAccountType.Cost) + { + if (account.OwnerPersonId != 0) + { + // TODO: add zoom, write capability + + ownerString = + "" + + JsonSanitize(Server.HtmlEncode(account.Owner.Canonical)) + ""; + } + else + { + // TODO: add write capability + + ownerString = + "" + + JsonSanitize(Server.HtmlEncode(Resources.Global.Global_NoOwner)) + ""; + } + } + + string grandChildren = GetAccountsRecurse(accountType, account.Identity); + if (!string.IsNullOrEmpty(grandChildren)) + { + grandChildren = ",\"state\":\"closed\",\"children\":[" + grandChildren + "]"; + } + + string editString = String.Format("", accountType.ToString().Substring(0,1), account.Identity); + + + childStrings.Add('{' + String.Format("\"id\":\"{0}\",\"accountName\":\"{1}\",\"owner\":\"{2}\",\"balance\":\"{3}\",\"budget\":\"{4}\",\"action\":\"{5}\"", + account.Identity, + Server.HtmlEncode(JsonSanitize(account.Name)), + ownerString, + _hashedAccounts[account.Identity].Count > 1 ? JsonDualString(account.Identity, _treeBalanceLookup[account.Identity], _singleBalanceLookup[account.Identity]) : (_singleBalanceLookup [account.Identity] / 100.0).ToString("N0"), + account.AccountType == FinancialAccountType.Income || account.AccountType == FinancialAccountType.Cost? + _hashedAccounts[account.Identity].Count > 1 ? (JsonDualString(account.Identity, _treeBudgetLookup[account.Identity], _singleBudgetLookup[account.Identity])) : + (_singleBudgetLookup[account.Identity] / 100.0).ToString("N0") : + string.Empty, + editString + ) + grandChildren + '}'); + } + + return String.Join(",", childStrings.ToArray()); + } + + private class DisplayedAccount + { + public string Name; + public int Identity; + }; + + private class DisplayedAccounts : List + { + // typedef + }; + + private Dictionary> _treeMap; + private Dictionary _singleBalanceLookup; + private Dictionary _treeBalanceLookup; + private Dictionary _singleBudgetLookup; + private Dictionary _treeBudgetLookup; + + + private void PopulateLookups(FinancialAccounts accounts) + { + _singleBalanceLookup = new Dictionary(); + _treeBalanceLookup = new Dictionary(); + _singleBudgetLookup = new Dictionary(); + _treeBudgetLookup = new Dictionary(); + + // 1) Actually, the accounts are already sorted. Or are supposed to be, anyway, + // since FinancialAccounts.ForOrganization gets the _tree_ rather than the flat list. + + // 2) Add all values to the accounts. + + foreach (FinancialAccount account in accounts) + { + // Get current balances + + // TODO: There must be a more optimized way to do this, like with a database optimization. This + // is a HORRIBLY expensive operation, as it performs one complex database query PER ACCOUNT. + + if (account.AccountType == FinancialAccountType.Cost || account.AccountType == FinancialAccountType.Income) + { + _singleBalanceLookup[account.Identity] = -account.GetDeltaCents(new DateTime(_year, 1, 1), + new DateTime(_year + 1, 1, 1)); + _singleBudgetLookup[account.Identity] = account.GetBudgetCents(_year); + } + else if (account.AccountType == FinancialAccountType.Asset || account.AccountType == FinancialAccountType.Debt) + { + _singleBalanceLookup[account.Identity] = account.GetDeltaCents(new DateTime(1900, 1, 1), + new DateTime(_year + 1, 1, 1)); + _singleBudgetLookup[account.Identity] = 0; // balance accounts don't have budgets + } + else + { + throw new InvalidOperationException("Account with invalid type encountered - " + account.AccountType.ToString()); + } + + // copy to treeLookups + + _treeBalanceLookup[account.Identity] = _singleBalanceLookup[account.Identity]; + _treeBudgetLookup[account.Identity] = _singleBudgetLookup[account.Identity]; + } + + // 3) Add all children's values to parents + + AddChildrenValuesToParents(_treeBalanceLookup, accounts); + AddChildrenValuesToParents(_treeBudgetLookup, accounts); + + // Done. + } + + + private void AddChildrenValuesToParents(Dictionary lookup, FinancialAccounts accounts) + { + // Iterate backwards and add any value to its parent's value, as they are sorted in tree order. + + for (int index = accounts.Count - 1; index >= 0; index--) + { + int parentFinancialAccountId = accounts[index].ParentFinancialAccountId; + int accountId = accounts[index].Identity; + + if (parentFinancialAccountId != 0) + { + lookup[parentFinancialAccountId] += lookup[accountId]; + } + } + } + + + + private string JsonDualString(int accountId, Int64 treeValue, Int64 singleValue) + { + if (treeValue != 0 && singleValue == 0) + { + return string.Format(_renderCulture, + "Σ {1:N0} ", + accountId, treeValue / 100.00); + } + return string.Format(_renderCulture, + "Σ {1:N0}{2:N0}", + accountId, treeValue / 100.0, singleValue / 100.0); + } + + } +} \ No newline at end of file diff --git a/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx b/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx index 88fc57eb..6a0d2a2a 100644 --- a/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx +++ b/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx @@ -15,8 +15,9 @@ $(document).ready(function () { - $('#tableProfitLoss').treegrid( + $('#tableResyncPreview').treegrid( { + /* onBeforeExpand: function (foo) { $('span.profitlossdata-collapsed-' + foo.id).fadeOut('fast', function () { $('span.profitlossdata-expanded-' + foo.id).fadeIn('slow'); @@ -28,7 +29,7 @@ $('span.profitlossdata-collapsed-' + foo.id).fadeIn('slow'); }); }, - + onLoadSuccess: function () { $('div.datagrid').css('opacity', 1); $('#imageLoadIndicator').hide(); @@ -54,7 +55,7 @@ } $('span.commonHeader').show(); - } + }*/ }); $('#<%=DropAccounts.ClientID %>').change(function () { @@ -74,8 +75,6 @@ $('#tableProfitLoss').treegid('reload'); }); - - $('div.datagrid').css('opacity', 0.4); }); function uploadCompletedCallback() { @@ -111,7 +110,10 @@ { width: "100%" }, { queue: false }); - $(".buttonNext").click(); + $("#tableResyncPreview").treegrid( + {url: 'Json-ResyncPreview.aspx?Guid=<%= this.UploadFile.GuidString %>'}); + $('#DivStepPreview').fadeIn(); + $('#DivStepProcessing').slideUp(); } else { // We're not done yet. Keep the progress bar on-screen and keep re-checking. @@ -189,30 +191,34 @@ -

Step 3/4: Comparison results - Resync?

+ -

Resynchronization complete

- - - - - - - - - - - - - -
——————
+ + + diff --git a/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx.cs b/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx.cs index 9599e69f..4d620696 100644 --- a/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx.cs +++ b/Site5/Pages/v5/Ledgers/ResyncExternalAccount.aspx.cs @@ -80,7 +80,7 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers - [WebMethod(true)] + [WebMethod(EnableSession = true)] public static int GetProcessingProgress(string guid) { // Get data from static variables @@ -92,7 +92,21 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers return 0; } - return (int)_staticDataLookup[key]; + lock (_staticDataLookup) + { + int percentReady = (int)_staticDataLookup[key]; + + if (percentReady >= 100) + { + // copy result from static class-scope variable to session-scope variable + HttpContext.Current.Session["LedgersResync" + guid + "MismatchArray"] = + _staticDataLookup[guid + "MismatchArray"]; + + _staticDataLookup[guid + "MismatchArray"] = null; // clear the static object, which will otherwise live on + } + + return percentReady; + } } [WebMethod(true)] @@ -256,23 +270,26 @@ namespace Swarmops.Frontend.Pages.v5.Ledgers int percentProcessed = (int) (currentRecordIndex*100L/externalData.Records.Length); - if (percentProcessed > 1) + lock (_staticDataLookup) { - _staticDataLookup[guid + "PercentRead"] = percentProcessed; // for the progress bar to update async + if (percentProcessed > 1) + { + _staticDataLookup[guid + "PercentRead"] = percentProcessed; + // for the progress bar to update async + } + + if (percentProcessed > 99) + { + // Placed inside loop to have a contiguous lock block, even though it decreases performance. + // Should normally be placed just outside. + _staticDataLookup[guid + "MismatchArray"] = mismatchList.ToArray(); + } } } + } private static Dictionary _staticDataLookup; } - - public class ExternalBankMismatchingDateTime - { - public DateTime DateTime; - public int MasterTransactionCount; - public long MasterDeltaCents; - public int SwarmopsTransactionCount; - public long SwarmopsDeltaCents; - } } \ No newline at end of file diff --git a/Site5/Pages/v5/Ledgers/UploadBankFiles.aspx.cs b/Site5/Pages/v5/Ledgers/UploadBankFiles.aspx.cs index 0766a123..47df5a14 100644 --- a/Site5/Pages/v5/Ledgers/UploadBankFiles.aspx.cs +++ b/Site5/Pages/v5/Ledgers/UploadBankFiles.aspx.cs @@ -229,7 +229,7 @@ namespace Swarmops.Site.Pages.Ledgers // Interpret and then import the data - ImportedBankData bankData = null; + ExternalBankData bankData = new ExternalBankData(); try { @@ -240,13 +240,15 @@ namespace Swarmops.Site.Pages.Ledgers switch(this.HiddenFileType.Value) { case "Seb": - bankData = ImportSebText(file.InputStream); + bankData.Profile = ExternalBankDataProfile.FromIdentity(ExternalBankDataProfile.SESebId); + bankData.LoadData(new StreamReader(file.InputStream, Encoding.GetEncoding(1252)), this.CurrentOrganization); break; case "PayPal": - bankData = ImportPaypal(file.InputStream); + throw new NotImplementedException("Todo - fix after Easter"); + // bankData = ImportPaypal(file.InputStream); break; case "Payson": - bankData = ImportPayson(file.InputStream); + throw new NotImplementedException("Won't reimplement"); break; case "BankgiroSE": // Payment file, not transaction file ImportedPaymentData paymentData = ImportBankgiroSE(file.InputStream); @@ -256,7 +258,7 @@ namespace Swarmops.Site.Pages.Ledgers throw new InvalidOperationException("File type value not set to a valid filter name"); } - this.LabelProcessing.Text = bankData.Rows.Count.ToString(); + this.LabelProcessing.Text = bankData.Records.ToString(); ImportResults results = ProcessImportedData(bankData); if (results.AccountBalanceMatchesBank) @@ -360,7 +362,7 @@ namespace Swarmops.Site.Pages.Ledgers } - protected ImportResults ProcessImportedData(ImportedBankData import) + protected ImportResults ProcessImportedData(ExternalBankData import) { FinancialAccount assetAccount = FinancialAccount.FromIdentity(Int32.Parse(this.DropAccounts.SelectedValue)); FinancialAccount autoDepositAccount = this.CurrentOrganization.FinancialAccounts.IncomeDonations; @@ -368,21 +370,21 @@ namespace Swarmops.Site.Pages.Ledgers ImportResults result = new ImportResults(); int count = 0; - int progressUpdateInterval = import.Rows.Count/40; + int progressUpdateInterval = import.Records.Length/40; if (progressUpdateInterval > 100) { progressUpdateInterval = 100; } - foreach (ImportedBankRow row in import.Rows) + foreach (ExternalBankDataRecord row in import.Records) { // Update progress. count++; if (progressUpdateInterval < 2 || count % progressUpdateInterval == 0) { - int percent = (count*99)/import.Rows.Count; + int percent = (count*99)/import.Records.Length; UpdateImportProgressBar(percent); } @@ -399,41 +401,30 @@ namespace Swarmops.Site.Pages.Ledgers } - // Each row is at least a stub, probably more. + string importKey = row.ImportHash; - string importKey = row.SuppliedTransactionId; - - // If importKey is empty, construct a hash from the data fields. - - if (string.IsNullOrEmpty(importKey)) - { - string commentKey = row.Comment; - if (row.DateTime.Year >= 2012) - { - commentKey = commentKey.ToLowerInvariant(); - } - - string hashKey = row.HashBase + commentKey + (row.AmountCentsNet / 100.0).ToString(CultureInfo.InvariantCulture) + (row.CurrentBalanceCents / 100.0).ToString(CultureInfo.InvariantCulture) + - row.DateTime.ToString("yyyy-MM-dd-hh-mm-ss"); - - importKey = SHA1.Hash(hashKey).Replace(" ", ""); - } - - if (importKey.Length > 30) - { - importKey = importKey.Substring(0, 30); - } - - Int64 amountCents = row.AmountCentsNet; + Int64 amountCents = row.TransactionNetCents; if (amountCents == 0) { - amountCents = row.AmountCentsGross; + amountCents = row.TransactionGrossCents; + } + + if (this.CurrentOrganization.Identity == 1 && assetAccount.Identity == 1 && this.CurrentOrganization.Name == "Piratpartiet SE") + { + // This is an ugly-as-fuck hack that sorts under the category "just bring our pilots the fuck back to operational + // status right fucking now". + + if (row.DateTime < new DateTime(2014,03,22)) + { + result.DuplicateTransactions++; + continue; + } } FinancialTransaction transaction = FinancialTransaction.ImportWithStub(this.CurrentOrganization.Identity, row.DateTime, assetAccount.Identity, amountCents, - row.Comment, importKey, + row.Description, importKey, this.CurrentUser.Identity); if (transaction != null) @@ -442,7 +433,7 @@ namespace Swarmops.Site.Pages.Ledgers result.TransactionsImported++; - FinancialAccounts accounts = FinancialAccounts.FromBankTransactionTag(row.Comment); + FinancialAccounts accounts = FinancialAccounts.FromBankTransactionTag(row.Description); if (accounts.Count == 1) { @@ -461,13 +452,13 @@ namespace Swarmops.Site.Pages.Ledgers geography.Identity, 0, transaction.Identity, localAccount.Identity.ToString()); } - else if (row.Comment.ToLowerInvariant().StartsWith(this.CurrentOrganization.IncomingPaymentTag)) + else if (row.Description.ToLowerInvariant().StartsWith(this.CurrentOrganization.IncomingPaymentTag)) { // Check for previously imported payment group PaymentGroup group = PaymentGroup.FromTag(this.CurrentOrganization, "SEBGM" + DateTime.Today.Year.ToString() + // TODO: Get tags from org - row.Comment.Substring(this.CurrentOrganization.IncomingPaymentTag.Length).Trim()); + row.Description.Substring(this.CurrentOrganization.IncomingPaymentTag.Length).Trim()); if (group != null && group.Open) { @@ -490,7 +481,7 @@ namespace Swarmops.Site.Pages.Ledgers // This is always an autodeposit, if there is a fee (which is never > 0.0) transaction.AddRow(this.CurrentOrganization.FinancialAccounts.CostsBankFees, -row.FeeCents, this.CurrentUser); - transaction.AddRow(autoDepositAccount, -row.AmountCentsGross, this.CurrentUser); + transaction.AddRow(autoDepositAccount, -row.TransactionGrossCents, this.CurrentUser); } else if (amountCents < autoDepositLimit * 100) { @@ -519,7 +510,7 @@ namespace Swarmops.Site.Pages.Ledgers 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.CurrentBalanceCents) + if (databaseAccountBalanceCents - beyondEofCents == import.LatestAccountBalanceCents) { Payouts.AutomatchAgainstUnbalancedTransactions(this.CurrentOrganization); result.AccountBalanceMatchesBank = true;