Refactored P&L and moved logic into logic layer, deploying to test

This commit is contained in:
Rick Falkvinge
2012-12-10 07:06:55 +00:00
parent c51372cd2d
commit 7b207a4e4a
5 changed files with 256 additions and 253 deletions
+230
View File
@@ -0,0 +1,230 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Activizr.Basic.Enums;
using Activizr.Logic.Structure;
namespace Activizr.Logic.Financial
{
[Serializable]
public class YearlyReport
{
public static YearlyReport Create (Organization organization, int year, FinancialAccountType accountType)
{
YearlyReport report = new YearlyReport();
report.Organization = organization;
report.Year = year;
// Get accounts
FinancialAccounts accounts = FinancialAccounts.ForOrganization(organization, accountType);
// Remove unwanted accounts
FinancialAccount resultsAccount = organization.FinancialAccounts.CostsYearlyResult;
foreach (FinancialAccount account in accounts)
{
// For now, just remove the "results" account. TODO: Remove inactive accounts, too.
if (account.Identity == resultsAccount.Identity)
{
accounts.Remove(account);
break;
}
}
// Build tree (there should be a template for this)
report._treeMap = new Dictionary<int, List<FinancialAccount>>();
foreach (FinancialAccount account in accounts)
{
if (!report._treeMap.ContainsKey(account.ParentIdentity))
{
report._treeMap[account.ParentIdentity] = new List<FinancialAccount>();
}
report._treeMap[account.ParentIdentity].Add(account);
}
FinancialAccounts orderedList = new FinancialAccounts(); // This list is guaranteed to have parents before children
report.PopulateOrderedList(orderedList, 0); // recursively add nodes parents-first
report.PopulateLookups(orderedList); // populate the lookup tables for results per account
report.ReportLines = new List<YearlyReportLine>();
report.RecurseAddLines(report.ReportLines, 0);
return report;
}
private void RecurseAddLines (List<YearlyReportLine> list, int renderNodeId)
{
foreach (FinancialAccount account in _treeMap[renderNodeId])
{
YearlyReportLine newLine = new YearlyReportLine();
newLine.AccountId = account.Identity;
newLine.AccountName = account.Name;
newLine.AccountValues = CreateYearlyReportNode(account.Identity, _singleLookups);
newLine.AccountTreeValues = CreateYearlyReportNode(account.Identity, _treeLookups);
if (_treeMap.ContainsKey(account.Identity))
{
RecurseAddLines(newLine.Children, account.Identity);
}
list.Add(newLine);
}
}
private YearlyReportNode CreateYearlyReportNode (int accountId, Dictionary<int, Int64>[] lookup)
{
YearlyReportNode node = new YearlyReportNode();
node.PreviousYear = lookup[0][accountId];
for (int quarter = 1; quarter <= 4; quarter++)
{
node.Quarters[quarter - 1] = lookup[quarter][accountId];
}
node.ThisYear = lookup[5][accountId];
return node;
}
private void PopulateOrderedList(FinancialAccounts orderedList, int renderNodeId)
{
foreach (FinancialAccount account in _treeMap[renderNodeId])
{
orderedList.Add(account);
if (_treeMap.ContainsKey(account.Identity))
{
PopulateOrderedList(orderedList, account.Identity); // recursive call
}
}
}
private Dictionary<int, List<FinancialAccount>> _treeMap;
private Dictionary<int, Int64>[] _singleLookups;
private Dictionary<int, Int64>[] _treeLookups;
private void PopulateLookups(FinancialAccounts accounts)
{
_singleLookups = new Dictionary<int, Int64>[6];
_treeLookups = new Dictionary<int, Int64>[6];
for (int index = 0; index < 6; index++)
{
_treeLookups[index] = new Dictionary<int, Int64>();
_singleLookups[index] = new Dictionary<int, Int64>();
}
DateTime[] quarterBoundaries =
{
new DateTime(this.Year, 1, 1), new DateTime(this.Year, 3, 1), new DateTime(this.Year, 6, 1),
new DateTime(this.Year, 9, 1), new DateTime(this.Year + 1, 1, 1)
};
// 1) Actually, the accounts are already sorted. Or are supposed to be, anyway,
// since FinancialAccounts.ForOrganization gets the _tree_ rather than the flat list.
// 2) Add all values to the accounts.
foreach (FinancialAccount account in accounts)
{
// Find this year's inbound
_singleLookups[0][account.Identity] = account.GetDeltaCents(new DateTime(this.Year - 1, 1, 1), new DateTime(this.Year, 1, 1));
// Find quarter diffs
for (int quarter = 0; quarter < 4; quarter++)
{
_singleLookups[quarter + 1][account.Identity] = account.GetDeltaCents(quarterBoundaries[quarter],
quarterBoundaries[quarter + 1]);
}
// Find outbound
_singleLookups[5][account.Identity] = account.GetDeltaCents(new DateTime(this.Year, 1, 1), new DateTime(this.Year + 1, 1, 1));
// copy to treeLookups
for (int index = 0; index < 6; index++)
{
_treeLookups[index][account.Identity] = _singleLookups[index][account.Identity];
}
}
// 3) Add all children's values to parents
for (int index = 0; index < 6; index++)
{
AddChildrenValuesToParents(_treeLookups[index], accounts);
}
// Done.
}
private void AddChildrenValuesToParents(Dictionary<int, Int64> lookup, FinancialAccounts accounts)
{
// Iterate backwards and add any value to its parent's value, as they are sorted in tree order.
for (int index = accounts.Count - 1; index >= 0; index--)
{
int parentFinancialAccountId = accounts[index].ParentFinancialAccountId;
int accountId = accounts[index].Identity;
if (parentFinancialAccountId != 0)
{
lookup[parentFinancialAccountId] += lookup[accountId];
}
}
}
public List<YearlyReportLine> ReportLines;
public Organization Organization;
public int Year;
}
[Serializable]
public class YearlyReportLine
{
public YearlyReportLine()
{
Children = new List<YearlyReportLine>();
}
public int AccountId;
public string AccountName;
public YearlyReportNode AccountValues;
public YearlyReportNode AccountTreeValues;
public List<YearlyReportLine> Children;
}
[Serializable]
public class YearlyReportNode
{
public YearlyReportNode()
{
Quarters = new Int64[4];
}
public Int64 PreviousYear;
public Int64[] Quarters;
public Int64 ThisYear;
}
}
+1
View File
@@ -66,6 +66,7 @@
<ItemGroup>
<Compile Include="Financial\CashAdvance.cs" />
<Compile Include="Financial\ImportedBankData.cs" />
<Compile Include="Financial\YearlyReport.cs" />
<Compile Include="Pirates\Interfaces.cs" />
<Compile Include="Security\Accesses.cs" />
<Compile Include="AssemblyInfo.cs" />
+1 -1
View File
@@ -125,7 +125,7 @@
<comment>The {0} is the organization name. The year number follows this string.</comment>
</data>
<data name="ProfitLossStatement_Info" xml:space="preserve">
<value>The P&amp;L is an overview of income and expenditures, and are grouped by budgets or cost/income type. The sum of all income and expenditure is the yearly result. You may also want to look at the &lt;a href="BalanceSheet.aspx"&gt;balance sheet&lt;/a&gt; which is the overview of assets and debts.</value>
<value>The P&amp;L is an overview of income and expenditures, which are grouped by budgets or cost/income type. The sum of all income and expenditure is the yearly result. You may also want to look at the &lt;a href="BalanceSheet.aspx"&gt;balance sheet&lt;/a&gt; which is the overview of assets and debts.</value>
</data>
<data name="ProfitLossStatement_LastYear" xml:space="preserve">
<value>Last Year</value>
@@ -53,101 +53,56 @@ public partial class Pages_v5_Ledgers_Json_ProfitLossData : System.Web.UI.Page
_year = Int32.Parse(yearParameter); // will throw if non-numeric - don't matter for app
}
// Get accounts
FinancialAccounts accounts = FinancialAccounts.ForOrganization(currentOrganization, FinancialAccountType.Result);
// Remove unwanted accounts
FinancialAccount resultsAccount = currentOrganization.FinancialAccounts.CostsYearlyResult;
foreach (FinancialAccount account in accounts)
{
// For now, just remove the "results" account. TODO: Remove inactive accounts, too.
if (account.Identity == resultsAccount.Identity)
{
accounts.Remove(account);
break;
}
}
// Build tree (there should be a template for this)
Dictionary<int, List<FinancialAccount>> treeMap = new Dictionary<int, List<FinancialAccount>>();
foreach (FinancialAccount account in accounts)
{
if (!treeMap.ContainsKey(account.ParentIdentity))
{
treeMap[account.ParentIdentity] = new List<FinancialAccount>();
}
treeMap[account.ParentIdentity].Add(account);
}
FinancialAccounts orderedList = new FinancialAccounts(); // This list is guaranteed to have parents before children
PopulateOrderedList(treeMap, orderedList, 0); // recursively add nodes parents-first
PopulateLookups(orderedList); // populate the lookup tables for results per account
YearlyReport report = YearlyReport.Create(currentOrganization, _year, FinancialAccountType.Result);
Response.ContentType = "application/json";
int renderRootNodeId = 0;
if (treeMap[0].Count == 1)
{
// assume there's a master root like "Costs"; bypass it
renderRootNodeId = treeMap[0][0].Identity;
}
Response.Output.WriteLine(RecurseTreeMap(treeMap, renderRootNodeId));
Response.Output.WriteLine(RecurseReport(report.ReportLines));
Response.End();
}
private int _year = 2012;
private CultureInfo _renderCulture;
private string RecurseTreeMap (Dictionary<int, List<FinancialAccount>> treeMap, int renderNodeId)
private string RecurseReport (List<YearlyReportLine> reportLines)
{
List<string> elements = new List<string>();
foreach (FinancialAccount account in treeMap[renderNodeId])
foreach (YearlyReportLine line in reportLines)
{
string element = string.Format("\"id\":{0},\"name\":\"{1}\"", account.Identity,
account.Name.Replace("\"", "'"));
string element = string.Format("\"id\":{0},\"name\":\"{1}\"", line.AccountId,
line.AccountName.Replace("\"", "'"));
if (treeMap.ContainsKey(account.Identity))
if (line.Children.Count > 0)
{
element += ",\"lastYear\":" +
JsonDualString(account.Identity, treeLookups[0][account.Identity], singleLookups[0][account.Identity]);
JsonDualString(line.AccountId, line.AccountTreeValues.PreviousYear, line.AccountValues.PreviousYear);
for (int quarter = 1; quarter <= 4; quarter++)
{
element += string.Format(",\"q{0}\":", quarter) +
JsonDualString(account.Identity, treeLookups[quarter][account.Identity], singleLookups[quarter][account.Identity]);
JsonDualString(line.AccountId, line.AccountTreeValues.Quarters[quarter-1], line.AccountValues.Quarters[quarter-1]);
}
element += ",\"ytd\":" +
JsonDualString(account.Identity, treeLookups[5][account.Identity], singleLookups[5][account.Identity]);
JsonDualString(line.AccountId, line.AccountTreeValues.ThisYear, line.AccountValues.ThisYear);
element += ",\"state\":\"closed\",\"children\":" + RecurseTreeMap(treeMap, account.Identity);
element += ",\"state\":\"closed\",\"children\":" + RecurseReport(line.Children);
}
else
{
element += string.Format(_renderCulture, ",\"lastYear\":\"{0:N0}\"", (double)singleLookups[0][account.Identity] / -100.0);
element += string.Format(_renderCulture, ",\"lastYear\":\"{0:N0}\"", (double)line.AccountValues.PreviousYear / -100.0);
for (int quarter = 1; quarter <= 4; quarter++)
{
element += string.Format(_renderCulture, ",\"q{0}\":\"{1:N0}\"", quarter, singleLookups[quarter][account.Identity] / -100.0);
element += string.Format(_renderCulture, ",\"q{0}\":\"{1:N0}\"", quarter, line.AccountValues.Quarters[quarter-1] / -100.0);
}
element += string.Format(_renderCulture, ",\"ytd\":\"{0:N0}\"", (double)singleLookups[5][account.Identity] / -100.0);
element += string.Format(_renderCulture, ",\"ytd\":\"{0:N0}\"", (double)line.AccountValues.ThisYear / -100.0);
}
elements.Add("{" + element + "}");
@@ -167,189 +122,5 @@ public partial class Pages_v5_Ledgers_Json_ProfitLossData : System.Web.UI.Page
}
private void PopulateOrderedList (Dictionary<int, List<FinancialAccount>> treeMap, FinancialAccounts orderedList, int renderNodeId)
{
foreach (FinancialAccount account in treeMap[renderNodeId])
{
orderedList.Add(account);
if (treeMap.ContainsKey(account.Identity))
{
PopulateOrderedList(treeMap, orderedList, account.Identity); // recursive call
}
}
}
private int _year = 2012;
private Dictionary<int, Int64>[] singleLookups;
private Dictionary<int, Int64>[] treeLookups;
private void PopulateLookups(FinancialAccounts accounts)
{
singleLookups = new Dictionary<int, Int64>[6];
treeLookups = new Dictionary<int, Int64>[6];
for (int index = 0; index < 6; index++)
{
treeLookups[index] = new Dictionary<int, Int64>();
singleLookups[index] = new Dictionary<int, Int64>();
}
DateTime[] quarterBoundaries =
{
new DateTime(_year, 1, 1), new DateTime(_year, 3, 1), new DateTime(_year, 6, 1),
new DateTime(_year, 9, 1), new DateTime(_year + 1, 1, 1)
};
// 1) Actually, the accounts are already sorted. Or are supposed to be, anyway,
// since FinancialAccounts.ForOrganization gets the _tree_ rather than the flat list.
// 2) Add all values to the accounts.
foreach (FinancialAccount account in accounts)
{
// Find this year's inbound
singleLookups[0][account.Identity] = account.GetDeltaCents(new DateTime(_year - 1, 1, 1), new DateTime(_year, 1, 1));
// Find quarter diffs
for (int quarter = 0; quarter < 4; quarter++)
{
singleLookups[quarter + 1][account.Identity] = account.GetDeltaCents(quarterBoundaries[quarter],
quarterBoundaries[quarter + 1]);
}
// Find outbound
singleLookups[5][account.Identity] = account.GetDeltaCents(new DateTime(_year, 1, 1), new DateTime(_year + 1, 1, 1));
// copy to treeLookups
for (int index = 0; index < 6; index++)
{
treeLookups[index][account.Identity] = singleLookups[index][account.Identity];
}
}
// 3) Add all children's values to parents
for (int index = 0; index < 6; index++)
{
AddChildrenValuesToParents(treeLookups[index], accounts);
}
// Done.
}
private void AddChildrenValuesToParents(Dictionary<int, Int64> lookup, FinancialAccounts accounts)
{
// Iterate backwards and add any value to its parent's value, as they are sorted in tree order.
for (int index = accounts.Count - 1; index >= 0; index--)
{
int parentFinancialAccountId = accounts[index].ParentFinancialAccountId;
int accountId = accounts[index].Identity;
if (parentFinancialAccountId != 0)
{
lookup[parentFinancialAccountId] += lookup[accountId];
}
}
}
/*
protected void GridBudgetAccounts_ItemCreated(object sender, GridItemEventArgs e)
{
// CreateExpandCollapseButton(e.Item, "Name");
if (e.Item is GridHeaderItem && e.Item.OwnerTableView != this.GridBudgetAccounts.MasterTableView)
{
e.Item.Style["display"] = "none";
}
if (e.Item is GridNestedViewItem)
{
e.Item.Cells[0].Visible = false;
}
if (e.Item is GridDataItem)
{
int year = DateTime.Today.Year;
FinancialAccount account = (FinancialAccount) e.Item.DataItem;
if (account == null)
{
return;
}
HyperLink editLink = (HyperLink) e.Item.FindControl("ManageLink");
editLink.Attributes["href"] = "#";
editLink.Attributes["onclick"] = String.Format("return ShowAccountForm('{0}','{1}');",
account.FinancialAccountId, e.Item.ItemIndex);
PopulateLine(e.Item);
}
}
protected void PopulateLine(GridItem item)
{
FinancialAccount account = (FinancialAccount) item.DataItem;
if (account == null)
{
return;
}
Label labelAccountName = (Label) item.FindControl("LabelAccountName");
Literal literalLastYear = (Literal) item.FindControl("LiteralLastYear");
Literal literalQ1 = (Literal) item.FindControl("LiteralQuarter1");
Literal literalQ2 = (Literal) item.FindControl("LiteralQuarter2");
Literal literalQ3 = (Literal) item.FindControl("LiteralQuarter3");
Literal literalQ4 = (Literal) item.FindControl("LiteralQuarter4");
Literal literalYtd = (Literal) item.FindControl("LiteralThisYear");
PopulateDualFigure(literalLastYear, "LastYear", 0, account.Identity);
PopulateDualFigure(literalQ1, "Q1", 1, account.Identity);
PopulateDualFigure(literalQ2, "Q2", 2, account.Identity);
PopulateDualFigure(literalQ3, "Q3", 3, account.Identity);
PopulateDualFigure(literalQ4, "Q4", 4, account.Identity);
PopulateDualFigure(literalYtd, "Ytd", 5, account.Identity);
labelAccountName.Text = account.Name;
}
*/
private void PopulateDualFigure(Literal literal, string spanPrefix, int category, int accountId)
{
Int64 treeValue = treeLookups[category][accountId];
Int64 singleValue = singleLookups[category][accountId];
string span =
string.Format(
"<span ID=\"GridSpanExpanded{1}{0}\" style=\"display:none\">{2:N0}</span><span ID=\"GridSpanCollapsed{1}{0}\">{4}{3:N0}</span>",
accountId, spanPrefix, singleValue, treeValue,
singleValue != treeValue ? "<b>&Sigma;</b>&nbsp;" : string.Empty);
literal.Text = span;
}
private void PopulateFigureCollapsed(Label label, int category, int accountId)
{
string prefix = string.Empty;
Int64 treeValue = treeLookups[category][accountId];
Int64 singleValue = singleLookups[category][accountId];
if (treeValue != singleValue)
{
prefix = "Σ ";
}
label.Text = prefix + treeValue.ToString("N0");
}
}
@@ -26,6 +26,7 @@
onLoadSuccess: function () {
$('div.datagrid').css('opacity', 1);
$('#imageLoadIndicator').hide();
$('span.loadingHeader').hide();
var selectedYear = $('#<%=DropYears.ClientID %>').val();
@@ -54,13 +55,13 @@
$('#tableProfitLoss').treegrid({ url: 'Json-ProfitLossData.aspx?Year=' + selectedYear });
$('#imageLoadIndicator').show();
$('div.datagrid').css('opacity', 0.5);
$('div.datagrid').css('opacity', 0.4);
$('#tableProfitLoss').treegid('reload');
});
$('div.datagrid').css('opacity', 0.5);
$('div.datagrid').css('opacity', 0.4);
});
var currentYear = <%=DateTime.Today.Year %>;
@@ -85,12 +86,12 @@
<thead>
<tr>
<th field="name" width="178"><asp:Literal ID="LiteralHeaderAccountName" runat="server"/></th>
<th field="lastYear" width="80" align="right"><span class="previousYearsHeader" id="previousLastYear" style="display:none"></span><span class="currentYearHeader"><asp:Literal ID="LiteralHeaderLastYear" runat="server" /></span></th>
<th field="q1" width="80" align="right"><span class="previousYearsHeader" id="previousQ1" style="display:none"></span><span class="currentYearHeader" id="currentQ1"><asp:Literal ID="LiteralHeaderQ1" runat="server" /></span></th>
<th field="q2" width="80" align="right"><span class="previousYearsHeader" id="previousQ2" style="display:none"></span><span class="currentYearHeader" id="currentQ2"><asp:Literal ID="LiteralHeaderQ2" runat="server" /></span></th>
<th field="q3" width="80" align="right"><span class="previousYearsHeader" id="previousQ3" style="display:none"></span><span class="currentYearHeader" id="currentQ3"><asp:Literal ID="LiteralHeaderQ3" runat="server" /></span></th>
<th field="q4" width="80" align="right"><span class="previousYearsHeader" id="previousQ4" style="display:none"></span><span class="currentYearHeader" id="currentQ4"><asp:Literal ID="LiteralHeaderQ4" runat="server" /></span></th>
<th field="ytd" width="80" align="right"><span class="previousYearsHeader" id="previousYtd" style="display:none"></span><span class="currentYearHeader"><asp:Literal ID="LiteralHeaderYtd" runat="server" /></span></th>
<th field="lastYear" width="80" align="right"><span class="previousYearsHeader" id="previousLastYear" style="display:none"></span><span class="currentYearHeader" style="display:none"><asp:Literal ID="LiteralHeaderLastYear" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="q1" width="80" align="right"><span class="previousYearsHeader" id="previousQ1" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ1"><asp:Literal ID="LiteralHeaderQ1" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="q2" width="80" align="right"><span class="previousYearsHeader" id="previousQ2" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ2"><asp:Literal ID="LiteralHeaderQ2" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="q3" width="80" align="right"><span class="previousYearsHeader" id="previousQ3" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ3"><asp:Literal ID="LiteralHeaderQ3" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="q4" width="80" align="right"><span class="previousYearsHeader" id="previousQ4" style="display:none"></span><span class="currentYearHeader" style="display:none" id="currentQ4"><asp:Literal ID="LiteralHeaderQ4" runat="server" /></span><span class="loadingHeader">&mdash;</span></th>
<th field="ytd" width="80" align="right"><span class="previousYearsHeader" id="previousYtd" style="display:none"></span><span class="currentYearHeader" style="display:none"><asp:Literal ID="LiteralHeaderYtd" runat="server" /></span></th>
</tr>
</thead>
</table>