Adding some logging to SwarmopsLog re. financials (more probably to follow)

This commit is contained in:
Rick Falkvinge
2014-01-07 17:24:06 +00:00
parent ba79524607
commit da7d24ec1f
14 changed files with 115 additions and 351 deletions
+5
View File
@@ -7,6 +7,8 @@ using Swarmops.Basic.Types.Financial;
using Swarmops.Database;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Communications.Transmission;
using Swarmops.Logic.Support;
using Swarmops.Logic.Support.LogEntries;
using Swarmops.Logic.Swarm;
using Swarmops.Logic.Structure;
@@ -46,6 +48,9 @@ namespace Swarmops.Logic.Financial
description));
OutboundComm.CreateNotificationForAttest(budget, forPerson, (double) amountCents/100.0, description, NotificationResource.CashAdvance_Requested); // Slightly misplaced logic, but failsafer here
SwarmopsLogEntry.Create(forPerson,
new CashAdvanceRequestedLogEntry(createdByPerson, forPerson, (double) amountCents/100.0, budget, description),
newAdvance);
return newAdvance;
}
+3
View File
@@ -5,6 +5,7 @@ using Swarmops.Basic.Types;
using Swarmops.Database;
using Swarmops.Logic.Communications;
using Swarmops.Logic.Communications.Transmission;
using Swarmops.Logic.Support.LogEntries;
using Swarmops.Logic.Swarm;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
@@ -66,6 +67,8 @@ namespace Swarmops.Logic.Financial
// Create notification
OutboundComm.CreateNotificationForAttest(budget, claimer, (double)amountCents / 100.0, description, NotificationResource.ExpenseClaim_Created); // Slightly misplaced logic, but failsafer here
SwarmopsLog.CreateEntry(claimer,
new ExpenseClaimFiledLogEntry(claimer /*filing person*/, claimer /*beneficiary*/, (double) amountCents/100.0, budget, description));
return newClaim;
}
+20
View File
@@ -6,6 +6,7 @@ using Swarmops.Basic.Enums;
using Swarmops.Basic.Types;
using Swarmops.Basic.Types.Financial;
using Swarmops.Database;
using Swarmops.Logic.Support.LogEntries;
using Swarmops.Logic.Swarm;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
@@ -200,6 +201,7 @@ namespace Swarmops.Logic.Financial
int advanceId = Int32.Parse(component.Substring(1));
CashAdvance advance = CashAdvance.FromIdentity(advanceId);
identityList.Add(advanceId);
Organization organization = Organization.FromIdentity(organizationId);
if (bank.Length < 1)
{
@@ -207,12 +209,20 @@ namespace Swarmops.Logic.Financial
bank = asker.BankName;
account = asker.BankAccount;
organizationId = advance.OrganizationId;
}
amountCents += advance.AmountCents;
advance.PaidOut = true;
//advance.Open = false; // isn't this closed only when settling the debt? Serious bug here?
SwarmopsLogEntry.Create(creator,
new PayoutCreatedLogEntry(creator, advance.Person, organization,
organization.Currency, (double) amountCents/100.0,
"Cash Advance Paid Out"),
advance.Person, advance);
}
string referenceString = string.Empty;
@@ -241,6 +251,8 @@ namespace Swarmops.Logic.Financial
{
// Expense claims, possibly followed up by cash advance paybacks
Person beneficiaryPerson = null;
Organization organization = null;
string bank = string.Empty;
string account = string.Empty;
List<int> claimIdentityList = new List<int>();
@@ -265,6 +277,8 @@ namespace Swarmops.Logic.Financial
organizationId = claim.OrganizationId;
}
beneficiaryPerson = claim.Claimer;
organization = claim.Organization;
amountCents += claim.AmountCents;
claim.Repaid = true;
@@ -292,6 +306,12 @@ namespace Swarmops.Logic.Financial
referenceString = "Expense Claims " + Formatting.GenerateRangeString(claimIdentityList);
}
SwarmopsLogEntry.Create(creator,
new PayoutCreatedLogEntry(creator, beneficiaryPerson, organization,
organization.Currency, amountCents/100.0,
referenceString),
beneficiaryPerson);
payoutId = SwarmDb.GetDatabaseForWriting().CreatePayout(organizationId, bank, account,
referenceString, amountCents, DateTime.Today.AddDays(1),
creator.Identity);
+2 -1
View File
@@ -214,10 +214,11 @@
<Compile Include="Support\DatabaseMaintenance.cs" />
<Compile Include="Support\Imagery.cs" />
<Compile Include="Support\IXmlPayload.cs" />
<Compile Include="Support\LogEntries\CashAdvanceAttestedLogEntry.cs" />
<Compile Include="Support\LogEntries\CashAdvanceRequestedLogEntry.cs" />
<Compile Include="Support\LogEntries\ExpenseClaimFiledLogEntry.cs" />
<Compile Include="Support\LogEntries\FinancialActionBase.cs" />
<Compile Include="Support\LogEntries\LogEntryBase.cs" />
<Compile Include="Support\LogEntries\PayoutCreatedLogEntry.cs" />
<Compile Include="Support\ObjectOptionalData.cs" />
<Compile Include="Support\PluralBase.cs" />
<Compile Include="Security\ActivityEnum.cs" />
@@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Support.LogEntries
{
class CashAdvanceAttestedLogEntry: CashAdvanceRequestedLogEntry
{
// Identical class
CashAdvanceAttestedLogEntry(Person attestingPerson, double amount, FinancialAccount budget, string reason)
:base (attestingPerson, amount, budget, reason)
{
}
}
}
@@ -15,17 +15,19 @@ namespace Swarmops.Logic.Support.LogEntries
// empty ctor needed for serialize
}
public CashAdvanceRequestedLogEntry(Person requestingPerson, double amount, FinancialAccount budget, string reason)
public CashAdvanceRequestedLogEntry(Person actingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason)
{
this.Amount = amount;
this.Currency = budget.Organization.Currency.Code;
this.DateTime = DateTime.UtcNow;
this.Description = reason;
this.OrganizationId = budget.OrganizationId;
this.FinancialAccountId = budget.Identity;
this.FinancialAccountName = budget.Name; // redundancy in case of future name changes
this.OwnerPersonId = budget.OwnerPersonId;
this.OwnerPersonName = budget.Owner.Name;
this.PersonId = requestingPerson.Identity; // do not save name for data retention reasons
this.ActingPersonId = actingPerson.Identity; // do not save name for data retention reasons
this.BeneficiaryPersonId = beneficiaryPerson.Identity;
}
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Support.LogEntries
{
[Serializable]
public class ExpenseClaimFiledLogEntry: FinancialActionBase
{
public ExpenseClaimFiledLogEntry()
{
// empty ctor needed for serialize
}
public ExpenseClaimFiledLogEntry(Person filingPerson, Person beneficiaryPerson, double amount, FinancialAccount budget, string reason)
{
this.Amount = amount;
this.Currency = budget.Organization.Currency.Code;
this.DateTime = DateTime.UtcNow;
this.Description = reason;
this.OrganizationId = budget.OrganizationId;
this.FinancialAccountId = budget.Identity;
this.FinancialAccountName = budget.Name; // redundancy in case of future name changes
this.OwnerPersonId = budget.OwnerPersonId;
this.OwnerPersonName = budget.Owner.Name;
this.ActingPersonId = filingPerson.Identity; // do not save name for data retention reasons
this.BeneficiaryPersonId = beneficiaryPerson.Identity;
}
}
}
@@ -16,7 +16,9 @@ namespace Swarmops.Logic.Support.LogEntries
public int FinancialAccountId { get; set; }
public string FinancialAccountName { get; set; }
public int PersonId { get; set; }
public int ActingPersonId { get; set; }
public int BeneficiaryPersonId { get; set; }
public int OrganizationId { get; set; }
public double Amount { get; set; }
public string Currency { get; set; }
public string Description { get; set; }
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Support.LogEntries
{
[Serializable]
public class PayoutCreatedLogEntry: FinancialActionBase
{
public PayoutCreatedLogEntry()
{
// public ctor required for serializability
}
public PayoutCreatedLogEntry(Person payingPerson, Person beneficiaryPerson, Organization organization, Currency currency, double amount, string reason)
{
this.Amount = amount;
this.Currency = currency.Code;
this.OrganizationId = organization.Identity;
this.DateTime = DateTime.UtcNow;
this.Description = reason;
this.ActingPersonId = payingPerson.Identity; // do not save name for data retention reasons
this.BeneficiaryPersonId = (beneficiaryPerson != null ? beneficiaryPerson.Identity : 0);
}
}
}
+14 -2
View File
@@ -32,9 +32,21 @@ namespace Swarmops.Logic.Support
return FromBasic(SwarmDb.GetDatabaseForWriting().GetSwarmopsLogEntry(swarmopsLogEntryId)); // Writing intentional
}
public static SwarmopsLogEntry Create (Person person, IXmlPayload logEntry)
public static SwarmopsLogEntry Create (Person person, IXmlPayload logEntry, params object[] affectedObjects)
{
return SwarmopsLog.CreateEntry(person, logEntry);
SwarmopsLogEntry entry = SwarmopsLog.CreateEntry(person, logEntry);
if (person != null)
{
entry.CreateAffectedObject(person);
}
foreach (IHasIdentity affectedObject in affectedObjects)
{
entry.CreateAffectedObject(affectedObject);
}
return entry;
}
public void CreateAffectedObject (IHasIdentity affectedObject)
@@ -1 +0,0 @@
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-ExpensableBudgetsTree.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Finance.Json_ExpensableBudgetsTree" %>
@@ -1,110 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Swarmops.Logic.Financial;
using Swarmops.Logic.Swarm;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
namespace Swarmops.Frontend.Pages.v5.Finance
{
public partial class Json_ExpensableBudgetsTree : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Current authentication
string identity = HttpContext.Current.User.Identity.Name;
string[] identityTokens = identity.Split(',');
string userIdentityString = identityTokens[0];
string organizationIdentityString = identityTokens[1];
int currentUserId = Convert.ToInt32(userIdentityString);
int currentOrganizationId = Convert.ToInt32(organizationIdentityString);
Person currentUser = Person.FromIdentity(currentUserId);
Authority authority = currentUser.GetAuthority();
Organization currentOrganization = Organization.FromIdentity(currentOrganizationId);
Response.ContentType = "application/json";
// Is this stuff in cache already?
string cacheKey = "ExpensableBudgets-Json-" +
currentOrganizationId.ToString((CultureInfo.InvariantCulture));
string accountsJson =
(string) Cache[cacheKey];
if (accountsJson != null)
{
Response.Output.WriteLine(accountsJson);
Response.End();
return;
}
// Not in cache. Construct.
// Get accounts
FinancialAccounts accounts = currentOrganization.FinancialAccounts.ExpensableBudgets;
// 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);
}
int renderRootNodeId = 0;
if (treeMap[0].Count == 1)
{
// assume there's a master root like "Costs"; bypass it
renderRootNodeId = treeMap[0][0].Identity;
}
accountsJson = RecurseTreeMap(treeMap, renderRootNodeId);
Cache.Insert(cacheKey, accountsJson, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);
// cache lasts for five minutes, no sliding expiration
Response.Output.WriteLine(accountsJson);
Response.End();
}
private string RecurseTreeMap(Dictionary<int, List<FinancialAccount>> treeMap, int node)
{
List<string> elements = new List<string>();
foreach (FinancialAccount account in treeMap[node])
{
string element = string.Format("\"id\":{0},\"text\":\"{1}\"", account.Identity,
account.Name.Replace("\"", "'"));
if (treeMap.ContainsKey(account.Identity))
{
element += ",\"state\":\"closed\",\"children\":" + RecurseTreeMap(treeMap, account.Identity);
}
elements.Add("{" + element + "}");
}
return "[" + String.Join(",", elements.ToArray()) + "]";
}
}
}
@@ -1,95 +0,0 @@
<%@ Page Title="" Language="C#" MasterPageFile="~/Master-v5.master" AutoEventWireup="true" CodeFile="RequestCashAdvance.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Finance.RequestCashAdvance" %>
<%@ Register src="~/Controls/v5/UI/ExternalScripts.ascx" tagname="ExternalScripts" tagprefix="Swarmops5" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderHead" Runat="Server">
<Swarmops5:ExternalScripts ID="ExternalScripts1" Package="easyui" Control="tree" runat="server" />
<link rel="stylesheet" type="text/css" href="/Style/v5-easyui-elements.css">
<script type="text/javascript">
$(document).ready(function () {
$('#DropBudgets').combotree({
animate: true
}); // Is this init call even necessary?
$('input.combo-text').click(function () {
$('span.combo-arrow').click();
});
});
function validateFields() {
var isValid = true;
isValid = validateTextField('#<%=this.TextAccount.ClientID %>', "<asp:Literal runat="server" ID="LiteralErrorBankAccount" />") && isValid;
isValid = validateTextField('#<%=this.TextClearing.ClientID %>', "<asp:Literal runat="server" ID="LiteralErrorBankClearing" />") && isValid;
isValid = validateTextField('#<%=this.TextBank.ClientID %>', "<asp:Literal runat="server" ID="LiteralErrorBankName" />") && isValid;
if ($('#DropBudgets').combotree('tree').tree('getSelected') == null) {
isValid = false;
alertify.error("<asp:Literal runat="server" ID="LiteralErrorBudget" />");
}
isValid = validateTextField('#<%=this.TextPurpose.ClientID %>', "<asp:Literal runat="server" ID="LiteralErrorPurpose" />") && isValid;
$.ajax({
type: "POST",
url: "/Automation/FieldValidation.asmx/IsAmountValid",
data: "{'amount': '" + escape($('#<%=this.TextAmount.ClientID %>').val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false, // blocks until function returns - race conditions otherwise
success: function (msg) {
if (msg.d != true) {
isValid = false;
alertify.error("<asp:Literal runat="server" ID="LiteralErrorAmount" />");
$('#<%=this.TextAmount.ClientID %>').focus();
}
}
});
return isValid;
}
function validateTextField (fieldId, message) {
if ($(fieldId).val().length == 0) {
alertify.error(message);
$(fieldId).focus();
return false;
}
return true;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderMain" Runat="Server">
<div class="entryFields">
<asp:TextBox runat="server" ID="TextAmount" CssClass="alignRight" />&nbsp;<br/>
<asp:TextBox runat="server" ID="TextPurpose" />&nbsp;<br/>
<select class="easyui-combotree" url="Json-ExpensableBudgetsTree.aspx" name="DropBudgets" id="DropBudgets" animate="true" style="width:300px"></select>&nbsp;<br/>
&nbsp;<br/><!-- placeholder for label-side H2 -->
<asp:TextBox runat="server" ID="TextBank" />&nbsp;<br/>
<asp:TextBox runat="server" ID="TextClearing" />&nbsp;<br/>
<asp:TextBox runat="server" ID="TextAccount" />&nbsp;<br/>
<asp:Button ID="ButtonRequest" runat="server" CssClass="buttonAccentColor" OnClientClick="return validateFields();" OnClick="ButtonRequest_Click" Text="Request"/>
</div>
<div class="entryLabels">
<asp:Label runat="server" ID="LabelAmount" /><br/>
<asp:Label runat="server" ID="LabelPurpose" /><br/>
<asp:Label runat="server" ID="LabelBudget" /><br/>
<h2><asp:Label runat="server" ID="LabelHeaderBankDetails" /></h2>
<asp:Label runat="server" ID="LabelBankName" /><br/>
<asp:Label runat="server" ID="LabelBankClearing" /><br/>
<asp:Label runat="server" ID="LabelBankAccount" />
</div>
<div style="clear:both"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderSide" Runat="Server">
</asp:Content>
@@ -1,119 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Swarmops.Logic.Financial;
namespace Swarmops.Frontend.Pages.v5.Finance
{
public partial class RequestCashAdvance : PageV5Base
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.CurrentOrganization.IsEconomyEnabled)
{
Response.Redirect("/Pages/v5/Financial/EconomyNotEnabled.aspx", true);
return;
}
this.PageTitle = Resources.Pages.Financial.RequestCashAdvance_PageTitle;
this.PageIcon = "iconshock-walletmoney";
this.InfoBoxLiteral = Resources.Pages.Financial.RequestCashAdvance_Info;
if (!Page.IsPostBack)
{
// Prime bank details
this.TextBank.Text = this.CurrentUser.BankName;
this.TextClearing.Text = this.CurrentUser.BankClearing;
this.TextAccount.Text = this.CurrentUser.BankAccount;
this.TextAmount.Text = 0.ToString("N2");
this.TextAmount.Focus();
Localize();
}
}
private void Localize()
{
this.LabelAmount.Text = string.Format(Resources.Pages.Financial.RequestCashAdvance_Amount,
CurrentOrganization.Currency.Code);
this.LabelPurpose.Text = Resources.Pages.Financial.RequestCashAdvance_Purpose;
this.LabelBudget.Text = Resources.Pages.Financial.RequestCashAdvance_Budget;
this.LabelHeaderBankDetails.Text = Resources.Pages.Financial.RequestCashAdvance_HeaderBankDetails;
this.LabelBankName.Text = Resources.Pages.Financial.RequestCashAdvance_BankName;
this.LabelBankClearing.Text = Resources.Pages.Financial.RequestCashAdvance_BankClearing;
this.LabelBankAccount.Text = Resources.Pages.Financial.RequestCashAdvance_BankAccount;
this.LiteralErrorAmount.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_Amount;
this.LiteralErrorPurpose.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_Purpose;
this.LiteralErrorBudget.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_Budget;
this.LiteralErrorBankName.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_BankName;
this.LiteralErrorBankClearing.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_BankClearing;
this.LiteralErrorBankAccount.Text = Resources.Pages.Financial.RequestCashAdvance_ValidationError_BankAccount;
}
protected void ButtonRequest_Click(object sender, EventArgs e)
{
// The data has been validated client-side already. We'll throw unfriendly exceptions if invalid data is passed here.
double amount = Double.Parse(this.TextAmount.Text, NumberStyles.Number);
// parses in current culture - intentional
Int64 amountCents = (Int64) amount*100;
string description = this.TextPurpose.Text;
FinancialAccount budget = FinancialAccount.FromIdentity(Int32.Parse(this.Request.Form["DropBudgets"]));
// sanity check
if (budget.Organization.Identity != CurrentOrganization.Identity)
{
throw new InvalidOperationException("Budget-organization mismatch; won't file cash advance");
}
// Store bank details for current user
CurrentUser.BankName = this.TextBank.Text;
CurrentUser.BankClearing = this.TextClearing.Text;
CurrentUser.BankAccount = this.TextAccount.Text;
// Create cash advance
CashAdvance cashAdvance = CashAdvance.Create(CurrentOrganization, CurrentUser, CurrentUser, amountCents,
budget,
description);
// Create success message
string successMessage = string.Format(Resources.Pages.Financial.RequestCashAdvance_SuccessMessagePartOne,
HttpUtility.HtmlEncode(CurrentUser.Name),
HttpUtility.HtmlEncode(description), CurrentOrganization.Currency.Code,
(double) (amountCents/100.0));
if (budget.OwnerPersonId != CurrentUser.Identity)
{
successMessage += "<br/><br/>" + Resources.Pages.Financial.RequestCashAdvance_SuccessMessagePartTwo +
"<br/>";
}
else
{
successMessage += "<br/><br/>" +
Resources.Pages.Financial.RequestCashAdvance_SuccessMessagePartTwoOwnBudget +
"<br/>";
// TODO: Auto-attest
}
Response.AppendCookie(new HttpCookie("DashboardMessage", HttpUtility.UrlEncode(successMessage)));
// Redirect to dashboard
Response.Redirect("/", true);
}
}
}