Work on Attestation, Concurrency. Db0017.

This commit is contained in:
Rick Falkvinge
2015-04-05 11:04:30 +02:00
parent 151b2ba201
commit e3d6f40fb2
17 changed files with 311 additions and 64 deletions
+2
View File
@@ -68,6 +68,8 @@
<Compile Include="Enums\PositionTitle.cs" />
<Compile Include="Enums\PositionType.cs" />
<Compile Include="Enums\RoleTypeClass.cs" />
<Compile Include="Exceptions\ConcurrencyException.cs" />
<Compile Include="Exceptions\DatabaseConcurrencyException.cs" />
<Compile Include="Generics\Tree.cs" />
<Compile Include="Interfaces\IEmailPerson.cs" />
<Compile Include="Interfaces\IHandleProvider.cs" />
+12
View File
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Swarmops.Common.Exceptions
{
public class ConcurrencyException: Exception
{
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Swarmops.Common.Exceptions
{
/// <summary>
/// Thrown when another session captured the item being modified before this session could
/// execute its transaction. This happens but must be handled gracefully.
/// </summary>
public class DatabaseConcurrencyException: ConcurrencyException
{
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Swarmops.Database
/// </summary>
public static int DbVersionExpected
{
get { return 16; }
get { return 17; }
}
+24
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Swarmops.Basic.Types.Financial;
using Swarmops.Common.Exceptions;
namespace Swarmops.Database
{
@@ -141,6 +142,29 @@ namespace Swarmops.Database
}
public void SetCashAdvanceAmountCents(int cashAdvanceId, Int64 amountCents)
{
using (DbConnection connection = GetMySqlDbConnection())
{
connection.Open();
DbCommand command = GetDbCommand("SetCashAdvanceAmountCents", connection);
command.CommandType = CommandType.StoredProcedure;
AddParameterWithName(command, "cashAdvanceId", cashAdvanceId);
AddParameterWithName(command, "amountCents", amountCents);
if (Convert.ToInt32(command.ExecuteScalar()) != 1) // returns count of rows updated
{
// This assumes that the cash advance ID existed, but that another sesssion modified it first,
// so the selector failed on the Open=1 and PaidOut=0 criteria rather than the Id=X criterion.
throw new DatabaseConcurrencyException();
}
}
}
public void SetCashAdvanceOpen(int cashAdvanceId, bool open)
{
using (DbConnection connection = GetMySqlDbConnection())
+2 -1
View File
@@ -13,4 +13,5 @@
0013 - Added PositionTitles for organizational culture flexibility [RF]
0014 - Forgot one storedproc in Db0012; renamed CreateAssignedRole [RF]
0015 - Merged PositionsStandard and PositionsAdditional into one table [RF]
0016 - Added SetCashAdvanceBudget procedure [RF]
0016 - Added SetCashAdvanceBudget procedure [RF]
0017 - Added SetCashAdvanceAmountCents procedure [RF]
+14
View File
@@ -0,0 +1,14 @@
CREATE PROCEDURE `SetCashAdvanceAmountCents`(
IN cashAdvanceId INTEGER,
IN amountCents INTEGER
)
BEGIN
UPDATE CashAdvances SET CashAdvances.AmountCents=amountCents
WHERE CashAdvances.CashAdvanceId=cashAdvanceId
AND CashAdvances.PaidOut=0
AND CashAdvances.Open=1;
SELECT ROW_COUNT() AS RecordsUpdated;
END
+12 -1
View File
@@ -12,7 +12,7 @@ using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Financial
{
[Serializable]
public class CashAdvance : BasicCashAdvance, IAttestable
public class CashAdvance : BasicCashAdvance, IPayable
{
#region Construction and creation
@@ -188,5 +188,16 @@ namespace Swarmops.Logic.Financial
get { return FinancialValidations.ForObject(this); }
}
public void SetBudget(FinancialAccount newBudget, Person settingPerson)
{
this.Budget = newBudget; // ignore settingPerson
}
public void SetAmountCents(Int64 newAmount, Person settingPerson)
{
SwarmDb.GetDatabaseForWriting().SetCashAdvanceAmountCents (this.Identity, newAmount);
}
}
}
+7 -1
View File
@@ -13,7 +13,7 @@ using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Financial
{
public class ExpenseClaim : BasicExpenseClaim, IValidatable, IAttestable
public class ExpenseClaim : BasicExpenseClaim, IValidatable, IAttestable, IPayable
{
#region Construction and Creation
@@ -433,5 +433,11 @@ namespace Swarmops.Logic.Financial
FinancialTransaction.RecalculateTransaction (nominalTransaction, updatingPerson);
}
public bool PaidOut // IPayable naming convention
{
get { return this.Repaid; }
set { this.Repaid = value; }
}
}
}
+24
View File
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Swarmops.Common.Interfaces;
using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Financial
{
public interface IPayable: IAttestable, IHasIdentity
{
new FinancialAccount Budget { get; }
void SetBudget (FinancialAccount newBudget, Person settingPerson);
Int64 AmountCents { get; }
void SetAmountCents (Int64 newAmount, Person settingPerson);
string Description { get; }
bool PaidOut { get; set; }
bool Open { get; set; }
}
}
+17 -1
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using NBitcoin;
using Swarmops.Basic.Types;
using Swarmops.Basic.Types.Financial;
using Swarmops.Common.Enums;
@@ -13,7 +14,7 @@ using Swarmops.Logic.Swarm;
namespace Swarmops.Logic.Financial
{
public class InboundInvoice : BasicInboundInvoice, IAttestable
public class InboundInvoice : BasicInboundInvoice, IAttestable, IPayable
{
private InboundInvoice (BasicInboundInvoice basicInstance) :
base (basicInstance)
@@ -221,5 +222,20 @@ namespace Swarmops.Logic.Financial
FinancialTransaction.RecalculateTransaction (nominalTransaction, updatingPerson);
}
public bool PaidOut // IPayable implementation
{
get { return (!Open && Attested); }
set
{
if (Attested)
{
Open = false;
return;
}
throw new InvalidOperationException("Can't set PaidOut if Attested is false");
}
}
}
}
+1
View File
@@ -89,6 +89,7 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Financial\IPayable.cs" />
<Compile Include="Resources\Logic.Financial.FinancialAccount.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
+8 -1
View File
@@ -180,4 +180,11 @@ public class AuthenticationData
{
public Organization CurrentOrganization;
public Person CurrentUser;
}
}
public class AjaxCallResult
{
public bool Success { get; set; }
public string DisplayMessage { get; set; }
}
+4
View File
@@ -663,4 +663,8 @@
<data name="Global_Error_WebsocketFailure" xml:space="preserve">
<value>Unable to connect WebSocket. Live updates will not be available.</value>
</data>
<data name="Error_CurrencyParsing" xml:space="preserve">
<value>Swarmops does not understand your currency amount. (One thousand money and zero cents are written like "{0:N2}".) Try again?</value>
<comment>The {0:N2} is just fed with the number 1000.00 in culture-specific format.</comment>
</data>
</root>
@@ -125,6 +125,15 @@
<value>Cash Advance #{0:N0} for {1} was UN-attested. It will not be paid out unless attested again.</value>
<comment>When somebody undoes a previous attestation.</comment>
</data>
<data name="AttestCosts_BudgetIsEmpty" xml:space="preserve">
<value>You cannot attest this amount. The budget is empty for the year {0}.</value>
</data>
<data name="AttestCosts_CannotAttestNegative" xml:space="preserve">
<value>You cannot attest a negative amount.</value>
</data>
<data name="AttestCosts_CannotAttestZero" xml:space="preserve">
<value>You cannot attest a zero amount.</value>
</data>
<data name="AttestCosts_Error_CantRebudgetSalary" xml:space="preserve">
<value>Sorry, you cannot rebudget a salary payout.</value>
</data>
@@ -186,6 +195,9 @@
<value>Attest</value>
<comment>keep short</comment>
</data>
<data name="AttestCosts_Modal_ButtonCorrect" xml:space="preserve">
<value>Attest</value>
</data>
<data name="AttestCosts_Modal_ButtonDeny" xml:space="preserve">
<value>Deny</value>
<comment>keep short</comment>
@@ -202,6 +214,9 @@
<value>What amount are you attesting instead (in {0})?</value>
<comment>The {0} is the organization currency (SEK, USD, µBTC etc).</comment>
</data>
<data name="AttestCosts_Modal_DescribeOptionCorrect" xml:space="preserve">
<value>Change this item to this amount (in {0}), then attest it like that:</value>
</data>
<data name="AttestCosts_Modal_DescribeOptionDeny" xml:space="preserve">
<value>Optional reason for denial to the submitter:</value>
</data>
@@ -214,6 +229,9 @@
<data name="AttestCosts_Modal_RadioOptionAmount" xml:space="preserve">
<value>I will attest this, but for a different amount.</value>
</data>
<data name="AttestCosts_Modal_RadioOptionCorrect" xml:space="preserve">
<value>The amount is wrong. I will attest it with the correct amount.</value>
</data>
<data name="AttestCosts_Modal_RadioOptionDeny" xml:space="preserve">
<value>I will not attest this record. It is scratched.</value>
<comment>This is a Monty Python reference. When translating, translate to "Deny attestation of this record altogether."</comment>
+28 -8
View File
@@ -104,7 +104,7 @@
accountId = $("#IconApproval" + recordId).attr('accountid');
$('div.radioOption').hide();
$('input:radio[name="ModalOptions"]').prop('checked', false);
SwarmopsJS.formatCurrency(amountRequested, function (data) { $('#<%=this.TextDifferentAmount.ClientID%>_Input').val(data); });
SwarmopsJS.formatCurrency(amountRequested, function (data) { $('#<%=this.TextCorrectAmount.ClientID%>_Input').val(data); });
$('<%=this.TextDenyReason.ClientID%>').val(''); // empty reason
<%=this.DialogDeny.ClientID%>_open();
}
@@ -296,7 +296,6 @@
function onRebudgetRecord() {
var newAccountId = <%=this.DropBudgetsRebudget.ClientID%>_val();
alert(newAccountId);
if (newAccountId == 0) {
alertify.error(decodeURIComponent('<asp:Literal ID="LiteralPleaseSelectBudget" runat="server" />'));
return;
@@ -320,6 +319,27 @@
});
}
function onAttestCorrectedAmount() {
if (recordId[0] == 'S') // Salary - cannot change amount this way
{
alertify.error(decodeURIComponent('<asp:Literal ID="LiteralCannotCorrectSalary" runat="server" />'));
}
SwarmopsJS.ajaxCall(
"/Pages/v5/Financial/AttestCosts.aspx/AttestCorrectedItem",
{ recordId: recordId, amountString: $('#<%=this.TextCorrectAmount.ClientID%>_Input').val() },
function(result) {
console.log(result);
if (!result.Success) {
alertify.error(result.DisplayMessage);
} else {
// Succeeded, attested for new amount. Since amount was changed, reload grid
$('#TableAttestableCosts').datagrid('reload');
<%= this.DialogDeny.ClientID %>_close();
}
});
}
var recordId = '';
var accountId = 0;
var budgetRemainingLookup = {};
@@ -371,7 +391,7 @@
<DialogCode>
<h2><asp:Label ID="LabelModalDenyHeader" runat="server" Text="Fix Problems Or Deny Attestation XYZ" /></h2>
<p><asp:Literal ID="LabelWhatProblem" runat="server" Text="What seems to be the problem? XYZ" /></p>
<p><input type="radio" id="RadioDeny" name="ModalOptions" value="Deny" /><label for="RadioDeny"><asp:Label runat="server" ID="LabelRadioDeny" Text="I will not attest this record. It is scratched. XYZ" /></label></p>
<p><input type="radio" id="RadioDeny" name="ModalOptions" value="Deny" onclick="$('#<%=this.TextDenyReason.ClientID%>').focus();" /><label for="RadioDeny"><asp:Label runat="server" ID="LabelRadioDeny" Text="I will not attest this record. It is scratched. XYZ" /></label></p>
<div id="radioOptionDeny" class="radioOption">
<div class="entryFields">
<asp:TextBox ID="TextDenyReason" runat="server" TextMode="MultiLine" Rows="3" Placeholder="My hovercraft is full of eels" />&#8203;<br/>
@@ -382,14 +402,14 @@
</div>
<div style="clear:both"></div>
</div>
<p><input type="radio" id="RadioAmount" name="ModalOptions" value="Amount" /><label for="RadioAmount"><asp:Label runat="server" ID="LabelRadioAmount" Text="I will attest, but for a different amount. XYZ" /></label></p>
<div id="radioOptionAmount" class="radioOption">
<p><input type="radio" id="RadioCorrect" name="ModalOptions" value="Correct" onclick="$('#<%=this.TextCorrectAmount.ClientID%>_Input').focus().select();" /><label for="RadioCorrect"><asp:Label runat="server" ID="LabelRadioCorrect" Text="I will attest, but for a different amount. XYZ" /></label></p>
<div id="radioOptionCorrect" class="radioOption">
<div class="entryFields">
<Swarmops5:CurrencyTextBox ID="TextDifferentAmount" runat="server" />&#8203;<br/>
<input type="button" value='<asp:Literal ID="LiteralButtonAmount" runat="server" Text="AmountXYZ" />' class="buttonAccentColor" onclick="onAttestDifferentAmount(); return false;" id="buttonExecuteDifferentAmount"/>
<Swarmops5:CurrencyTextBox ID="TextCorrectAmount" runat="server" />&#8203;<br/>
<input type="button" value='<asp:Literal ID="LiteralButtonCorrect" runat="server" Text="AmountXYZ" />' class="buttonAccentColor" onclick="onAttestCorrectedAmount(); return false;" id="buttonExecuteCorrectedAmount"/>
</div>
<div class="entryLabels">
<asp:Label runat="server" ID="LabelDescribeDifferentAmount" Text="What amount are you attesting instead (SEK)? XYZ" />
<asp:Label runat="server" ID="LabelDescribeCorrect" Text="What amount are you attesting instead (SEK)? XYZ" />
</div>
<div style="clear:both"></div>
</div>
+121 -50
View File
@@ -1,8 +1,10 @@
using System;
using System.Activities.Expressions;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel.Security;
using System.Threading;
using System.Web;
using System.Web.Services;
using System.Web.UI;
@@ -92,14 +94,14 @@ namespace Swarmops.Frontend.Pages.v5.Financial
this.LiteralErrorInsufficientBudget.Text = JavascriptEscape (Resources.Pages.Financial.AttestCosts_OutOfBudget);
this.LabelDescribeDeny.Text = Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionDeny;
this.LabelDescribeDifferentAmount.Text = String.Format (Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionAmount, CurrentOrganization.Currency.DisplayCode);
this.LabelDescribeCorrect.Text = String.Format (Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionAmount, CurrentOrganization.Currency.DisplayCode);
this.LabelDescribeRebudget.Text = Resources.Pages.Financial.AttestCosts_Modal_DescribeOptionRebudget;
this.LabelRadioAmount.Text = Resources.Pages.Financial.AttestCosts_Modal_RadioOptionAmount;
this.LabelRadioCorrect.Text = Resources.Pages.Financial.AttestCosts_Modal_RadioOptionAmount;
this.LabelRadioDeny.Text = Resources.Pages.Financial.AttestCosts_Modal_RadioOptionDeny;
this.LabelRadioRebudget.Text = Resources.Pages.Financial.AttestCosts_Modal_RadioOptionRebudget;
this.LiteralButtonAmount.Text = Resources.Pages.Financial.AttestCosts_Modal_ButtonAmount; // these may be flagged red by Resharper. That's Resharper being wrong.
this.LiteralButtonCorrect.Text = Resources.Pages.Financial.AttestCosts_Modal_ButtonAmount; // these may be flagged red by Resharper. That's Resharper being wrong.
this.LiteralButtonDeny.Text = Resources.Pages.Financial.AttestCosts_Modal_ButtonDeny;
this.LiteralButtonRebudget.Text = Resources.Pages.Financial.AttestCosts_Modal_ButtonRebudget;
@@ -111,50 +113,124 @@ namespace Swarmops.Frontend.Pages.v5.Financial
JavascriptEscape (Resources.Pages.Financial.AttestCosts_Error_CantRebudgetSalary);
}
static protected IPayable PayableFromRecordId (string recordId)
{
char recordType = recordId[0];
int itemId = Int32.Parse(recordId.Substring(1));
switch (recordType)
{
case 'E': // Expense claim
return ExpenseClaim.FromIdentity (itemId);
case 'A': // Cash advance
return CashAdvance.FromIdentity(itemId);
case 'I': // Inbound invoice
return InboundInvoice.FromIdentity (itemId);
default:
throw new NotImplementedException("Unknown record type");
}
}
[WebMethod]
public static void RebudgetItem (string recordId, int newAccountId)
{
AuthenticationData authData = GetAuthenticationDataAndCulture();
char recordType = recordId[0];
int itemId = Int32.Parse (recordId.Substring (1));
IPayable payable = PayableFromRecordId (recordId);
FinancialAccount newAccount = FinancialAccount.FromIdentity(newAccountId);
switch (recordType)
if (payable.Budget.OrganizationId != authData.CurrentOrganization.Identity ||
payable.Budget.OwnerPersonId != authData.CurrentUser.Identity ||
newAccount.OrganizationId != authData.CurrentOrganization.Identity)
{
case 'E': // Expense claim
ExpenseClaim claim = ExpenseClaim.FromIdentity (itemId);
if (claim.Budget.OrganizationId != authData.CurrentOrganization.Identity ||
claim.Budget.OwnerPersonId != authData.CurrentUser.Identity ||
newAccount.OrganizationId != authData.CurrentOrganization.Identity)
{
throw new UnauthorizedAccessException();
}
claim.SetBudget (newAccount, authData.CurrentUser);
break;
case 'A': // Cash advance
CashAdvance advance = CashAdvance.FromIdentity(itemId);
if (advance.Budget.OrganizationId != authData.CurrentOrganization.Identity ||
advance.Budget.OwnerPersonId != authData.CurrentUser.Identity ||
newAccount.OrganizationId != authData.CurrentOrganization.Identity)
{
throw new UnauthorizedAccessException();
}
advance.Budget = newAccount; // no accounting changes, so just change
break;
case 'I': // Cash advance
InboundInvoice invoice = InboundInvoice.FromIdentity (itemId);
if (invoice.Budget.OrganizationId != authData.CurrentOrganization.Identity ||
invoice.Budget.OwnerPersonId != authData.CurrentUser.Identity ||
newAccount.OrganizationId != authData.CurrentOrganization.Identity)
{
throw new UnauthorizedAccessException();
}
invoice.SetBudget (newAccount, authData.CurrentUser);
break;
default:
throw new NotImplementedException("Unknown record type");
throw new UnauthorizedAccessException();
}
payable.SetBudget (newAccount, authData.CurrentUser);
}
[WebMethod]
public static AjaxCallResult AttestCorrectedItem(string recordId, string amountString)
{
AuthenticationData authData = GetAuthenticationDataAndCulture();
double amount = 0.0;
try
{
amount = Double.Parse (amountString, NumberStyles.Currency, Thread.CurrentThread.CurrentCulture);
}
catch (Exception)
{
return new AjaxCallResult
{
Success = false,
DisplayMessage = String.Format(Resources.Global.Error_CurrencyParsing, 1000.00)
};
}
Int64 amountCents = (Int64) (amount*100);
if (amountCents < 0)
{
return new AjaxCallResult
{
Success = false,
DisplayMessage = Resources.Pages.Financial.AttestCosts_CannotAttestNegative
};
}
if (amountCents == 0)
{
return new AjaxCallResult
{
Success = false,
DisplayMessage = Resources.Pages.Financial.AttestCosts_CannotAttestZero
};
}
IPayable payable = PayableFromRecordId (recordId);
FinancialAccount budget = payable.Budget;
if (budget.OrganizationId != authData.CurrentOrganization.Identity ||
budget.OwnerPersonId != authData.CurrentUser.Identity)
{
throw new UnauthorizedAccessException();
}
Int64 centsRemaining = GetBudgetRemaining (budget);
if (centsRemaining/100.0 < amount)
{
// TODO: Handle the special case where the IPayable is not on current year, so against another (last) year's budget
string notEnoughFunds;
if (centsRemaining > 0)
{
notEnoughFunds = String.Format (Resources.Pages.Financial.AttestCosts_OutOfBudgetPrecise,
authData.CurrentOrganization.Currency.DisplayCode, centsRemaining/100.0, DateTime.UtcNow.Year);
}
else
{
notEnoughFunds = String.Format (Resources.Pages.Financial.AttestCosts_BudgetIsEmpty,
DateTime.UtcNow.Year);
}
return new AjaxCallResult
{
Success = false,
DisplayMessage = notEnoughFunds
};
}
payable.SetAmountCents (amountCents, authData.CurrentUser);
payable.Attest (authData.CurrentUser);
return new AjaxCallResult
{
Success = true
};
}
[WebMethod]
@@ -303,11 +379,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial
public int AccountId { get; set; }
public double Remaining { get; set; }
}
[WebMethod]
public static AttestOperationResult Attest (string identifier)
public static AjaxCallResult Attest (string identifier)
{
identifier = HttpUtility.UrlDecode (identifier);
@@ -315,7 +391,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial
}
[WebMethod]
public static AttestOperationResult Deattest (string identifier)
public static AjaxCallResult Deattest (string identifier)
{
identifier = HttpUtility.UrlDecode (identifier);
@@ -323,7 +399,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial
}
private static AttestOperationResult HandleAttestationDeattestation (string identifier, AttestationMode mode)
private static AjaxCallResult HandleAttestationDeattestation (string identifier, AttestationMode mode)
{
AuthenticationData authData = GetAuthenticationDataAndCulture();
@@ -455,7 +531,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial
if (amountCents > budgetRemaining)
{
return new AttestOperationResult
return new AjaxCallResult
{
DisplayMessage = Resources.Pages.Financial.AttestCosts_OutOfBudget,
Success = false
@@ -479,7 +555,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial
throw new InvalidOperationException ("Unknown Attestation Mode: " + mode);
}
return new AttestOperationResult {DisplayMessage = result, Success = true};
return new AjaxCallResult {DisplayMessage = result, Success = true};
}
@@ -554,11 +630,6 @@ namespace Swarmops.Frontend.Pages.v5.Financial
public string Title { get; set; }
}
public struct AttestOperationResult
{
public string DisplayMessage;
public bool Success;
}
}
}