From 83a0720a1fc4c3447c03d05c91bce6d2abd7ac06 Mon Sep 17 00:00:00 2001 From: Rick Falkvinge Date: Thu, 31 Mar 2016 18:32:43 +0200 Subject: [PATCH] Fixed a lot of stuff in attestation. Some harmless debug code remains. --- Logic/Financial/CashAdvance.cs | 3 + Logic/Financial/ExpenseClaim.cs | 3 + Logic/Financial/FinancialAccount.cs | 138 +++++++++++++++++- Logic/Financial/InboundInvoice.cs | 5 + Logic/Financial/Salary.cs | 5 + Site5/Pages/v5/Financial/AttestCosts.aspx | 61 +++++--- Site5/Pages/v5/Financial/AttestCosts.aspx.cs | 120 ++------------- .../v5/Financial/Json-AttestableCosts.aspx.cs | 8 +- Site5/Pages/v5/Public/Initialize.aspx.cs | 2 +- 9 files changed, 214 insertions(+), 131 deletions(-) diff --git a/Logic/Financial/CashAdvance.cs b/Logic/Financial/CashAdvance.cs index 3ddbfe4c..f47b82c4 100644 --- a/Logic/Financial/CashAdvance.cs +++ b/Logic/Financial/CashAdvance.cs @@ -52,6 +52,9 @@ namespace Swarmops.Logic.Financial new CashAdvanceRequestedLogEntry (createdByPerson, forPerson, amountCents/100.0, budget, description), newAdvance); + // Clear a cache + FinancialAccount.ClearAttestationAdjustmentsCache (organization); + return newAdvance; } diff --git a/Logic/Financial/ExpenseClaim.cs b/Logic/Financial/ExpenseClaim.cs index ef773a0d..8001b3a7 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -78,6 +78,9 @@ namespace Swarmops.Logic.Financial new ExpenseClaimFiledLogEntry (claimer /*filing person*/, claimer /*beneficiary*/, amountCents/100.0, budget, description), newClaim); + // Clear a cache + FinancialAccount.ClearAttestationAdjustmentsCache(organization); + return newClaim; } diff --git a/Logic/Financial/FinancialAccount.cs b/Logic/Financial/FinancialAccount.cs index f5da4850..2f601e7f 100644 --- a/Logic/Financial/FinancialAccount.cs +++ b/Logic/Financial/FinancialAccount.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using Swarmops.Basic.Types.Financial; using Swarmops.Common.Enums; using Swarmops.Common.Generics; @@ -457,8 +458,13 @@ namespace Swarmops.Logic.Financial return SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget (Identity, year); } - public Int64 GetBudgetCents (int year) + public Int64 GetBudgetCents (int year = -1) { + if (year == -1) + { + year = DateTime.UtcNow.Year; + } + return (Int64) (SwarmDb.GetDatabaseForReading().GetFinancialAccountBudget (Identity, year)*100); } @@ -484,6 +490,7 @@ namespace Swarmops.Logic.Financial SwarmDb.GetDatabaseForWriting().SetFinancialAccountBudgetMonthly (Identity, year, month, amountCents); } + public static FinancialAccount Create (Organization organization, string newAccountName, FinancialAccountType accountType, FinancialAccount parentAccount) { @@ -503,5 +510,134 @@ namespace Swarmops.Logic.Financial { return FinancialAccounts.ThisAndBelow (this); } + + + static private Dictionary> _organizationBudgetAttestationSpaceLookup = + new Dictionary>(); + + public static Dictionary GetBudgetAttestationSpaceAdjustments(Organization organization) + { + // This function returns a dictionary for the cents that are either accounted for but not attested, + // or attested but accounted for, to be used to understand how much is really left in budget + + // Positive adjustment means more [cost] budget available, negative less [cost] budget available + + if (_organizationBudgetAttestationSpaceLookup.ContainsKey (organization.Identity)) + { + return _organizationBudgetAttestationSpaceLookup [organization.Identity]; + } + + // TODO: This is expensive research, we should cache this result and clear cache on any attestation or create op + + Dictionary result = new Dictionary(); + + // Cash advances are accounted for when paid out. Make sure they count toward the budget when attested. + + CashAdvances advances = CashAdvances.ForOrganization(organization); + foreach (CashAdvance advance in advances) + { + if (!result.ContainsKey(advance.BudgetId)) + { + result[advance.BudgetId] = 0; + } + + if (advance.Attested) + { + result[advance.BudgetId] -= advance.AmountCents; + } + } + + // Expense claims, Inbound invoices, and Salaries are accounted for when filed. Make sure they DON'T + // count toward the budget while they are NOT attested. + + ExpenseClaims claims = ExpenseClaims.ForOrganization(organization); // gets all open claims + foreach (ExpenseClaim claim in claims) + { + if (!result.ContainsKey(claim.BudgetId)) + { + result[claim.BudgetId] = 0; + } + + if (!claim.Attested) + { + result[claim.BudgetId] += claim.AmountCents; + } + } + + InboundInvoices invoices = InboundInvoices.ForOrganization(organization); + foreach (InboundInvoice invoice in invoices) + { + if (!result.ContainsKey(invoice.BudgetId)) + { + result[invoice.BudgetId] = 0; + } + + if (!invoice.Attested) + { + result[invoice.BudgetId] += invoice.AmountCents; + } + } + + Salaries salaries = Salaries.ForOrganization(organization); + foreach (Salary salary in salaries) + { + if (!result.ContainsKey(salary.PayrollItem.BudgetId)) + { + result[salary.PayrollItem.BudgetId] = 0; + } + + if (!salary.Attested) + { + result[salary.PayrollItem.BudgetId] += (salary.GrossSalaryCents + salary.AdditiveTaxCents); + } + } + + _organizationBudgetAttestationSpaceLookup[organization.Identity] = result; + + return result; + } + + public static void ClearAttestationAdjustmentsCache (Organization organization) + { + if (_organizationBudgetAttestationSpaceLookup.ContainsKey (organization.Identity)) + { + _organizationBudgetAttestationSpaceLookup.Remove (organization.Identity); + } + } + + + + public Int64 GetBudgetCentsRemaining(int year = -1) + { + if (year == -1) + { + year = DateTime.UtcNow.Year; + } + + if (this.AccountType != FinancialAccountType.Cost) + { + throw new NotImplementedException("The behavior of this function is undefined for revenue accounts"); + } + + Int64 deltaCentsYear = this.GetDeltaCents(new DateTime(year, 1, 1), + new DateTime(year + 1, 1, 1)); + Int64 budgetYear = this.GetBudgetCents(year); + + Dictionary adjustments = GetBudgetAttestationSpaceAdjustments (this.Organization); + + Int64 result = budgetYear; // start with the initial (negative) budget for a cost account + result += deltaCentsYear; // if money spent, that's a positive number in bookkeeping, and so should reduce neg number + // (bring it closer to zero). If result goes positive here, budget is overdrafted. + + if (adjustments.ContainsKey (this.Identity)) + { + // A positive adjustment means more available in the budget. As the (cost) budget is negative, we should reduce + // by this number. + + result -= adjustments[this.Identity]; + } + + return result; + } } } \ No newline at end of file diff --git a/Logic/Financial/InboundInvoice.cs b/Logic/Financial/InboundInvoice.cs index ed4b667b..42aacd21 100644 --- a/Logic/Financial/InboundInvoice.cs +++ b/Logic/Financial/InboundInvoice.cs @@ -201,6 +201,11 @@ namespace Swarmops.Logic.Financial new InboundInvoiceCreatedLogEntry (creatingPerson, supplier, description, amountCents/100.0, budget), newInvoice); + // Clear a cache + FinancialAccount.ClearAttestationAdjustmentsCache(organization); + + + return newInvoice; } diff --git a/Logic/Financial/Salary.cs b/Logic/Financial/Salary.cs index 6b88239c..fd253315 100644 --- a/Logic/Financial/Salary.cs +++ b/Logic/Financial/Salary.cs @@ -287,6 +287,11 @@ namespace Swarmops.Logic.Financial salary.TaxPaid = true; } + // Clear a cache + FinancialAccount.ClearAttestationAdjustmentsCache(payrollItem.Organization); + + + return salary; } diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx b/Site5/Pages/v5/Financial/AttestCosts.aspx index 410f7735..bd68b85d 100644 --- a/Site5/Pages/v5/Financial/AttestCosts.aspx +++ b/Site5/Pages/v5/Financial/AttestCosts.aspx @@ -18,6 +18,7 @@ preload([ '/Images/Abstract/ajaxloader-medium.gif', + '/Images/Abstract/ajaxloader-48x36px.gif', '/Images/Icons/iconshock-balloon-yes-128x96px-hot.png', '/Images/Icons/iconshock-balloon-yes-128x96px-disabled.png', '/Images/Icons/iconshock-balloon-yes-128x96px-hot-disabled.png', @@ -47,7 +48,9 @@ }, onLoadSuccess: function () { - $(".LocalIconApproval").attr("src", approvalOverdraftIcon); // initialize as disabled until budgets known + budgetRemainingLookup.attestabilityInitialized = false; + + $(".LocalIconApproval").attr("src", '/Images/Abstract/ajaxloader-48x36px.gif'); // initialize as rotating loader until budgets known $(".LocalIconApproved").attr("src", "/Images/Icons/iconshock-green-tick-128x96px.png").css("opacity", 0.5); $(".LocalIconDenied").attr("src", "/Images/Icons/iconshock-red-cross-circled-128x96px.png"); $(".LocalIconUndo").attr("src", "/Images/Icons/iconshock-balloon-undo-128x96px.png"); @@ -56,21 +59,25 @@ $(".LocalIconApproval, .LocalIconUndo, .LocalIconDenial").css("cursor", "pointer"); $(".LocalIconApproval").mouseover(function () { - if ($(this).attr("rel") != "loading") { - if ($(this).hasClass("LocalFundsInsufficient")) { - $(this).attr("src", approvalOverdraftIconHover); - } else { - $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px-hot.png"); + if (budgetRemainingLookup.attestabilityInitialized) { + if ($(this).attr("rel") != "loading") { + if ($(this).hasClass("LocalFundsInsufficient")) { + $(this).attr("src", approvalOverdraftIconHover); + } else { + $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px-hot.png"); + } } } }); $(".LocalIconApproval").mouseout(function () { - if ($(this).attr("rel") != "loading") { - if ($(this).hasClass("LocalFundsInsufficient")) { - $(this).attr("src", approvalOverdraftIcon); - } else { - $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px.png"); + if (budgetRemainingLookup.attestabilityInitialized) { + if ($(this).attr("rel") != "loading") { + if ($(this).hasClass("LocalFundsInsufficient")) { + $(this).attr("src", approvalOverdraftIcon); + } else { + $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px.png"); + } } } }); @@ -174,7 +181,7 @@ var accountId = $("#IconApproval" + baseid).attr("accountid"); var funds = parseFloat($("#IconApproval" + baseid).attr("amount")); - budgetRemainingLookup[accountId] += funds; + budgetRemainingLookup[accountId] -= funds; setAttestability(); recheckBudgets(); // will double-check budgets against server } else { @@ -219,11 +226,11 @@ // Check if budgets have been fetched, and if so, initialize attestability if (budgetRemainingLookup.budgetsLoaded == true) { - setAttestability(); - } + setAttestability(); + } - budgetRemainingLookup.rowsLoaded = true; - } + budgetRemainingLookup.rowsLoaded = true; + } } ); @@ -285,8 +292,9 @@ var accountId = $(this).attr("accountid"); var funds = parseFloat($(this).attr("amount")); - budgetRemainingLookup[accountId] -= funds; + budgetRemainingLookup[accountId] += funds; // plus because the budget is negative setAttestability(); + recheckBudgets(); // will double-check budgets against server } else { // failure, likely from attesting too quickly and overrunning budget @@ -307,6 +315,7 @@ SwarmopsJS.ajaxCall("/Pages/v5/Financial/AttestCosts.aspx/GetRemainingBudgets", {}, function(data) { data.forEach(function(accountData, dummy1, dummy2) { budgetRemainingLookup[accountData.AccountId] = accountData.Remaining; + console.log("Rechecking budget " + accountData.AccountId + ": remaining is " + accountData.Remaining); }); setAttestability(); @@ -319,19 +328,31 @@ $('.LocalIconApproval').each(function() { var accountId = $(this).attr('accountid'); var amountRequested = $(this).attr('amount'); + var fundsInBudget = -budgetRemainingLookup[accountId]; + + console.log("attestability checking accountid " + accountId + ", amount requested is " + amountRequested + ", funds in budget is " + fundsInBudget); - var fundsInBudget = budgetRemainingLookup[accountId]; if (fundsInBudget >= amountRequested) { + console.log("- removing insufficience marker"); $(this).removeClass("LocalFundsInsufficient"); if ($(this).attr("rel") != "loading") { $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px.png"); + } else { + $(this).attr("src", approvalOverdraftIcon); } } - else if (!$(this).hasClass("LocalFundsInsufficient")) { - $(this).addClass("LocalFundsInsufficient"); + else { if ($(this).attr("rel") != "loading") { $(this).attr("src", approvalOverdraftIcon); } + + if (!$(this).hasClass("LocalFundsInsufficient")) { + console.log("- adding insufficience marker"); + $(this).addClass("LocalFundsInsufficient"); + if ($(this).attr("rel") != "loading") { + $(this).attr("src", approvalOverdraftIcon); + } + } } }); diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx.cs b/Site5/Pages/v5/Financial/AttestCosts.aspx.cs index b1e6b789..869c440e 100644 --- a/Site5/Pages/v5/Financial/AttestCosts.aspx.cs +++ b/Site5/Pages/v5/Financial/AttestCosts.aspx.cs @@ -10,6 +10,7 @@ using System.Web; using System.Web.Services; using System.Web.UI; using Resources; +using Swarmops.Common.Enums; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; @@ -74,7 +75,10 @@ namespace Swarmops.Frontend.Pages.v5.Financial if (account.OwnerPersonId == authData.CurrentUser.Identity || (account.OwnerPersonId == 0 && authData.Authority.HasAccess (new Access (authData.CurrentOrganization, AccessAspect.Administration)))) { - result[account.Identity] = true; + if (account.AccountType == FinancialAccountType.Cost) + { + result[account.Identity] = true; + } } } @@ -229,7 +233,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial throw new UnauthorizedAccessException(); } - Int64 centsRemaining = GetBudgetRemaining (budget); + Int64 centsRemaining = budget.GetBudgetCentsRemaining(); if (centsRemaining/100.0 < amount) { @@ -280,17 +284,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial List result = new List(); int currentYear = DateTime.UtcNow.Year; - Dictionary budgetAdjustments = GetAccountingAdjustments (organization); foreach (int accountId in accountLookup.Keys) { FinancialAccount account = FinancialAccount.FromIdentity (accountId); - Int64 remaining = GetBudgetRemaining (account, currentYear); - - if (budgetAdjustments.ContainsKey (accountId)) - { - remaining += budgetAdjustments[accountId]; - } + Int64 remaining = account.GetBudgetCentsRemaining (currentYear); result.Add (new BudgetRemainder { AccountId = accountId, Remaining = remaining/100.0 }); } @@ -298,94 +296,6 @@ namespace Swarmops.Frontend.Pages.v5.Financial return result.ToArray(); } - private static Dictionary GetAccountingAdjustments (Organization organization) - { - // This function returns a dictionary for the cents that are either accounted for but not attested, - // or attested but accounted for, to be used to understand how much is really left in budget - - // Positive adjustment means more [cost] budget available, negative less [cost] budget available - - Dictionary result = new Dictionary(); - - // Cash advances are accounted for when paid out. Make sure they count toward the budget when attested. - - CashAdvances advances = CashAdvances.ForOrganization (organization); - foreach (CashAdvance advance in advances) - { - if (!result.ContainsKey (advance.BudgetId)) - { - result[advance.BudgetId] = 0; - } - - if (advance.Attested) - { - result[advance.BudgetId] -= advance.AmountCents; - } - } - - // Expense claims, Inbound invoices, and Salaries are accounted for when filed. Make sure they DON'T - // count toward the budget while they are NOT attested. - - ExpenseClaims claims = ExpenseClaims.ForOrganization (organization); // gets all open claims - foreach (ExpenseClaim claim in claims) - { - if (!result.ContainsKey(claim.BudgetId)) - { - result[claim.BudgetId] = 0; - } - - if (!claim.Attested) - { - result[claim.BudgetId] += claim.AmountCents; - } - } - - InboundInvoices invoices = InboundInvoices.ForOrganization (organization); - foreach (InboundInvoice invoice in invoices) - { - if (!result.ContainsKey(invoice.BudgetId)) - { - result[invoice.BudgetId] = 0; - } - - if (!invoice.Attested) - { - result[invoice.BudgetId] += invoice.AmountCents; - } - } - - Salaries salaries = Salaries.ForOrganization (organization); - foreach (Salary salary in salaries) - { - if (!result.ContainsKey(salary.PayrollItem.BudgetId)) - { - result[salary.PayrollItem.BudgetId] = 0; - } - - if (!salary.Attested) - { - result[salary.PayrollItem.BudgetId] += (salary.GrossSalaryCents + salary.AdditiveTaxCents); - } - } - - return result; - } - - private static Int64 GetBudgetRemaining (FinancialAccount account, int year = -1) - { - if (year == -1) - { - year = DateTime.UtcNow.Year; - } - - Int64 deltaCentsYear = account.GetDeltaCents(new DateTime(year, 1, 1), - new DateTime(year + 1, 1, 1)); - Int64 budgetYear = account.GetBudgetCents(year); - - Dictionary adjustments = GetAccountingAdjustments (account.Organization); - - return -(budgetYear - deltaCentsYear) + (adjustments.ContainsKey(account.Identity)? adjustments[account.Identity]: 0); - } public class BudgetRemainder { @@ -534,17 +444,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial if (mode == AttestationMode.Attestation) { - Int64 budgetRemaining = GetBudgetRemaining (attestableItem.Budget, DateTime.UtcNow.Year); - Dictionary budgetAdjustments = GetAccountingAdjustments (authData.CurrentOrganization); - - if (budgetAdjustments.ContainsKey (attestableItem.Budget.Identity)) - { - budgetRemaining += budgetAdjustments[attestableItem.Budget.Identity]; - } + Int64 budgetRemaining = attestableItem.Budget.GetBudgetCentsRemaining(); result = string.Empty; - if (amountCents > budgetRemaining) + if (amountCents > -budgetRemaining) { if ( authData.Authority.HasAccess (new Access (authData.CurrentOrganization, @@ -552,6 +456,10 @@ namespace Swarmops.Frontend.Pages.v5.Financial { // Admin rights, so allow (forced) overdraft + // Unless budget was nonzero and allocated, set protest message + + if (attestableItem.Budget.Owner != null || attestableItem.Budget.GetBudgetCents() != 0) + result = Resources.Pages.Financial.AttestCosts_Overdrafted + " "; } else @@ -583,6 +491,8 @@ namespace Swarmops.Frontend.Pages.v5.Financial throw new InvalidOperationException ("Unknown Attestation Mode: " + mode); } + FinancialAccount.ClearAttestationAdjustmentsCache (authData.CurrentOrganization); + return new AjaxCallResult {DisplayMessage = result, Success = true}; } diff --git a/Site5/Pages/v5/Financial/Json-AttestableCosts.aspx.cs b/Site5/Pages/v5/Financial/Json-AttestableCosts.aspx.cs index 63fd923c..9a67d7d5 100644 --- a/Site5/Pages/v5/Financial/Json-AttestableCosts.aspx.cs +++ b/Site5/Pages/v5/Financial/Json-AttestableCosts.aspx.cs @@ -9,7 +9,7 @@ using Swarmops.Logic.Swarm; public partial class Pages_v5_Finance_Json_AttestableCosts : DataV5Base { - private Dictionary _attestationRights; + private Dictionary _attestationRights; private AttestableItems _items; private AttestableItems _attestedItems; @@ -90,20 +90,20 @@ public partial class Pages_v5_Finance_Json_AttestableCosts : DataV5Base } - private Dictionary GetAttestationRights() + private Dictionary GetAttestationRights() { // Right now, this function is quite primitive. At some point in the future, it needs to take into // account that a budget may have several attesters. Right now, it just loops over all accounts and // checks the owner. - Dictionary result = new Dictionary(); + Dictionary result = new Dictionary(); FinancialAccounts accounts = FinancialAccounts.ForOrganization (CurrentOrganization); foreach (FinancialAccount account in accounts) { if (account.OwnerPersonId == CurrentUser.Identity) { - result[account.Identity] = true; + result[account.Identity] = account.GetBudgetCentsRemaining(); } } diff --git a/Site5/Pages/v5/Public/Initialize.aspx.cs b/Site5/Pages/v5/Public/Initialize.aspx.cs index 67dddc10..c9fca625 100644 --- a/Site5/Pages/v5/Public/Initialize.aspx.cs +++ b/Site5/Pages/v5/Public/Initialize.aspx.cs @@ -733,7 +733,7 @@ namespace Swarmops.Frontend.Pages.v5.Public Positions.CreateSysadminPositions(); Positions.CreateOrganizationDefaultPositions (Organization.Sandbox, PositionTitle.Default); } - catch (Exception e) + catch (Exception) { throw; }