diff --git a/Logic/Financial/AnnualReport.cs b/Logic/Financial/AnnualReport.cs index 0a50f121..98fed8b8 100644 --- a/Logic/Financial/AnnualReport.cs +++ b/Logic/Financial/AnnualReport.cs @@ -150,6 +150,7 @@ namespace Swarmops.Logic.Financial } aggregateLine.AccountTreeValues.ThisYear += reportLine.AccountTreeValues.ThisYear; + aggregateLine.AccountTreeValues.ThisYearBudget += reportLine.AccountTreeValues.ThisYearBudget; } } @@ -162,7 +163,8 @@ namespace Swarmops.Logic.Financial this.Totals = new AnnualReportNode(); this.Totals.PreviousYear = PopulateOneTotal (this._singleLookups[0]); - this.Totals.ThisYear = PopulateOneTotal (this._singleLookups[5]); + this.Totals.ThisYear = PopulateOneTotal(this._singleLookups[5]); + this.Totals.ThisYearBudget = PopulateOneTotal(this._singleLookups[6]); for (int quarter = 0; quarter < 4; quarter++) { @@ -186,8 +188,8 @@ namespace Swarmops.Logic.Financial newLine.AccountId = account.Identity; newLine.AccountName = account.Name; newLine.AccountType = account.AccountType; - newLine.AccountValues = CreateYearlyReportNode (account.Identity, this._singleLookups); - newLine.AccountTreeValues = CreateYearlyReportNode (account.Identity, this._treeLookups); + newLine.AccountValues = CreateAnnualReportNode (account.Identity, this._singleLookups); + newLine.AccountTreeValues = CreateAnnualReportNode (account.Identity, this._treeLookups); if (this._treeMap.ContainsKey (account.Identity)) { @@ -199,7 +201,7 @@ namespace Swarmops.Logic.Financial } - private AnnualReportNode CreateYearlyReportNode (int accountId, Dictionary[] lookup) + private AnnualReportNode CreateAnnualReportNode (int accountId, Dictionary[] lookup) { AnnualReportNode node = new AnnualReportNode(); node.PreviousYear = lookup[0][accountId]; @@ -210,6 +212,7 @@ namespace Swarmops.Logic.Financial } node.ThisYear = lookup[5][accountId]; + node.ThisYearBudget = lookup[6][accountId]; return node; } @@ -230,10 +233,12 @@ namespace Swarmops.Logic.Financial private void PopulateLookups (FinancialAccounts accounts) { - this._singleLookups = new Dictionary[6]; - this._treeLookups = new Dictionary[6]; + // Seven elements in each array: lastyear, q1, q2, q3, q4, thisyear, thisyearbudget - for (int index = 0; index < 6; index++) + this._singleLookups = new Dictionary[7]; + this._treeLookups = new Dictionary[7]; + + for (int index = 0; index < 7; index++) { this._treeLookups[index] = new Dictionary(); this._singleLookups[index] = new Dictionary(); @@ -252,6 +257,17 @@ namespace Swarmops.Logic.Financial foreach (FinancialAccount account in accounts) { + // If result account, find budget + + if (this._accountType == FinancialAccountType.Result) + { + this._singleLookups[6][account.Identity] = account.GetBudgetCents (this.Year); + } + else + { + this._singleLookups[6][account.Identity] = 0; // if balance account, this is zero + } + // Find this year's inbound if (this._accountType == FinancialAccountType.Result) @@ -300,7 +316,7 @@ namespace Swarmops.Logic.Financial // copy to treeLookups - for (int index = 0; index < 6; index++) + for (int index = 0; index < 7; index++) { this._treeLookups[index][account.Identity] = this._singleLookups[index][account.Identity]; } @@ -308,7 +324,7 @@ namespace Swarmops.Logic.Financial // 3) Add all children's values to parents - for (int index = 0; index < 6; index++) + for (int index = 0; index < 7; index++) { AddChildrenValuesToParents (this._treeLookups[index], accounts); } @@ -360,6 +376,7 @@ namespace Swarmops.Logic.Financial public Int64 PreviousYear; public Int64[] Quarters; public Int64 ThisYear; + public Int64 ThisYearBudget; public AnnualReportNode() { 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/Logic/Security/Authority.cs b/Logic/Security/Authority.cs index ae8e89a1..ef3db7fa 100644 --- a/Logic/Security/Authority.cs +++ b/Logic/Security/Authority.cs @@ -178,7 +178,10 @@ namespace Swarmops.Logic.Security private readonly AuthorityData _data; - + public bool IsIdentified + { + get { return (_data.PersonId > 0); } + } /// /// Determines if this Authority has a particular Access. diff --git a/Logic/Swarm/DashboardTodos.cs b/Logic/Swarm/DashboardTodos.cs index b9f75b34..ca90a087 100644 --- a/Logic/Swarm/DashboardTodos.cs +++ b/Logic/Swarm/DashboardTodos.cs @@ -15,15 +15,19 @@ namespace Swarmops.Logic.Swarm { DashboardTodos result = new DashboardTodos(); - result.AddBitcoinChecks (authority); + if (authority.IsIdentified) // exclude OpenLedgers and other anon identities + { - result.AddExpenseClaimAttestations(authority); - result.AddCashAdvanceAttestations(authority); - //result.AddSalaryAttestations(person, organization); TODO! - result.AddReceiptValidations(authority); - result.AddPayouts(authority); + result.AddBitcoinChecks (authority); - // TODO: Add any hooks + result.AddExpenseClaimAttestations (authority); + result.AddCashAdvanceAttestations (authority); + //result.AddSalaryAttestations(person, organization); TODO! + result.AddReceiptValidations (authority); + result.AddPayouts (authority); + + // TODO: Add any hooks + } return result; } diff --git a/Site5/App_GlobalResources/Global.resx b/Site5/App_GlobalResources/Global.resx index 5d7dc7e5..f15dbf89 100644 --- a/Site5/App_GlobalResources/Global.resx +++ b/Site5/App_GlobalResources/Global.resx @@ -717,4 +717,12 @@ Previous + + YTD + Try to keep short if there isn't an established shortform for "Year To Date", like "So far" or similar + + + Flags + As in a table column header + \ No newline at end of file diff --git a/Site5/App_GlobalResources/Menu5.resx b/Site5/App_GlobalResources/Menu5.resx index 1fc6b9bb..818bfda8 100644 --- a/Site5/App_GlobalResources/Menu5.resx +++ b/Site5/App_GlobalResources/Menu5.resx @@ -417,4 +417,7 @@ Donate Funds + + Budget vs Actual + \ No newline at end of file diff --git a/Site5/App_GlobalResources/Pages.Financial.resx b/Site5/App_GlobalResources/Pages.Financial.resx index eaad7470..3a5c9723 100644 --- a/Site5/App_GlobalResources/Pages.Financial.resx +++ b/Site5/App_GlobalResources/Pages.Financial.resx @@ -279,6 +279,9 @@ Salary #{0:N0} for {1} was DE-attested. It will not be paid out unless attested again. When somebody undoes a previous attestation. + + <strong>WARNING: UNINITIALIZED BUDGET</strong><br/><br/>The cost you're approving belongs to an uninitialized budget -- an account in the ledger that lacks owner and doesn't have a set budget allowance for the year. Consider visiting the Account Plan and allocating budgets for the expected revenue and expenses.<br/><br/>This message will only display once per visit to Attestations.<br/> + Invoice amount (in {0}) {0} is the organization's main currency. diff --git a/Site5/App_GlobalResources/Pages.Ledgers.resx b/Site5/App_GlobalResources/Pages.Ledgers.resx index 6ea91c46..4214c098 100644 --- a/Site5/App_GlobalResources/Pages.Ledgers.resx +++ b/Site5/App_GlobalResources/Pages.Ledgers.resx @@ -732,4 +732,14 @@ Payout #{0:N0}, {5} (expected {1:yyyy-MMM-dd}) for {2}: {3} {4:N2} 0 is the payout Id, 1 is the date (do edit format if called for in culture), 2 is the recipient name, and 3 4 is the currency and amount, 5 is the specification (like "Expense Claim #4711") + + Budget vs Actual + + + This page displays the budgeted breakdown compared to a breakdown of the actual outcome so far. + + + Budget vs Actual + Financial budget vs. Actual financial outcome + \ No newline at end of file diff --git a/Site5/MainMenu-v5-OpenLedgers.xml b/Site5/MainMenu-v5-OpenLedgers.xml index bfeca3ab..dc2bec5f 100644 --- a/Site5/MainMenu-v5-OpenLedgers.xml +++ b/Site5/MainMenu-v5-OpenLedgers.xml @@ -5,22 +5,32 @@ Ledgers_BalanceSheet - 3 + 0 /Pages/v5/Ledgers/BalanceSheet.aspx Link - + - Ledgers_ProfitLossStatement - 3 - - - /Pages/v5/Ledgers/ProfitLossStatement.aspx - Link - + Ledgers_ProfitLossStatement + 0 + + + /Pages/v5/Ledgers/ProfitLossStatement.aspx + Link + + + + + Ledgers_BudgetVsActual + 0 + + + /Pages/v5/Ledgers/BudgetActual.aspx + Link + diff --git a/Site5/MainMenu-v5.xml b/Site5/MainMenu-v5.xml index eeaf7199..d7e8ce8c 100644 --- a/Site5/MainMenu-v5.xml +++ b/Site5/MainMenu-v5.xml @@ -301,6 +301,17 @@ Submenu + + Ledgers_BudgetVsActual + 0 + + iconshock-abacus + /Pages/v5/Ledgers/BudgetActual.aspx + Link + + + + Ledgers_LiquidityForecast 3 diff --git a/Site5/Pages/v5/Admin/OrgSettings.aspx b/Site5/Pages/v5/Admin/OrgSettings.aspx index 56202021..9cb99772 100644 --- a/Site5/Pages/v5/Admin/OrgSettings.aspx +++ b/Site5/Pages/v5/Admin/OrgSettings.aspx @@ -106,6 +106,9 @@ if (orgSettings.AccountPaypal) { $('.paypalAccountField').show(); } + + $('#<%=this.TextOpenLedgersDomain.ClientID%>_TextInput').val(orgSettings.OpenLedgersDomain); + $('#<%=this.TextVanityDomain.ClientID%>_TextInput').val(orgSettings.VanityDomain); } var suppressSwitchResponse = false; diff --git a/Site5/Pages/v5/Admin/OrgSettings.aspx.cs b/Site5/Pages/v5/Admin/OrgSettings.aspx.cs index 7d75ce08..b09a2d52 100644 --- a/Site5/Pages/v5/Admin/OrgSettings.aspx.cs +++ b/Site5/Pages/v5/Admin/OrgSettings.aspx.cs @@ -135,6 +135,9 @@ namespace Swarmops.Frontend.Pages.v5.Admin result.ParticipantFinancials = org.ParticipantFinancialsEnabled; result.PaypalAccountAddress = org.PaypalAccountMailAddress; + result.OpenLedgersDomain = org.OpenLedgersDomain; + result.VanityDomain = org.VanityDomain; + // TODO: Add all the other fields return result; @@ -443,6 +446,9 @@ namespace Swarmops.Frontend.Pages.v5.Admin public bool AccountsVat; public bool ParticipantFinancials; public string PaypalAccountAddress; + + public string OpenLedgersDomain; + public string VanityDomain; } } } \ No newline at end of file diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx b/Site5/Pages/v5/Financial/AttestCosts.aspx index 410f7735..a415673d 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', @@ -31,6 +32,22 @@ '/Images/Icons/iconshock-balloon-undo-128x96px-hot.png' ]); + loadUninitializedBudgets(); // no need to wait for doc.ready to load operating params + + SwarmopsJS.ajaxCall("/Pages/v5/Financial/AttestCosts.aspx/GetRemainingBudgets", {}, function(data) { + data.forEach(function(accountData, dummy1, dummy2) { + budgetRemainingLookup[accountData.AccountId] = accountData.Remaining; + }); + + if (budgetRemainingLookup.rowsLoaded == true) { + setAttestability(); + } + + budgetRemainingLookup.budgetsLoaded = true; + }); + + // Doc.ready: + $(document).ready(function () { $('#TableAttestableCosts').datagrid( { @@ -47,7 +64,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 +75,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"); + } } } }); @@ -154,6 +177,13 @@ $(this).attr("rel", "loading"); $(this).attr("src", "/Images/Abstract/ajaxloader-48x36px.gif"); $("#IconApproved" + $(this).attr("baseid")).fadeTo(1000, 0.01); + + var baseid = $(this).attr("baseid"); + var accountId = $("#IconApproval" + baseid).attr("accountid"); + var funds = parseFloat($("#IconApproval" + baseid).attr("amount")); + budgetRemainingLookup[accountId] -= funds; + setAttestability(); + $.ajax({ type: "POST", url: "/Pages/v5/Financial/AttestCosts.aspx/Deattest", @@ -172,10 +202,6 @@ $('.row' + baseid).animate({ color: "#000" }, 100); alertify.log(msg.d.DisplayMessage); - var accountId = $("#IconApproval" + baseid).attr("accountid"); - var funds = parseFloat($("#IconApproval" + baseid).attr("amount")); - budgetRemainingLookup[accountId] += funds; - setAttestability(); recheckBudgets(); // will double-check budgets against server } else { $(this).attr("src", "/Images/Icons/iconshock-greentick-128x96px.png"); @@ -219,11 +245,11 @@ // Check if budgets have been fetched, and if so, initialize attestability if (budgetRemainingLookup.budgetsLoaded == true) { - setAttestability(); - } + setAttestability(); + } - budgetRemainingLookup.rowsLoaded = true; - } + budgetRemainingLookup.rowsLoaded = true; + } } ); @@ -236,18 +262,6 @@ }); - SwarmopsJS.ajaxCall("/Pages/v5/Financial/AttestCosts.aspx/GetRemainingBudgets", {}, function(data) { - data.forEach(function(accountData, dummy1, dummy2) { - budgetRemainingLookup[accountData.AccountId] = accountData.Remaining; - }); - - if (budgetRemainingLookup.rowsLoaded == true) { - setAttestability(); - } - - budgetRemainingLookup.budgetsLoaded = true; - }); - // If we're running with admin privileges, allow overdraft override if (canOverdraftBudgets) { @@ -261,6 +275,19 @@ $(approvalIcon).attr("rel", "loading"); $(approvalIcon).attr("src", "/Images/Abstract/ajaxloader-48x36px.gif"); $("#IconDenial" + $(approvalIcon).attr("baseid")).fadeTo(1000, 0.01).css("cursor", "default"); + + var baseid = $(approvalIcon).attr("baseid"); + var accountId = $("#IconApproval" + baseid).attr("accountid"); + var funds = parseFloat($("#IconApproval" + baseid).attr("amount")); + budgetRemainingLookup[accountId] += funds; + setAttestability(); + + if (budgetUninitializedLookup[accountId] == true && uninitializedPopupDisplayed == false) { + alertify.alert(decodeURIComponent('')); + uninitializedPopupDisplayed = true; + } + + $.ajax({ type: "POST", url: "/Pages/v5/Financial/AttestCosts.aspx/Attest", @@ -283,10 +310,6 @@ $('.row' + baseid).animate({ color: "#AAA" }, 400); alertify.success(msg.d.DisplayMessage); - var accountId = $(this).attr("accountid"); - var funds = parseFloat($(this).attr("amount")); - budgetRemainingLookup[accountId] -= funds; - setAttestability(); recheckBudgets(); // will double-check budgets against server } else { // failure, likely from attesting too quickly and overrunning budget @@ -307,31 +330,52 @@ 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(); }); } + function loadUninitializedBudgets() { + SwarmopsJS.ajaxCall("/Pages/v5/Financial/AttestCosts.aspx/GetUninitializedBudgets", {}, function(data) { + console.log(data); + data.forEach(function(accountData, dummy1, dummy2) { + budgetUninitializedLookup[accountData] = true; + // console.log("Rechecking budget " + accountData.AccountId + ": remaining is " + accountData.Remaining); + }); + }); + } + function setAttestability() { $('.LocalIconApproval').each(function() { var accountId = $(this).attr('accountid'); var amountRequested = $(this).attr('amount'); + var fundsInBudget = -budgetRemainingLookup[accountId]; - var fundsInBudget = budgetRemainingLookup[accountId]; - if (fundsInBudget >= amountRequested) { + // console.log("attestability checking accountid " + accountId + ", amount requested is " + amountRequested + ", funds in budget is " + fundsInBudget); + + if (fundsInBudget >= amountRequested || budgetUninitializedLookup[accountId] == true) { + // console.log("- removing insufficience marker"); $(this).removeClass("LocalFundsInsufficient"); if ($(this).attr("rel") != "loading") { $(this).attr("src", "/Images/Icons/iconshock-balloon-yes-128x96px.png"); } } - 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); + } + } } }); @@ -421,6 +465,8 @@ var recordId = ''; var accountId = 0; var budgetRemainingLookup = {}; + var budgetUninitializedLookup = {}; + var uninitializedPopupDisplayed = false; // The variable below is advisory for the UI - actual access control is done server-side var canOverdraftBudgets = ; diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx.cs b/Site5/Pages/v5/Financial/AttestCosts.aspx.cs index b1e6b789..76730191 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; @@ -67,20 +68,49 @@ namespace Swarmops.Frontend.Pages.v5.Financial // checks the owner. Dictionary result = new Dictionary(); - FinancialAccounts accounts = FinancialAccounts.ForOrganization (authData.CurrentOrganization); + FinancialAccounts accounts = FinancialAccounts.ForOrganization(authData.CurrentOrganization); foreach (FinancialAccount account in accounts) { - if (account.OwnerPersonId == authData.CurrentUser.Identity || - (account.OwnerPersonId == 0 && authData.Authority.HasAccess (new Access (authData.CurrentOrganization, AccessAspect.Administration)))) + 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; + } } } return result; } + [WebMethod] + public static int[] GetUninitializedBudgets() + { + AuthenticationData authData = GetAuthenticationDataAndCulture(); + + // This function finds the exceptional accounts that aren't initialized, to let a sysadmin approve expenses to them. + + List result = new List(); + FinancialAccounts accounts = FinancialAccounts.ForOrganization(authData.CurrentOrganization); + + foreach (FinancialAccount account in accounts) + { + if (account.AccountType == FinancialAccountType.Cost) + { + if (account.OwnerPersonId == 0 && + authData.Authority.HasAccess (new Access (authData.CurrentOrganization, + AccessAspect.Administration))) + { + result.Add (account.Identity); + } + } + } + + return result.ToArray(); + } + private void Localize() { PageTitle = Resources.Pages.Financial.AttestCosts_PageTitle; @@ -95,6 +125,8 @@ namespace Swarmops.Frontend.Pages.v5.Financial this.LabelGridHeaderRequested.Text = Resources.Pages.Financial.AttestCosts_GridHeader_Requested; this.LiteralErrorInsufficientBudget.Text = JavascriptEscape (Resources.Pages.Financial.AttestCosts_OutOfBudget); + this.LiteralWarnUnintializedBudget.Text = + JavascriptEscape (Resources.Pages.Financial.AttestCosts_Warn_UninitializedBudget); this.LabelDescribeDeny.Text = Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionDeny; this.LabelDescribeCorrect.Text = String.Format (Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionAmount, CurrentOrganization.Currency.DisplayCode); @@ -229,7 +261,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 +312,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 +324,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 +472,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 +484,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 +519,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/Ledgers/BudgetActual.aspx b/Site5/Pages/v5/Ledgers/BudgetActual.aspx new file mode 100644 index 00000000..679f0bdb --- /dev/null +++ b/Site5/Pages/v5/Ledgers/BudgetActual.aspx @@ -0,0 +1,113 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="BudgetActual.aspx.cs" Inherits="Pages_v5_Ledgers_BudgetActual" %> + + + + + + + +

<%= CurrentOrganization.Currency.DisplayCode %>
 Loading
 

+ + + + + + + + + + +
————
+
+ +
+ +

+ +
+
+ +
+
+ +
+ diff --git a/Site5/Pages/v5/Ledgers/BudgetActual.aspx.cs b/Site5/Pages/v5/Ledgers/BudgetActual.aspx.cs new file mode 100644 index 00000000..bb655ffa --- /dev/null +++ b/Site5/Pages/v5/Ledgers/BudgetActual.aspx.cs @@ -0,0 +1,64 @@ +using System; +using System.Globalization; +using Resources; +using Resources.Pages; +using Swarmops.Logic.Security; + +public partial class Pages_v5_Ledgers_BudgetActual : PageV5Base +{ + protected void Page_Load (object sender, EventArgs e) + { + if (!CurrentOrganization.IsEconomyEnabled) + { + Response.Redirect ("/Pages/v5/Financial/EconomyNotEnabled.aspx", true); + return; + } + + PageIcon = "iconshock-abacus"; + PageTitle = Ledgers.BudgetActual_PageTitle; + InfoBoxLiteral = Ledgers.BudgetActual_Info; + + // Security: If the org has open ledgers, then anyone may read. Otherwise, Financials.Read. + + if (!String.IsNullOrEmpty(CurrentOrganization.OpenLedgersDomain)) + { + PageAccessRequired = new Access(AccessAspect.Null, AccessType.Read); + } + else + { + PageAccessRequired = new Access(CurrentOrganization, AccessAspect.Financials, AccessType.Read); + } + + + if (!Page.IsPostBack) + { + int year = DateTime.Today.Year; + int firstFiscalYear = CurrentOrganization.FirstFiscalYear; + + while (year >= firstFiscalYear) + { + this.DropYears.Items.Add (year.ToString (CultureInfo.InvariantCulture)); + year--; + } + + Localize(); + } + + RegisterControl (EasyUIControl.DataGrid | EasyUIControl.Tree); + } + + private void Localize() + { + int year = DateTime.UtcNow.Year; + + this.LabelContentHeader.Text = string.Format (Ledgers.BudgetActual_ContentHeader, + CurrentOrganization.Name); + this.LiteralHeaderLastYearActual.Text = Global.Financial_Actuals + @" " + (year - 1).ToString(CultureInfo.InvariantCulture); + this.LiteralHeaderBudget.Text = Global.Financial_Budget + @" " + year.ToString(CultureInfo.InvariantCulture); ; + this.LiteralHeaderActual.Text = Global.Financial_Actuals + @" " + Global.Financial_YTD; + this.LiteralActual.Text = Global.Financial_Actuals; + this.LiteralBudget.Text = Global.Financial_Budget; + this.LiteralHeaderAccountName.Text = Ledgers.ProfitLossStatement_AccountName; + this.LiteralHeaderFlags.Text = Global.Global_Flags; + } +} \ No newline at end of file diff --git a/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx b/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx new file mode 100644 index 00000000..9d91194f --- /dev/null +++ b/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx @@ -0,0 +1 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-BudgetActualData.aspx.cs" Inherits="Pages_v5_Ledgers_Json_BudgetActualData" %> diff --git a/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx.cs b/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx.cs new file mode 100644 index 00000000..9a92763f --- /dev/null +++ b/Site5/Pages/v5/Ledgers/Json-BudgetActualData.aspx.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Resources.Pages; +using Swarmops.Common.Enums; +using Swarmops.Logic.Financial; + +public partial class Pages_v5_Ledgers_Json_BudgetActualData : DataV5Base +{ + private AuthenticationData _authenticationData; + private int _year = 2012; + + protected void Page_Load (object sender, EventArgs e) + { + // Get auth data + + this._authenticationData = GetAuthenticationDataAndCulture(); + + // Get current year + + this._year = DateTime.Today.Year; + + string yearParameter = Request.QueryString["Year"]; + + if (!string.IsNullOrEmpty (yearParameter)) + { + this._year = Int32.Parse (yearParameter); // will throw if non-numeric - don't matter for app + } + + AnnualReport report = AnnualReport.Create (CurrentOrganization, this._year, FinancialAccountType.Result); + LocalizeRoot (report.ReportLines); + + Response.ContentType = "application/json"; + + Response.Output.WriteLine ("{\"rows\": " + RecurseReport (report.ReportLines) + ", \"footer\": [" + + WriteFooter (report.Totals) + "]}"); + + Response.End(); + } + + + private void LocalizeRoot (List lines) + { + Dictionary localizeMap = new Dictionary(); + + localizeMap["%ASSET_ACCOUNTGROUP%"] = Resources.Global.Financial_Asset; + localizeMap["%DEBT_ACCOUNTGROUP%"] = Resources.Global.Financial_Debt; + localizeMap["%INCOME_ACCOUNTGROUP%"] = Resources.Global.Financial_Income; + localizeMap["%COST_ACCOUNTGROUP%"] = Resources.Global.Financial_Cost; + + foreach (AnnualReportLine line in lines) + { + if (localizeMap.ContainsKey (line.AccountName)) + { + line.AccountName = localizeMap[line.AccountName]; + } + } + } + + + private string WriteFooter (AnnualReportNode totals) + { + string result = string.Format ("\"name\":\"{0}\"", Ledgers.ProfitLossStatement_Results); + + result += string.Format(CultureInfo.CurrentCulture, ",\"lastYearActual\":\"{0:N0}\"", + (double)totals.PreviousYear / -100.0); + + result += string.Format(CultureInfo.CurrentCulture, ",\"yearBudget\":\"{0:N0}\"", (double)totals.ThisYearBudget / 100.0); + + result += string.Format(CultureInfo.CurrentCulture, ",\"yearActual\":\"{0:N0}\"", (double)totals.ThisYear / -100.0); + + return "{" + result + "}"; + } + + + private string RecurseReport (List reportLines) + { + List elements = new List(); + + foreach (AnnualReportLine line in reportLines) + { + string element = string.Format ("\"id\":\"{0}\",\"name\":\"{1}\"", line.AccountId, + JsonSanitize (line.AccountName)); + + if (line.Children.Count > 0) + { + element += ",\"lastYearActual\":" + + JsonDualString (line.AccountId, line.AccountTreeValues.PreviousYear, + line.AccountValues.PreviousYear); + + element += ",\"yearBudget\":" + + JsonDualString(line.AccountId, -line.AccountTreeValues.ThisYearBudget, -line.AccountValues.ThisYearBudget); + + element += ",\"yearActual\":" + + JsonDualString (line.AccountId, line.AccountTreeValues.ThisYear, line.AccountValues.ThisYear); + + + element += ",\"state\":\"closed\",\"children\":" + RecurseReport (line.Children); + } + else + { + element += string.Format (CultureInfo.CurrentCulture, ",\"lastYearActual\":\"{0:N0}\"", + (double) line.AccountValues.PreviousYear/-100.0); + + element += string.Format(CultureInfo.CurrentCulture, ",\"yearBudget\":\"{0:N0}\"", + (double)line.AccountValues.ThisYearBudget / 100.0); + + element += string.Format (CultureInfo.CurrentCulture, ",\"yearActual\":\"{0:N0}\"", + (double) line.AccountValues.ThisYear/-100.0); + } + + elements.Add ("{" + element + "}"); + } + + return "[" + String.Join (",", elements.ToArray()) + "]"; + } + + + private string JsonDualString (int accountId, Int64 treeValue, Int64 singleValue) + { + if (treeValue != 0 && singleValue == 0) + { + return string.Format (CultureInfo.CurrentCulture, + "\"Σ {1:N0} \"", + accountId, treeValue/-100.00); + } + return string.Format (CultureInfo.CurrentCulture, + "\"Σ {1:N0}{2:N0}\"", + accountId, treeValue/-100.0, singleValue/-100.0); + } +} \ No newline at end of file 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; }