diff --git a/Common/Common.csproj b/Common/Common.csproj index 6fd858d5..38bb40ce 100644 --- a/Common/Common.csproj +++ b/Common/Common.csproj @@ -68,6 +68,8 @@ + + diff --git a/Common/Exceptions/ConcurrencyException.cs b/Common/Exceptions/ConcurrencyException.cs new file mode 100644 index 00000000..06d8c9c8 --- /dev/null +++ b/Common/Exceptions/ConcurrencyException.cs @@ -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 + { + } +} diff --git a/Common/Exceptions/DatabaseConcurrencyException.cs b/Common/Exceptions/DatabaseConcurrencyException.cs new file mode 100644 index 00000000..9f589d88 --- /dev/null +++ b/Common/Exceptions/DatabaseConcurrencyException.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Swarmops.Common.Exceptions +{ + /// + /// Thrown when another session captured the item being modified before this session could + /// execute its transaction. This happens but must be handled gracefully. + /// + public class DatabaseConcurrencyException: ConcurrencyException + { + } +} diff --git a/Database/Configuration.cs b/Database/Configuration.cs index 3524304f..e6670b13 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -14,7 +14,7 @@ namespace Swarmops.Database /// public static int DbVersionExpected { - get { return 16; } + get { return 17; } } diff --git a/Database/Database-CashAdvances.cs b/Database/Database-CashAdvances.cs index 521980f1..93ff9c23 100644 --- a/Database/Database-CashAdvances.cs +++ b/Database/Database-CashAdvances.cs @@ -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()) diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index 21343236..2d71c451 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -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] \ No newline at end of file +0016 - Added SetCashAdvanceBudget procedure [RF] +0017 - Added SetCashAdvanceAmountCents procedure [RF] diff --git a/Database/Schemata/upgrade-0017.sql b/Database/Schemata/upgrade-0017.sql new file mode 100644 index 00000000..73dc6606 --- /dev/null +++ b/Database/Schemata/upgrade-0017.sql @@ -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 diff --git a/Logic/Financial/CashAdvance.cs b/Logic/Financial/CashAdvance.cs index 4ea1d6ce..502957e0 100644 --- a/Logic/Financial/CashAdvance.cs +++ b/Logic/Financial/CashAdvance.cs @@ -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); + } } } \ No newline at end of file diff --git a/Logic/Financial/ExpenseClaim.cs b/Logic/Financial/ExpenseClaim.cs index e0a5533b..23601be6 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -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; } + } } } \ No newline at end of file diff --git a/Logic/Financial/IPayable.cs b/Logic/Financial/IPayable.cs new file mode 100644 index 00000000..51929075 --- /dev/null +++ b/Logic/Financial/IPayable.cs @@ -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; } + } +} diff --git a/Logic/Financial/InboundInvoice.cs b/Logic/Financial/InboundInvoice.cs index b15c8e21..5e16d44a 100644 --- a/Logic/Financial/InboundInvoice.cs +++ b/Logic/Financial/InboundInvoice.cs @@ -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"); + } + } } } \ No newline at end of file diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index a7268db5..4fe33725 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -89,6 +89,7 @@ + True True diff --git a/Site5/App_Code/PageV5Base.cs b/Site5/App_Code/PageV5Base.cs index e3e2e0d7..7d8c969d 100644 --- a/Site5/App_Code/PageV5Base.cs +++ b/Site5/App_Code/PageV5Base.cs @@ -180,4 +180,11 @@ public class AuthenticationData { public Organization CurrentOrganization; public Person CurrentUser; -} \ No newline at end of file +} + + +public class AjaxCallResult +{ + public bool Success { get; set; } + public string DisplayMessage { get; set; } +} diff --git a/Site5/App_GlobalResources/Global.resx b/Site5/App_GlobalResources/Global.resx index 53d5b540..52ede672 100644 --- a/Site5/App_GlobalResources/Global.resx +++ b/Site5/App_GlobalResources/Global.resx @@ -663,4 +663,8 @@ Unable to connect WebSocket. Live updates will not be available. + + Swarmops does not understand your currency amount. (One thousand money and zero cents are written like "{0:N2}".) Try again? + The {0:N2} is just fed with the number 1000.00 in culture-specific format. + \ No newline at end of file diff --git a/Site5/App_GlobalResources/Pages.Financial.resx b/Site5/App_GlobalResources/Pages.Financial.resx index ac60cae7..7f50bb2e 100644 --- a/Site5/App_GlobalResources/Pages.Financial.resx +++ b/Site5/App_GlobalResources/Pages.Financial.resx @@ -125,6 +125,15 @@ Cash Advance #{0:N0} for {1} was UN-attested. It will not be paid out unless attested again. When somebody undoes a previous attestation. + + You cannot attest this amount. The budget is empty for the year {0}. + + + You cannot attest a negative amount. + + + You cannot attest a zero amount. + Sorry, you cannot rebudget a salary payout. @@ -186,6 +195,9 @@ Attest keep short + + Attest + Deny keep short @@ -202,6 +214,9 @@ What amount are you attesting instead (in {0})? The {0} is the organization currency (SEK, USD, µBTC etc). + + Change this item to this amount (in {0}), then attest it like that: + Optional reason for denial to the submitter: @@ -214,6 +229,9 @@ I will attest this, but for a different amount. + + The amount is wrong. I will attest it with the correct amount. + I will not attest this record. It is scratched. This is a Monty Python reference. When translating, translate to "Deny attestation of this record altogether." diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx b/Site5/Pages/v5/Financial/AttestCosts.aspx index 6a31ff48..77b435e1 100644 --- a/Site5/Pages/v5/Financial/AttestCosts.aspx +++ b/Site5/Pages/v5/Financial/AttestCosts.aspx @@ -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('')); return; @@ -320,6 +319,27 @@ }); } + function onAttestCorrectedAmount() { + if (recordId[0] == 'S') // Salary - cannot change amount this way + { + alertify.error(decodeURIComponent('')); + } + + 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 @@

-

+

​
@@ -382,14 +402,14 @@
-

-
+

+
- ​
- + ​
+
diff --git a/Site5/Pages/v5/Financial/AttestCosts.aspx.cs b/Site5/Pages/v5/Financial/AttestCosts.aspx.cs index 04669999..e512c05d 100644 --- a/Site5/Pages/v5/Financial/AttestCosts.aspx.cs +++ b/Site5/Pages/v5/Financial/AttestCosts.aspx.cs @@ -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; - } } } \ No newline at end of file