diff --git a/Database/Database-Documents.cs b/Database/Database-Documents.cs index 58bfb88e..d8bd501c 100644 --- a/Database/Database-Documents.cs +++ b/Database/Database-Documents.cs @@ -36,7 +36,7 @@ namespace Swarmops.Database } - public BasicDocument[] GetDocumentsForForeignObject (DocumentType documentType, int foreignId) + public BasicDocument[] GetDocumentsForForeignObject(DocumentType documentType, int foreignId) { List result = new List(); @@ -64,6 +64,33 @@ namespace Swarmops.Database } + public BasicDocument[] GetDocumentsRecentByDescription(string description) + { + List result = new List(); + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand( + "SELECT Documents.DocumentId,Documents.ServerFileName,Documents.ClientFileName,Documents.Description,DocumentTypes.Name AS DocumentType,Documents.ForeignId,Documents.FileSize,Documents.UploadedByPersonId,Documents.UploadedDateTime From Documents,DocumentTypes " + + "WHERE Documents.Description = '" + description.Replace ("'", "''") + " AND " + + "Documents.UploadedDateTime > '" + DateTime.UtcNow.AddDays(-1).ToString("yyyy-MM-dd HH:mm") + "'", connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadDocumentFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + private BasicDocument ReadDocumentFromDataReader(DbDataReader reader) { int documentId = reader.GetInt32(0); @@ -102,7 +129,7 @@ namespace Swarmops.Database command.Parameters.Add(new MySqlParameter("foreignId", foreignId)); command.Parameters.Add(new MySqlParameter("fileSize", fileSize)); command.Parameters.Add(new MySqlParameter("uploadedByPersonId", uploadedByPersonId)); - command.Parameters.Add(new MySqlParameter("uploadedDateTime", DateTime.Now)); + command.Parameters.Add(new MySqlParameter("uploadedDateTime", DateTime.UtcNow)); /* AddParameterWithName(command, "serverFileName", serverFileName); diff --git a/Logic/Financial/ExpenseClaim.cs b/Logic/Financial/ExpenseClaim.cs index 6df08a45..52489c46 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -32,13 +32,13 @@ namespace Swarmops.Logic.Financial } public static ExpenseClaim Create (Person claimer, Organization organization, FinancialAccount budget, - DateTime expenseDate, string description, Int64 amountCents) + FinancialAccount costType, DateTime expenseDate, string description, Int64 amountCents) { ExpenseClaim newClaim = FromIdentity (SwarmDb.GetDatabaseForWriting().CreateExpenseClaim (claimer.Identity, organization.Identity, budget.Identity, expenseDate, description, amountCents)); // Create the financial transaction with rows - string transactionDescription = "Expense #" + newClaim.Identity + ": " + description; + string transactionDescription = "Expense #" + newClaim.Identity + ": " + description; // TODO: Localize if (transactionDescription.Length > 64) { @@ -51,6 +51,7 @@ namespace Swarmops.Logic.Financial transaction.AddRow(organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); transaction.AddRow(budget, amountCents, claimer); + transaction.AddRow(costType, amountCents, claimer); // dimension 2 // Make the transaction dependent on the expense claim diff --git a/Logic/Financial/OrganizationFinancialAccounts.cs b/Logic/Financial/OrganizationFinancialAccounts.cs index 13cb7d46..96d92f06 100644 --- a/Logic/Financial/OrganizationFinancialAccounts.cs +++ b/Logic/Financial/OrganizationFinancialAccounts.cs @@ -243,5 +243,54 @@ namespace Swarmops.Logic.Financial return result; } } + + + public FinancialAccounts ExpensableCostTypes + { + // TODO: This needs to return a tree, not a flat list. + + get + { + FinancialAccounts result = new FinancialAccounts(); + + int yearlyResultId = this.CostsYearlyResult.Identity; + + FinancialAccounts costAccounts = + FinancialAccounts.ForOrganization(Organization.FromIdentity(_organizationId), + FinancialAccountType.Cost); + + foreach (FinancialAccount account in costAccounts) + { + if (account.Identity != yearlyResultId && account.Dimension == 2 && account.Expensable) + { + result.Add(account); + } + } + + if (result.Count == 0) + { + // Cost types have not been primed; add default account to organization and return it. + + FinancialAccount defaultCostTypeAccount = FinancialAccount.Create(this._organizationId, + "Unspecified Costs", + FinancialAccountType.Cost, 0); + defaultCostTypeAccount.Dimension = 2; + + this[OrganizationFinancialAccountType.CostTypeUnspecified] = defaultCostTypeAccount; + + FinancialAccount defaultIncomeTypeAccount = FinancialAccount.Create(this._organizationId, + "Unspecified Income", + FinancialAccountType.Income, 0); + defaultIncomeTypeAccount.Dimension = 2; + + result.Add(defaultCostTypeAccount); + + this[OrganizationFinancialAccountType.IncomeTypeUnspecified] = defaultIncomeTypeAccount; + } + + return result; + } + } + } } diff --git a/Logic/Support/Documents.cs b/Logic/Support/Documents.cs index 2f9076e2..fc039b28 100644 --- a/Logic/Support/Documents.cs +++ b/Logic/Support/Documents.cs @@ -59,6 +59,12 @@ namespace Swarmops.Logic.Support } + public static Documents RecentFromGuid (Guid guid) + { + return FromArray (SwarmDb.GetDatabaseForReading().GetDocumentsRecentByDescription (guid.ToString())); + } + + public void SetForeignObjectForAll (IHasIdentity foreignObject) { foreach (Document doc in this) diff --git a/Site5/App_Code/DataV5Base.cs b/Site5/App_Code/DataV5Base.cs index a3b84796..beb70ace 100644 --- a/Site5/App_Code/DataV5Base.cs +++ b/Site5/App_Code/DataV5Base.cs @@ -176,6 +176,11 @@ public class DataV5Base : System.Web.UI.Page protected static AuthenticationData GetAuthenticationDataAndCulture() + { + return GetAuthenticationDataAndCulture(HttpContext.Current); + } + + protected static AuthenticationData GetAuthenticationDataAndCulture(HttpContext suppliedContext) { // This function is called from static page methods in AJAX calls to get // the current set of authentication data. Static page methods cannot access @@ -185,7 +190,7 @@ public class DataV5Base : System.Web.UI.Page // Find various credentials - string identity = HttpContext.Current.User.Identity.Name; + string identity = suppliedContext.User.Identity.Name; string[] identityTokens = identity.Split(','); string userIdentityString = identityTokens[0]; diff --git a/Site5/Automation/Json-ExpensableCostTypesTree.aspx b/Site5/Automation/Json-ExpensableCostTypesTree.aspx new file mode 100644 index 00000000..dd21fd93 --- /dev/null +++ b/Site5/Automation/Json-ExpensableCostTypesTree.aspx @@ -0,0 +1 @@ +<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json-ExpensableCostTypesTree.aspx.cs" Inherits="Swarmops.Frontend.Pages.v5.Financial.Json_ExpensableCostTypesTree" %> diff --git a/Site5/Automation/Json-ExpensableCostTypesTree.aspx.cs b/Site5/Automation/Json-ExpensableCostTypesTree.aspx.cs new file mode 100644 index 00000000..10538a83 --- /dev/null +++ b/Site5/Automation/Json-ExpensableCostTypesTree.aspx.cs @@ -0,0 +1,95 @@ +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.Financial +{ + public partial class Json_ExpensableCostTypesTree : DataV5Base + { + protected void Page_Load(object sender, EventArgs e) + { + Response.ContentType = "application/json"; + + // Is this stuff in cache already? + + string cacheKey = "CostTypes-Json-" + + this.CurrentOrganization.Identity.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 = this.CurrentOrganization.FinancialAccounts.ExpensableCostTypes; + + // Build tree (there should be a template for this) + + Dictionary> treeMap = new Dictionary>(); + + foreach (FinancialAccount account in accounts) + { + if (!treeMap.ContainsKey(account.ParentIdentity)) + { + treeMap[account.ParentIdentity] = new List(); + } + + treeMap[account.ParentIdentity].Add(account); + } + + int renderRootNodeId = 0; + + if (treeMap[0].Count == 1 && treeMap.ContainsKey(treeMap[0][0].Identity)) + { + // 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> treeMap, int node) + { + List elements = new List(); + + 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()) + "]"; + + } + } +} \ No newline at end of file diff --git a/Site5/Automation/UploadFileHandler.ashx b/Site5/Automation/UploadFileHandler.ashx index 6bbae681..69a684bf 100644 --- a/Site5/Automation/UploadFileHandler.ashx +++ b/Site5/Automation/UploadFileHandler.ashx @@ -2,123 +2,162 @@ using System; using System.Collections.Generic; -using System.Configuration; +using System.Collections.Specialized; +using System.Diagnostics; using System.Drawing; using System.IO; -using System.Linq; using System.Web; using System.Web.Script.Serialization; +using Swarmops.Logic.Structure; +using Swarmops.Logic.Support; +using Swarmops.Logic.Swarm; -namespace Swarmops.Frontend.Automation { - public class FileTransferHandler : IHttpHandler { - private readonly JavaScriptSerializer js = new JavaScriptSerializer(); +namespace Swarmops.Frontend.Automation +{ + public class FileTransferHandler : DataV5Base, IHttpHandler + { + private readonly JavaScriptSerializer js = new JavaScriptSerializer(); - public string StorageRoot { - get - { - if (System.Diagnostics.Debugger.IsAttached) - { - return @"C:\Windows\Temp\\"; // Windows debugging environment - } - else - { - return "/opt/swarmops/upload/"; // production location on Debian installation TODO: config file - } - } - } - public bool IsReusable { get { return false; } } + public string StorageRoot + { + get + { + if (Debugger.IsAttached) + { + return @"C:\Windows\Temp\\Swarmops-Debug\\"; // Windows debugging environment + } + else + { + return "/opt/swarmops/upload/"; // production location on Debian installation TODO: config file + } + } + } - public void ProcessRequest (HttpContext context) { - context.Response.AddHeader("Pragma", "no-cache"); - context.Response.AddHeader("Cache-Control", "private, no-cache"); + #region IHttpHandler Members - HandleMethod(context); - } + public bool IsReusable + { + get { return false; } + } - // Handle request based on method - private void HandleMethod (HttpContext context) { - switch (context.Request.HttpMethod) { - case "HEAD": - case "GET": - if (GivenFilename(context)) DeliverFile(context); - else ListCurrentFiles(context); - break; + public void ProcessRequest (HttpContext context) + { + context.Response.AddHeader ("Pragma", "no-cache"); + context.Response.AddHeader ("Cache-Control", "private, no-cache"); - case "POST": - case "PUT": - UploadFile(context); - break; + HandleMethod (context); + } - case "DELETE": - DeleteFile(context); - break; + #endregion - case "OPTIONS": - ReturnOptions(context); - break; + // Handle request based on method + private void HandleMethod (HttpContext context) + { + switch (context.Request.HttpMethod) + { + case "HEAD": + case "GET": + if (GivenFilename (context)) DeliverFile (context); + else ListCurrentFiles (context); + break; - default: - context.Response.ClearHeaders(); - context.Response.StatusCode = 405; - break; - } - } + case "POST": + case "PUT": + UploadFile (context); + break; - private static void ReturnOptions(HttpContext context) { - context.Response.AddHeader("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS"); - context.Response.StatusCode = 200; - } + case "DELETE": + DeleteFile (context); + break; - // Delete file from the server - private void DeleteFile (HttpContext context) { - var filePath = StorageRoot + context.Request["f"]; - if (File.Exists(filePath)) { - File.Delete(filePath); - } - } + case "OPTIONS": + ReturnOptions (context); + break; - // Upload file to the server - private void UploadFile (HttpContext context) { - var statuses = new List(); - var headers = context.Request.Headers; + default: + context.Response.ClearHeaders(); + context.Response.StatusCode = 405; + break; + } + } - if (string.IsNullOrEmpty(headers["X-File-Name"])) { - UploadWholeFile(context, statuses); - } else { - UploadPartialFile(headers["X-File-Name"], context, statuses); - } + private static void ReturnOptions (HttpContext context) + { + context.Response.AddHeader ("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS"); + context.Response.StatusCode = 200; + } - WriteJsonIframeSafe(context, statuses); - } + // Delete file from the server + private void DeleteFile (HttpContext context) + { + string filePath = StorageRoot + context.Request["f"]; + if (File.Exists (filePath)) + { + File.Delete (filePath); + } + } - // Upload partial file - private void UploadPartialFile (string fileName, HttpContext context, List statuses) { - if (context.Request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request"); - var inputStream = context.Request.Files[0].InputStream; - var fullName = StorageRoot + Path.GetFileName(fileName); + // Upload file to the server + private void UploadFile (HttpContext context) + { + var statuses = new List(); + NameValueCollection headers = context.Request.Headers; - using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write)) { - var buffer = new byte[1024]; + if (string.IsNullOrEmpty (headers["X-File-Name"])) + { + UploadWholeFile (context, statuses); + } + else + { + UploadPartialFile (headers["X-File-Name"], context, statuses); + } - var l = inputStream.Read(buffer, 0, 1024); - while (l > 0) { - fs.Write(buffer, 0, l); - l = inputStream.Read(buffer, 0, 1024); - } - fs.Flush(); - fs.Close(); - } - statuses.Add(new FilesStatus(new FileInfo(fullName))); - } + WriteJsonIframeSafe (context, statuses); + } - // Upload entire file - private void UploadWholeFile (HttpContext context, List statuses) { - for (int i = 0; i < context.Request.Files.Count; i++) { - var file = context.Request.Files[i]; - string fullName = Path.GetFileName(file.FileName); + // Upload partial file + private void UploadPartialFile (string fileName, HttpContext context, List statuses) + { + if (context.Request.Files.Count != 1) + throw new HttpRequestValidationException ( + "Attempt to upload chunked file containing more than one fragment per request"); + Stream inputStream = context.Request.Files[0].InputStream; + string fullName = StorageRoot + Path.GetFileName (fileName); + + throw new NotImplementedException ( + "We should never get to partial upload. If we do, something is very very unexpected and this needs to be implemented."); + + using (var fs = new FileStream (fullName, FileMode.Append, FileAccess.Write)) + { + var buffer = new byte[1024]; + + int l = inputStream.Read (buffer, 0, 1024); + while (l > 0) + { + fs.Write (buffer, 0, l); + l = inputStream.Read (buffer, 0, 1024); + } + fs.Flush(); + fs.Close(); + } + statuses.Add (new FilesStatus (new FileInfo (fullName))); + } + + // Upload entire file + private void UploadWholeFile (HttpContext context, List statuses) + { + for (int i = 0; i < context.Request.Files.Count; i++) + { + HttpPostedFile file = context.Request.Files[i]; + string fullName = Path.GetFileName (file.FileName); // Store in MemoryStream in order to try to load as an image + AuthenticationData authData = GetAuthenticationDataAndCulture (context); + + Person uploadingPerson = authData.CurrentUser; + Organization currentOrg = authData.CurrentOrganization; + /* MemoryStream ms = new MemoryStream(); byte[] fileData = new byte[file.ContentLength]; @@ -126,87 +165,145 @@ namespace Swarmops.Frontend.Automation { file.InputStream.Read(fileData, 0, file.ContentLength); ms.Write(fileData, 0, file.ContentLength); ms.Position = 0;*/ - + // Try to load as image. If fails, not an acceptable file - try - { - Image image = Image.FromStream(file.InputStream); + try + { + Image image = Image.FromStream (file.InputStream); } - catch (Exception) - { - FilesStatus errorStatus = new FilesStatus(fullName, file.ContentLength); - errorStatus.error = "ERR_NOT_IMAGE"; - errorStatus.url = string.Empty; - errorStatus.delete_url = string.Empty; - errorStatus.thumbnail_url = string.Empty; - - statuses.Add(errorStatus); + catch (Exception) + { + var errorStatus = new FilesStatus (fullName, file.ContentLength); + errorStatus.error = "ERR_NOT_IMAGE"; + errorStatus.url = string.Empty; + errorStatus.delete_url = string.Empty; + errorStatus.thumbnail_url = string.Empty; + + statuses.Add (errorStatus); // -1 for length means the file was NOT saved, and that it could not be parsed as image. - return; - } - - // TODO: Store to file name dependent on GUID - - // TODO: Store new image in db + return; + } - file.InputStream.Position = 0; - file.SaveAs(StorageRoot + Path.GetFileName(file.FileName)); - - statuses.Add(new FilesStatus(fullName, file.ContentLength)); - } - } + string guid = context.Request.QueryString["Guid"]; - private void WriteJsonIframeSafe (HttpContext context, List statuses) { - context.Response.AddHeader("Vary", "Accept"); - try { - if (context.Request["HTTP_ACCEPT"].Contains("application/json")) - context.Response.ContentType = "application/json"; - else - context.Response.ContentType = "text/plain"; - } catch { - context.Response.ContentType = "text/plain"; - } + if (string.IsNullOrEmpty (guid)) + { + throw new ArgumentException ("No Context Guid supplied with upload"); + } - var jsonObj = js.Serialize(statuses.ToArray()); - context.Response.Write(jsonObj); - } + string fileNameBase = guid + "-" + uploadingPerson.Identity.ToString ("X8").ToLowerInvariant() + "-" + + currentOrg.Identity.ToString ("X4").ToLowerInvariant(); - private static bool GivenFilename (HttpContext context) { - return !string.IsNullOrEmpty(context.Request["f"]); - } + DateTime utcNow = DateTime.UtcNow; - private void DeliverFile (HttpContext context) { - var filename = context.Request["f"]; - var filePath = StorageRoot + filename; + string fileFolder = utcNow.Year.ToString ("0000") + Path.DirectorySeparatorChar + + utcNow.Month.ToString ("00") + Path.DirectorySeparatorChar + + utcNow.Day.ToString ("00"); - if (File.Exists(filePath)) { - context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); - context.Response.ContentType = "application/octet-stream"; - context.Response.ClearContent(); - context.Response.WriteFile(filePath); - } else - context.Response.StatusCode = 404; - } + if (!Directory.Exists (fileFolder)) + { + Directory.CreateDirectory (fileFolder); + } + + int fileCounter = 0; + string fileName = string.Empty; + + do + { + fileCounter++; + fileName = fileNameBase + "-" + fileCounter.ToString ("X2").ToLowerInvariant(); + } while (File.Exists (StorageRoot + fileFolder + Path.DirectorySeparatorChar + fileName) && fileCounter < 512); + + if (fileCounter >= 512) + { + throw new InvalidOperationException ( + "File name determination failed; probable file system permissions error"); + } + + file.InputStream.Position = 0; + file.SaveAs (StorageRoot + fileFolder + Path.DirectorySeparatorChar + fileName); + + Document.Create (StorageRoot + fileFolder + Path.DirectorySeparatorChar + fileName, file.FileName, file.ContentLength, + guid, null, authData.CurrentUser); + + statuses.Add (new FilesStatus (fullName, file.ContentLength)); + } + } + + private void WriteJsonIframeSafe (HttpContext context, List statuses) + { + context.Response.AddHeader ("Vary", "Accept"); + try + { + if (context.Request["HTTP_ACCEPT"].Contains ("application/json")) + context.Response.ContentType = "application/json"; + else + context.Response.ContentType = "text/plain"; + } + catch + { + context.Response.ContentType = "text/plain"; + } + + string jsonObj = js.Serialize (statuses.ToArray()); + context.Response.Write (jsonObj); + } + + private static bool GivenFilename (HttpContext context) + { + return !string.IsNullOrEmpty (context.Request["f"]); + } + + private void DeliverFile (HttpContext context) + { + string filename = context.Request["f"]; + string filePath = StorageRoot + filename; + + if (File.Exists (filePath)) + { + context.Response.AddHeader ("Content-Disposition", "attachment; filename=\"" + filename + "\""); + context.Response.ContentType = "application/octet-stream"; + context.Response.ClearContent(); + context.Response.WriteFile (filePath); + } + else + context.Response.StatusCode = 404; + } + + private void ListCurrentFiles (HttpContext context) + { + FileInfo[] files = + new DirectoryInfo (StorageRoot) + .GetFiles ("*", SearchOption.TopDirectoryOnly); - private void ListCurrentFiles (HttpContext context) { - var files = - new DirectoryInfo(StorageRoot) - .GetFiles("*", SearchOption.TopDirectoryOnly); - // completely wrong, redo from scratch - string jsonObj = js.Serialize(files); - context.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\""); - context.Response.Write(jsonObj); - context.Response.ContentType = "application/json"; - } - } + string jsonObj = js.Serialize (files); + context.Response.AddHeader ("Content-Disposition", "inline; filename=\"files.json\""); + context.Response.Write (jsonObj); + context.Response.ContentType = "application/json"; + } + } public class FilesStatus { public const string HandlerPath = "/"; + public FilesStatus() + { + } + + public FilesStatus (FileInfo fileInfo) + { + SetValues (fileInfo.Name, (int) fileInfo.Length); + } + + public FilesStatus (string fileName, int fileLength) + { + SetValues (fileName, fileLength); + } + public string group { get; set; } public string name { get; set; } public string type { get; set; } @@ -218,13 +315,7 @@ namespace Swarmops.Frontend.Automation { public string delete_type { get; set; } public string error { get; set; } - public FilesStatus() { } - - public FilesStatus(FileInfo fileInfo) { SetValues(fileInfo.Name, (int)fileInfo.Length); } - - public FilesStatus(string fileName, int fileLength) { SetValues(fileName, fileLength); } - - private void SetValues(string fileName, int fileLength) + private void SetValues (string fileName, int fileLength) { name = fileName; type = "image/png"; diff --git a/Site5/Controls/v5/Base/FileUpload.ascx.cs b/Site5/Controls/v5/Base/FileUpload.ascx.cs index 4ff892e5..b164649e 100644 --- a/Site5/Controls/v5/Base/FileUpload.ascx.cs +++ b/Site5/Controls/v5/Base/FileUpload.ascx.cs @@ -14,7 +14,7 @@ namespace Swarmops.Controls.Base { if (!Page.IsPostBack) { - Guid = new Guid(); + Guid = Guid.NewGuid(); if (Filter == UploadFilter.Unknown) // if not set in control { diff --git a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx index a1e2a4e3..85f51a84 100644 --- a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx +++ b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx @@ -87,7 +87,7 @@  
 
 
-  
+  
 
diff --git a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs index 98f73f35..9e007af1 100644 --- a/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs +++ b/Site5/Pages/v5/Financial/FileExpenseClaim.aspx.cs @@ -6,6 +6,7 @@ using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Swarmops.Logic.Financial; +using Swarmops.Logic.Support; namespace Swarmops.Frontend.Pages.v5.Financial { @@ -64,6 +65,7 @@ namespace Swarmops.Frontend.Pages.v5.Financial 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. + // People who choose to disable JavaScript and then submit bad input almost deserve to be hurt. double amount = Double.Parse(this.TextAmount.Text, NumberStyles.Number); // parses in current culture - intentional @@ -72,6 +74,8 @@ namespace Swarmops.Frontend.Pages.v5.Financial string description = this.TextPurpose.Text; FinancialAccount budget = FinancialAccount.FromIdentity(Int32.Parse(this.Request.Form["DropBudgets"])); + FinancialAccount costType = + FinancialAccount.FromIdentity (Int32.Parse ((this.Request.Form["DropCostTypes"]))); // sanity check @@ -80,19 +84,31 @@ namespace Swarmops.Frontend.Pages.v5.Financial throw new InvalidOperationException("Budget-organization mismatch; won't file cash advance"); } + if (costType.Organization.Identity != CurrentOrganization.Identity) + { + throw new InvalidOperationException("CostType-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 + // Get documents; check that documents have been uploaded - CashAdvance cashAdvance = CashAdvance.Create(CurrentOrganization, CurrentUser, CurrentUser, amountCents, - budget, - description); + Documents documents = Documents.RecentFromGuid (this.FileUpload.Guid); + + if (documents.Count == 0) + { + throw new InvalidOperationException("No documents uploaded"); + } + + ExpenseClaim claim = ExpenseClaim.Create (this.CurrentUser, this.CurrentOrganization, budget, costType, + DateTime.UtcNow, description, amountCents); + + documents.SetForeignObjectForAll(claim); - // Create success message /* string successMessage = string.Format(Resources.Pages.Financial.FileExpenseClaim_SuccessMessagePartOne, HttpUtility.HtmlEncode(CurrentUser.Name),