This commit is contained in:
Rick Falkvinge
2016-04-03 19:53:46 +02:00
24 changed files with 702 additions and 179 deletions
+26 -9
View File
@@ -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<int, Int64>[] lookup)
private AnnualReportNode CreateAnnualReportNode (int accountId, Dictionary<int, Int64>[] 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<int, Int64>[6];
this._treeLookups = new Dictionary<int, Int64>[6];
// Seven elements in each array: lastyear, q1, q2, q3, q4, thisyear, thisyearbudget
for (int index = 0; index < 6; index++)
this._singleLookups = new Dictionary<int, Int64>[7];
this._treeLookups = new Dictionary<int, Int64>[7];
for (int index = 0; index < 7; index++)
{
this._treeLookups[index] = new Dictionary<int, Int64>();
this._singleLookups[index] = new Dictionary<int, Int64>();
@@ -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()
{
+3
View File
@@ -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;
}
+3
View File
@@ -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;
}
+137 -1
View File
@@ -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<int, Dictionary<int, Int64>> _organizationBudgetAttestationSpaceLookup =
new Dictionary<int, Dictionary<int, long>>();
public static Dictionary<int, Int64> 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<int, Int64> result = new Dictionary<int, long>();
// 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<int, Int64> 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;
}
}
}
+5
View File
@@ -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;
}
+5
View File
@@ -287,6 +287,11 @@ namespace Swarmops.Logic.Financial
salary.TaxPaid = true;
}
// Clear a cache
FinancialAccount.ClearAttestationAdjustmentsCache(payrollItem.Organization);
return salary;
}
+4 -1
View File
@@ -178,7 +178,10 @@ namespace Swarmops.Logic.Security
private readonly AuthorityData _data;
public bool IsIdentified
{
get { return (_data.PersonId > 0); }
}
/// <summary>
/// Determines if this Authority has a particular Access.
+11 -7
View File
@@ -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;
}
+8
View File
@@ -717,4 +717,12 @@
<data name="Global_WizardPrevious" xml:space="preserve">
<value>Previous</value>
</data>
<data name="Financial_YTD" xml:space="preserve">
<value>YTD</value>
<comment>Try to keep short if there isn't an established shortform for "Year To Date", like "So far" or similar</comment>
</data>
<data name="Global_Flags" xml:space="preserve">
<value>Flags</value>
<comment>As in a table column header</comment>
</data>
</root>
+3
View File
@@ -417,4 +417,7 @@
<data name="Menu5_Financial_DonateFunds" xml:space="preserve">
<value>Donate Funds</value>
</data>
<data name="Menu5_Ledgers_BudgetVsActual" xml:space="preserve">
<value>Budget vs Actual</value>
</data>
</root>
@@ -279,6 +279,9 @@
<value>Salary #{0:N0} for {1} was DE-attested. It will not be paid out unless attested again.</value>
<comment>When somebody undoes a previous attestation.</comment>
</data>
<data name="AttestCosts_Warn_UninitializedBudget" xml:space="preserve">
<value>&lt;strong&gt;WARNING: UNINITIALIZED BUDGET&lt;/strong&gt;&lt;br/&gt;&lt;br/&gt;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.&lt;br/&gt;&lt;br/&gt;This message will only display once per visit to Attestations.&lt;br/&gt;</value>
</data>
<data name="CreateInboundInvoice_Amount" xml:space="preserve">
<value>Invoice amount (in {0})</value>
<comment>{0} is the organization's main currency.</comment>
@@ -732,4 +732,14 @@
<value>Payout #{0:N0}, {5} (expected {1:yyyy-MMM-dd}) for {2}: {3} {4:N2}</value>
<comment>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")</comment>
</data>
<data name="BudgetActual_ContentHeader" xml:space="preserve">
<value>Budget vs Actual</value>
</data>
<data name="BudgetActual_Info" xml:space="preserve">
<value>This page displays the budgeted breakdown compared to a breakdown of the actual outcome so far.</value>
</data>
<data name="BudgetActual_PageTitle" xml:space="preserve">
<value>Budget vs Actual</value>
<comment>Financial budget vs. Actual financial outcome</comment>
</data>
</root>
+19 -9
View File
@@ -5,22 +5,32 @@
<MainMenuItem>
<ResourceKey>Ledgers_BalanceSheet</ResourceKey>
<UserLevel>3</UserLevel>
<UserLevel>0</UserLevel>
<Permissions />
<ImageUrl />
<NavigateUrl>/Pages/v5/Ledgers/BalanceSheet.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
<MainMenuItem>
<ResourceKey>Ledgers_ProfitLossStatement</ResourceKey>
<UserLevel>3</UserLevel>
<Permissions />
<ImageUrl />
<NavigateUrl>/Pages/v5/Ledgers/ProfitLossStatement.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
<ResourceKey>Ledgers_ProfitLossStatement</ResourceKey>
<UserLevel>0</UserLevel>
<Permissions />
<ImageUrl />
<NavigateUrl>/Pages/v5/Ledgers/ProfitLossStatement.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
<MainMenuItem>
<ResourceKey>Ledgers_BudgetVsActual</ResourceKey>
<UserLevel>0</UserLevel>
<Permissions />
<ImageUrl />
<NavigateUrl>/Pages/v5/Ledgers/BudgetActual.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
<MainMenuItem>
+11
View File
@@ -301,6 +301,17 @@
<Type>Submenu</Type>
<Children>
<MainMenuItem>
<ResourceKey>Ledgers_BudgetVsActual</ResourceKey>
<UserLevel>0</UserLevel>
<Permissions />
<ImageUrl>iconshock-abacus</ImageUrl>
<NavigateUrl>/Pages/v5/Ledgers/BudgetActual.aspx</NavigateUrl>
<Type>Link</Type>
<Children />
</MainMenuItem>
<MainMenuItem>
<ResourceKey>Ledgers_LiquidityForecast</ResourceKey>
<UserLevel>3</UserLevel>
+3
View File
@@ -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;
+6
View File
@@ -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;
}
}
}
+85 -39
View File
@@ -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('<asp:Literal id="LiteralWarnUnintializedBudget" runat="server" />'));
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 = <asp:Literal ID="LiteralCanOverdraftBudgets" runat="server" />;
+46 -108
View File
@@ -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<int, bool> result = new Dictionary<int, bool>();
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<int> result = new List<int>();
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<BudgetRemainder> result = new List<BudgetRemainder>();
int currentYear = DateTime.UtcNow.Year;
Dictionary<int, Int64> 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<int, Int64> 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<int, Int64> result = new Dictionary<int, long>();
// 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<int, Int64> 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<int, Int64> 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};
}
@@ -9,7 +9,7 @@ using Swarmops.Logic.Swarm;
public partial class Pages_v5_Finance_Json_AttestableCosts : DataV5Base
{
private Dictionary<int, bool> _attestationRights;
private Dictionary<int, Int64> _attestationRights;
private AttestableItems _items;
private AttestableItems _attestedItems;
@@ -90,20 +90,20 @@ public partial class Pages_v5_Finance_Json_AttestableCosts : DataV5Base
}
private Dictionary<int, bool> GetAttestationRights()
private Dictionary<int, Int64> 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<int, bool> result = new Dictionary<int, bool>();
Dictionary<int, Int64> result = new Dictionary<int, Int64>();
FinancialAccounts accounts = FinancialAccounts.ForOrganization (CurrentOrganization);
foreach (FinancialAccount account in accounts)
{
if (account.OwnerPersonId == CurrentUser.Identity)
{
result[account.Identity] = true;
result[account.Identity] = account.GetBudgetCentsRemaining();
}
}
+113
View File
@@ -0,0 +1,113 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="BudgetActual.aspx.cs" Inherits="Pages_v5_Ledgers_BudgetActual" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<script type="text/javascript">
$(document).ready(function () {
$('#tableBudgetActual').treegrid(
{
onBeforeExpand: function (foo) {
$('span.budgetactualdata-collapsed-' + foo.id).fadeOut('fast', function () {
$('span.budgetactualdata-expanded-' + foo.id).fadeIn('slow');
});
},
onBeforeCollapse: function (foo) {
$('span.budgetactualdata-expanded-' + foo.id).fadeOut('fast', function () {
$('span.budgetactualdata-collapsed-' + foo.id).fadeIn('slow');
});
},
onLoadSuccess: function () {
$('div.datagrid').css('opacity', 1);
$('#imageLoadIndicator').hide();
$('span.loadingHeader').hide();
$('span.allYearsHeader').show();
var selectedYear = $('#<%=DropYears.ClientID %>').val();
if (selectedYear == currentYear)
{
$('span.previousYearsHeader').hide();
$('span.currentYearHeader').show();
}
else
{
$('#previousLastActual').text(actualLoc + ' ' + (selectedYear - 1));
$('#previousBudget').text(budgetLoc + ' ' + selectedYear);
$('#previousYtd').text(actualLoc + ' ' + selectedYear);
$('span.currentYearHeader').hide();
$('span.previousYearsHeader').show();
}
}
});
$('#<%=DropYears.ClientID %>').change(function () {
var selectedYear = $('#<%=DropYears.ClientID %>').val();
$('#tableBudgetActual').treegrid({ url: 'Json-BudgetActualData.aspx?Year=' + selectedYear });
$('#imageLoadIndicator').show();
$('div.datagrid').css('opacity', 0.4);
$('#tableBudgetActual').treegrid('reload');
});
$('div.datagrid').css('opacity', 0.4);
});
var currentYear = <%=DateTime.Today.Year %>;
var budgetLoc = '<asp:Literal ID="LiteralBudget" runat="server" />';
var actualLoc = '<asp:Literal ID="LiteralActual" runat="server" />';
</script>
<style>
.content h2 select {
font-size: 16px;
font-weight: bold;
color: #1C397E;
letter-spacing: 1px;
}
table.datagrid-ftable {
font-weight: 500;
}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<h2><div class="elementFloatFar"><%= CurrentOrganization.Currency.DisplayCode %></div><div class="elementFloatNear"><asp:Label ID="LabelContentHeader" runat="server" /> <asp:DropDownList runat="server" ID="DropYears"/>&nbsp;<img alt="Loading" src="/Images/Abstract/ajaxloader-blackcircle.gif" ID="imageLoadIndicator" /></div>&nbsp;</h2>
<table id="tableBudgetActual" title="" class="easyui-treegrid" style="width:680px;height:600px"
url="Json-BudgetActualData.aspx"
rownumbers="false"
animate="true" showFooter="true" fitColumns="true"
idField="id" treeField="name">
<thead>
<tr>
<th field="name" width="178"><asp:Literal ID="LiteralHeaderAccountName" runat="server"/></th>
<th field="lastYearActual" width="80" align="right"><span class="previousYearsHeader" id="previousLastActual" style="display:none"></span><span class="currentYearHeader" style="display:none"><asp:Literal ID="LiteralHeaderLastYearActual" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="yearBudget" width="80" align="right"><span class="previousYearsHeader" id="previousBudget" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ1"><asp:Literal ID="LiteralHeaderBudget" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="yearActual" width="80" align="right"><span class="previousYearsHeader" id="previousYtd" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ2"><asp:Literal ID="LiteralHeaderActual" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="flags" width="40" align="right"><span class="allYearsHeader" style="display:none" id="currentFlags"><asp:Literal ID="LiteralHeaderFlags" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
</tr>
</thead>
</table>
<div style="clear:both"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderSide" Runat="Server">
<h2 class="blue"><asp:Label ID="LabelSidebarDownload" Text="Download This" runat="server" /><span class="arrow"></span></h2>
<div class="box">
<div class="content">
<div class="link-row-encaps" id="linkDownloadReport" onclick="document.location='placeholder';" >
<div class="link-row-icon" style="background-image:url('/Images/Icons/iconshock-downarrow-16px.png');background-position:-1px -1px"></div>
<span id="spanDownloadText">ProfitLossxxxx-yyyymmdd.csv</span>
</div>
</div>
</div>
</asp:Content>
@@ -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;
}
}
@@ -0,0 +1 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-BudgetActualData.aspx.cs" Inherits="Pages_v5_Ledgers_Json_BudgetActualData" %>
@@ -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<AnnualReportLine> lines)
{
Dictionary<string, string> localizeMap = new Dictionary<string, string>();
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<AnnualReportLine> reportLines)
{
List<string> elements = new List<string>();
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,
"\"<span class=\\\"budgetactualdata-collapsed-{0}\\\"><strong>&Sigma;</strong> {1:N0}</span><span class=\\\"budgetactualdata-expanded-{0}\\\" style=\\\"display:none\\\">&nbsp;</span>\"",
accountId, treeValue/-100.00);
}
return string.Format (CultureInfo.CurrentCulture,
"\"<span class=\\\"budgetactualdata-collapsed-{0}\\\"><strong>&Sigma;</strong> {1:N0}</span><span class=\\\"budgetactualdata-expanded-{0}\\\" style=\\\"display:none\\\">{2:N0}</span>\"",
accountId, treeValue/-100.0, singleValue/-100.0);
}
}
+1 -1
View File
@@ -733,7 +733,7 @@ namespace Swarmops.Frontend.Pages.v5.Public
Positions.CreateSysadminPositions();
Positions.CreateOrganizationDefaultPositions (Organization.Sandbox, PositionTitle.Default);
}
catch (Exception e)
catch (Exception)
{
throw;
}