diff --git a/Basic/Basic.csproj b/Basic/Basic.csproj index 8cd79a9e..ed6fa013 100644 --- a/Basic/Basic.csproj +++ b/Basic/Basic.csproj @@ -58,6 +58,7 @@ + diff --git a/Basic/Types/Financial/BasicExpenseClaim.cs b/Basic/Types/Financial/BasicExpenseClaim.cs index 5ad6f141..87944fea 100644 --- a/Basic/Types/Financial/BasicExpenseClaim.cs +++ b/Basic/Types/Financial/BasicExpenseClaim.cs @@ -8,7 +8,7 @@ namespace Swarmops.Basic.Types.Financial /// /// Normal constructor /// - public BasicExpenseClaim (int expenseClaimId, int claimingPersonId, DateTime createdDateTime, + public BasicExpenseClaim (int expenseClaimId, int claimingPersonId, DateTime createdDateTime, int expenseClaimGroupId, bool open, bool attested, bool documented, bool claimed, int organizationId, int organizationSequenceId, int geographyId, int budgetId, DateTime expenseDate, string description, double preApprovedAmount, Int64 amountCents, Int64 vatCents, bool repaid, bool keepSeparate) @@ -31,13 +31,14 @@ namespace Swarmops.Basic.Types.Financial this.VatCents = vatCents; this.Repaid = repaid; this.KeepSeparate = keepSeparate; + this.GroupId = expenseClaimGroupId; } /// /// Copy constructor /// public BasicExpenseClaim (BasicExpenseClaim original) - : this (original.Identity, original.ClaimingPersonId, original.CreatedDateTime, + : this (original.Identity, original.ClaimingPersonId, original.CreatedDateTime, original.GroupId, original.Open, original.Attested, original.Validated, original.Claimed, original.OrganizationId, original.OrganizationSequenceId, original.GeographyId, original.BudgetId, original.ExpenseDate, original.Description, @@ -65,6 +66,7 @@ namespace Swarmops.Basic.Types.Financial public bool Repaid { get; protected set; } public bool KeepSeparate { get; protected set; } public bool Claimed { get; protected set; } + public int GroupId { get; protected set; } // The fields below are not just encapsulated yet diff --git a/Basic/Types/Financial/BasicExpenseClaimGroup.cs b/Basic/Types/Financial/BasicExpenseClaimGroup.cs new file mode 100644 index 00000000..788fa0a9 --- /dev/null +++ b/Basic/Types/Financial/BasicExpenseClaimGroup.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Common.Enums; +using Swarmops.Common.Interfaces; + +namespace Swarmops.Basic.Types.Financial +{ + public class BasicExpenseClaimGroup: IHasIdentity + { + public BasicExpenseClaimGroup(int expenseClaimGroupId, DateTime createdDateTime, int createdByPersonId, bool open, ExpenseClaimGroupType groupType, string groupData) + { + this.ExpenseClaimGroupId = expenseClaimGroupId; + this.CreatedDateTime = createdDateTime; + this.CreatedByPersonId = createdByPersonId; + this.Open = open; + this.GroupType = groupType; + this.GroupData = groupData; + } + + public BasicExpenseClaimGroup(BasicExpenseClaimGroup original) + : this (original.ExpenseClaimGroupId, original.CreatedDateTime, original.CreatedByPersonId, original.Open, original.GroupType, original.GroupData) + { + // copy ctor + } + + public int ExpenseClaimGroupId { get; set; } + public DateTime CreatedDateTime { get; set; } + public int CreatedByPersonId { get; set; } + public bool Open { get; set; } + public ExpenseClaimGroupType GroupType { get; set; } + public string GroupData { get; set; } + + + public int Identity { get { return this.ExpenseClaimGroupId; } } + } +} diff --git a/Common/Common.csproj b/Common/Common.csproj index 6d681984..b05ebc05 100644 --- a/Common/Common.csproj +++ b/Common/Common.csproj @@ -49,6 +49,7 @@ + diff --git a/Common/Enums/ExpenseClaimGroupType.cs b/Common/Enums/ExpenseClaimGroupType.cs new file mode 100644 index 00000000..56c54688 --- /dev/null +++ b/Common/Enums/ExpenseClaimGroupType.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Swarmops.Common.Enums +{ + public enum ExpenseClaimGroupType + { + Unknown = 0, + Expensify + } +} diff --git a/Database/Configuration.cs b/Database/Configuration.cs index 6fe03908..d87305ca 100644 --- a/Database/Configuration.cs +++ b/Database/Configuration.cs @@ -12,7 +12,7 @@ namespace Swarmops.Database /// /// This is the IN-CODE revision of the database. The version we expect to be running against. /// - public static int DbVersionExpected => 68; + public static int DbVersionExpected => 69; // This class is in horrible need of serious refactoring. For its simplicity in task, it's a horrible bowl of spaghetti. diff --git a/Database/Database-ExpenseGroups.cs b/Database/Database-ExpenseGroups.cs new file mode 100644 index 00000000..cf65c6e5 --- /dev/null +++ b/Database/Database-ExpenseGroups.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Globalization; +using Swarmops.Basic.Types; +using Swarmops.Basic.Types.Financial; +using Swarmops.Basic.Types.Security; +using Swarmops.Basic.Types.Swarm; +using Swarmops.Common.Enums; +using Swarmops.Common.Interfaces; + +namespace Swarmops.Database +{ + public partial class SwarmDb + { + #region Field reading code + + private const string expenseClaimGroupFieldSequence = + " ExpenseClaimGroups.ExpenseClaimGroupId, ExpenseClaimGroups.CreatedDateTime, ExpenseClaimGroups.CreatedByPersonId, ExpenseClaimGroups.Open, ExpenseClaimGroupTypes.Name, " + // 0-4 + " ExpenseClaimGroups.ExpenseClaimGroupData " + // 5 + " FROM ExpenseClaimGroups JOIN ExpenseClaimGroupTypes ON (ExpenseGlaimGroupTypes.ExpenseClaimGroupTypeId=ExpenseClaimGroups.ExpenseClaimGroupTypeId) "; + + private static BasicExpenseClaimGroup ReadExpenseClaimGroupFromDataReader(DbDataReader reader) + { + int expenseClaimGroupId = reader.GetInt32(0); + DateTime createdDateTime = reader.GetDateTime(1); + int createdByPersonId = reader.GetInt32(2); + bool open = reader.GetInt32(3) != 0 ? true : false; + string groupTypeName = reader.GetString(4); + string groupData = reader.GetString(5); + + ExpenseClaimGroupType groupType = (ExpenseClaimGroupType)Enum.Parse(typeof(ExpenseClaimGroupType), groupTypeName); + + return new BasicExpenseClaimGroup(expenseClaimGroupId, createdDateTime, createdByPersonId, open, groupType, groupData); + } + + #endregion + + public BasicExpenseClaimGroup GetExpenseClaimGroup(int expenseClaimGroupId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = + GetDbCommand("SELECT " + expenseClaimGroupFieldSequence + " WHERE ExpenseClaimGroups.ExpenseClaimGroupId= " + expenseClaimGroupId.ToString(CultureInfo.InvariantCulture), + connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + return ReadExpenseClaimGroupFromDataReader(reader); + } + + throw new ArgumentException("No such ExpenseClaimGroupId"); + } + } + } + + public BasicExpenseClaimGroup[] GetExpenseClaimGroups(params object[] conditions) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + List result = new List(); + connection.Open(); + + DbCommand command = GetDbCommand("SELECT " + expenseClaimGroupFieldSequence + ConstructWhereClause("ExpenseClaimGroups", conditions), + connection); + + using (DbDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + result.Add(ReadExpenseClaimGroupFromDataReader(reader)); + } + + return result.ToArray(); + } + } + } + + + + /* + * IN organizationId INT, + IN dateTime DATETIME, + IN createdByPersonId INT, + IN expenseClaimGroupType VARCHAR(64), + IN expenseClaimGroupData TEXT + */ + public int CreateExpenseClaimGroup(int organizationId, int personId, ExpenseClaimGroupType groupType, string groupData) + { + DateTime utcNow = DateTime.UtcNow; + + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("CreateExpenseClaimGroup", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "organizationId", organizationId); + AddParameterWithName(command, "personId", personId); + AddParameterWithName(command, "dateTime", utcNow); + AddParameterWithName(command, "expenseClaimGroupType", groupType.ToString()); + AddParameterWithName(command, "expenseClaimGroupData", groupData); + + return Convert.ToInt32(command.ExecuteScalar()); + } + } + + public void SetExpenseClaimGroupClosed(int expenseClaimGroupId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetExpenseClaimGroupClosed", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "expenseClaimGroupId", expenseClaimGroupId); + command.ExecuteNonQuery(); + } + } + } +} + \ No newline at end of file diff --git a/Database/Database-Expenses.cs b/Database/Database-Expenses.cs index 82971387..850c563e 100644 --- a/Database/Database-Expenses.cs +++ b/Database/Database-Expenses.cs @@ -11,10 +11,10 @@ namespace Swarmops.Database public partial class SwarmDb { private string expenseClaimFieldSequence = - " ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + // 0-4 - " Validated,Claimed,OrganizationId,GeographyId,BudgetId," + // 5-9 - " ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid," + // 10-14 - " KeepSeparate,VatCents,OrganizationSequenceId " + // 15-17 + " ExpenseClaimId,ClaimingPersonId,CreatedDateTime,Open,Attested," + // 0-4 + " Validated,Claimed,OrganizationId,GeographyId,BudgetId," + // 5-9 + " ExpenseDate,Description,PreApprovedAmount,AmountCents,Repaid," + // 10-14 + " KeepSeparate,VatCents,OrganizationSequenceId,ExpenseClaimGroupId " + // 15-18 " FROM ExpenseClaims"; public BasicExpenseClaim GetExpenseClaim (int expenseClaimId) @@ -181,8 +181,9 @@ namespace Swarmops.Database bool keepSeparate = reader.GetBoolean (15); Int64 vatCents = reader.GetInt64(16); int organizationSequenceId = reader.GetInt32(17); + int expenseClaimGroupId = reader.GetInt32(18); - return new BasicExpenseClaim (expenseClaimId, claimingPersonId, createdDateTime, + return new BasicExpenseClaim (expenseClaimId, claimingPersonId, createdDateTime, expenseClaimGroupId, open, attested, documented, claimed, organizationId, organizationSequenceId, geographyId, budgetId, expenseDate, description, preApprovedAmount, amountCents, vatCents, repaid, keepSeparate); @@ -432,19 +433,36 @@ namespace Swarmops.Database } - public int SetExpenseClaimRepaid (int expenseClaimId, bool repaid) + public int SetExpenseClaimRepaid(int expenseClaimId, bool repaid) { using (DbConnection connection = GetMySqlDbConnection()) { connection.Open(); - DbCommand command = GetDbCommand ("SetExpenseClaimRepaid", connection); + DbCommand command = GetDbCommand("SetExpenseClaimRepaid", connection); command.CommandType = CommandType.StoredProcedure; - AddParameterWithName (command, "expenseClaimId", expenseClaimId); - AddParameterWithName (command, "repaid", repaid); + AddParameterWithName(command, "expenseClaimId", expenseClaimId); + AddParameterWithName(command, "repaid", repaid); - return Convert.ToInt32 (command.ExecuteScalar()); + return Convert.ToInt32(command.ExecuteScalar()); + } + } + + + public void SetExpenseClaimGroup(int expenseClaimId, int expenseClaimGroupId) + { + using (DbConnection connection = GetMySqlDbConnection()) + { + connection.Open(); + + DbCommand command = GetDbCommand("SetExpenseClaimGroup", connection); + command.CommandType = CommandType.StoredProcedure; + + AddParameterWithName(command, "expenseClaimId", expenseClaimId); + AddParameterWithName(command, "expenseClaimGroupId", expenseClaimGroupId); + + command.ExecuteNonQuery(); } } diff --git a/Database/Database.csproj b/Database/Database.csproj index d5ea05cc..165c92c5 100644 --- a/Database/Database.csproj +++ b/Database/Database.csproj @@ -61,6 +61,7 @@ + diff --git a/Database/Schemata/revisions.txt b/Database/Schemata/revisions.txt index 52df7730..197b4488 100644 --- a/Database/Schemata/revisions.txt +++ b/Database/Schemata/revisions.txt @@ -66,3 +66,4 @@ 0066 - Added OrganizationSequenceId to CashAdvances, ExpenseClaims [RF] 0067 - Bugfix for 0066 [RF] 0068 - Added SetSalaryOpen [RF] +0069 - Added table, procs for ExpenseClaimGroups [RF] \ No newline at end of file diff --git a/Database/Schemata/upgrade-0069.sql b/Database/Schemata/upgrade-0069.sql new file mode 100644 index 00000000..7de7fd06 --- /dev/null +++ b/Database/Schemata/upgrade-0069.sql @@ -0,0 +1,111 @@ +ALTER TABLE `ExpenseClaims` +ADD COLUMN `ExpenseClaimGroupId` INT(11) NOT NULL DEFAULT 0 AFTER `ClosedDateTime`, +ADD INDEX `Index_GroupId` (`ExpenseClaimGroupId` ASC) + +# + +CREATE TABLE `ExpenseClaimGroups` ( + `ExpenseClaimGroupId` INT NOT NULL AUTO_INCREMENT, + `OrganizationId` INT NOT NULL, + `CreatedDateTime` DATETIME NOT NULL, + `CreatedByPersonId` INT NOT NULL, + `Open` TINYINT NOT NULL DEFAULT 1, + `ExpenseClaimGroupTypeId` INT NOT NULL, + `ExpenseClaimGroupData` TEXT NOT NULL, + PRIMARY KEY (`ExpenseClaimGroupId`), + INDEX `Idx_Person` (`CreatedByPersonId` ASC), + INDEX `Idx_Time` (`CreatedDateTime` ASC), + INDEX `Idx_Org` (`OrganizationId` ASC), + INDEX `Idx_Open` (`Open` ASC), + INDEX `Idx_Type` (`ExpenseClaimGroupTypeId` ASC)) + +# + +CREATE TABLE `ExpenseClaimGroupTypes` ( + `ExpenseClaimGroupTypeId` INT NOT NULL AUTO_INCREMENT, + `Name` VARCHAR(64) NOT NULL, + PRIMARY KEY (`ExpenseClaimGroupTypeId`)) + +# + +DROP PROCEDURE IF EXISTS `CreateExpenseClaimGroup` + +# + +DROP PROCEDURE IF EXISTS `SetExpenseClaimGroup` + +# + +DROP PROCEDURE IF EXISTS `SetExpenseClaimGroupClosed` + +# + +CREATE PROCEDURE `CreateExpenseClaimGroup`( + IN organizationId INT, + IN dateTime DATETIME, + IN createdByPersonId INT, + IN expenseClaimGroupType VARCHAR(64), + IN expenseClaimGroupData TEXT +) +BEGIN + + DECLARE expenseClaimGroupTypeId INT; + + IF ((SELECT COUNT(*) FROM ExpenseClaimGroupTypes WHERE ExpenseClaimGroupTypes.Name=expenseClaimGroupType) = 0) + THEN + INSERT INTO ExpenseClaimGroupTypes (Name) VALUES (expenseClaimGroupType); + SELECT LAST_INSERT_ID() INTO expenseClaimGroupTypeId; + ELSE + SELECT ExpenseClaimGroupTypes.ExpenseClaimGroupTypeId + INTO expenseclaimGroupTypeId FROM ExpenseClaimGroupTypes + WHERE ExpenseClaimGroupTypes.Name = expenseClaimGroupType; + END IF; + + INSERT INTO ExpenseClaimGroups (OrganizationId,CreatedDateTime,CreatedByPersonId,ExpenseClaimGroupTypeId,ExpenseClaimGroupData) + VALUES (organizationId,dateTime,createdByPersonId,expenseClaimGroupTypeId,expenseClaimGroupData); + + SELECT LAST_INSERT_ID() AS Identity; + +END + +# + +CREATE PROCEDURE `SetExpenseClaimGroupClosed` ( + IN expenseClaimGroupId +) +BEGIN + DECLARE createdByPersonId INT; + DECLARE organizationId INT; + + SELECT ExpenseClaimGroups.CreatedByPersonId + INTO createdByPersonId + WHERE ExpenseClaimGroups.ExpenseClaimGroupId = expenseClaimGroupId; + + SELECT ExpenseClaimGroups.OrganizationId + INTO organizationId + WHERE ExpenseClaimGroups.ExpenseClaimGroupId = expenseClaimGroupId; + + UPDATE ExpenseClaimGroups + SET ExpenseClaimGroups.Open = 0 + WHERE ExpenseClaimGroups.ExpenseClaimGroupId = expenseClaimGroupId; + + UPDATE ExpenseClaims + SET ClaimingPersonId = createdByPersonId, + OrganizationId = organizationId + WHERE ExpenseClaimGroupId = expenseClaimGroupId; + +END + +# + +CREATE PROCEDURE `SetExpenseClaimGroup` ( + IN expenseClaimId, + IN expenseClaimGroupId +) +BEGIN + UPDATE ExpenseClaims + SET ExpenseClaimGroupId=expenseClaimGroupId + WHERE ExpenseClaimId=expenseClaimId; +END + + diff --git a/FrontSocket/FrontendServices.cs b/FrontSocket/FrontendServices.cs index 5858b8e7..a6d6f2e2 100644 --- a/FrontSocket/FrontendServices.cs +++ b/FrontSocket/FrontendServices.cs @@ -57,20 +57,24 @@ namespace Swarmops.Frontend.Socket break; case "ConvertPdf": JArray pdfFilesArray = (JArray) json["PdfFiles"]; - List pdfFilesList = new List(); - foreach (string pdfFileString in pdfFilesArray) + JArray pdfClientNamesArray = (JArray)json["ClientFileNames"]; + + List rasterizationTargets = new List(); + for (int loop = 0; loop < pdfFilesArray.Count; loop++) { - pdfFilesList.Add(pdfFileString); + rasterizationTargets.Add(new RasterizationTarget + { + FullyQualifiedFileName = (string) pdfFilesArray[loop], + ClientFileName = (string) pdfClientNamesArray[loop], + }); } - JArray pdfClientNamesArray = (JArray) json["ClientFileNames"]; - List pdfClientNames = new List(); - foreach (string pdfClientName in pdfClientNamesArray) - { - pdfClientNames.Add(pdfClientName); - } + Organization organization = Organization.FromIdentity((int)json["OrganizationId"]); - ConvertPdf(pdfFilesList.ToArray(), pdfClientNames.ToArray(), (string) json["Guid"], Person.FromIdentity((int) json["PersonId"]), Organization.FromIdentity((int) json["OrganizationId"])); + PdfProcessor pdfMaker = new PdfProcessor(); + pdfMaker.RasterizationProgress += BroadcastGuidProgress; + pdfMaker.RasterizeMany(rasterizationTargets.ToArray(), (string) json["Guid"], _authority.Person, + _authority.Organization); break; case "ConvertPdfHires": @@ -142,214 +146,187 @@ namespace Swarmops.Frontend.Socket // Sessions.Broadcast("{\"messageType\":\"EditorCount\"," + String.Format("\"editorCount\":\"{0}\"", Sessions.ActiveIDs.ToArray().Length) + '}'); } + /* private void ConvertPdf(string[] pdfFiles, string[] pdfClientNames, string guid, Person person, Organization organization) { List failedConversionFileNames = new List(); - using (StreamWriter debugWriter = new StreamWriter("/tmp/PdfConversionDebug-" + guid + ".txt")) + try { + int fileCount = pdfFiles.Length; - try + Process process = null; + Document lastDocument = null; + + for (int fileIndex = 0; fileIndex < fileCount; fileIndex++) { - debugWriter.WriteLine("ConvertPdf started"); + // Set progress to indicate we're at file 'index' of 'fileCount' - int fileCount = pdfFiles.Length; + int progress = fileIndex * 99 / fileCount; // 99 at most -- 100 indicates complete + int progressFileStep = 99 / fileCount; + int currentFilePageCount = 0; + int currentFilePageStepMilli = 0; - Process process = null; - Document lastDocument = null; + string relativeFileName = pdfFiles[fileIndex]; - for (int fileIndex = 0; fileIndex < fileCount; fileIndex++) + // Use qpdf to determine the number of pages in the PDF + + string pageCountFileName = "/tmp/pagecount-" + guid + ".txt"; + + process = Process.Start("bash", + "-c \"qpdf --show-npages " + Document.StorageRoot + relativeFileName + " > " + pageCountFileName + "\""); + + process.WaitForExit(); + + if (process.ExitCode == 2) { - // Set progress to indicate we're at file 'index' of 'fileCount' - - int progress = fileIndex * 99 / fileCount; // 99 at most -- 100 indicates complete - int progressFileStep = 99 / fileCount; - int currentFilePageCount = 0; - int currentFilePageStepMilli = 0; - - string relativeFileName = pdfFiles[fileIndex]; - - debugWriter.WriteLine("------------------------------------"); - debugWriter.WriteLine("{3:D2}%, Converting PDF file {0} of {1}; {2}", fileIndex + 1, fileCount, - relativeFileName, progress); - - // Use qpdf to determine the number of pages in the PDF - - string pageCountFileName = "/tmp/pagecount-" + guid + ".txt"; - - process = Process.Start("bash", - "-c \"qpdf --show-npages " + Document.StorageRoot + relativeFileName + " > " + pageCountFileName + "\""); - - process.WaitForExit(); - - if (process.ExitCode == 2) - { - // Bad PDF file - failedConversionFileNames.Add( - ((string[])GuidCache.Get("PdfClientNames-" + guid))[fileIndex].Replace("'", "") - .Replace("\"", "")); // caution; we're displaying user input, guard against XSS - continue; - } - - // Read the resulting page count from the file we piped - - using (StreamReader pageCountReader = new StreamReader(pageCountFileName)) - { - string line = pageCountReader.ReadLine().Trim(); - while (line.StartsWith("WARNING") || line.StartsWith("qpdf:")) - { - line = pageCountReader.ReadLine().Trim(); // ignore warnings and chatter - } - currentFilePageCount = Int32.Parse(line); - debugWriter.WriteLine("{0:D2}%, parsed to int as {1}", progress, currentFilePageCount); - currentFilePageStepMilli = progressFileStep * 1000 / currentFilePageCount; - } - - File.Delete(pageCountFileName); - - // Begin the conversion - - debugWriter.WriteLine("{0:D2}%, deleted page count file, starting conversion process", progress); - - // Density 75 means 75dpi means conversion - // Hires 600dpi conversion is also made, but from backend after this conversion - - process = Process.Start("bash", - "-c \"convert -density 75 -background white -alpha remove " + Document.StorageRoot + relativeFileName + - " " + Document.StorageRoot + relativeFileName + "-%04d.png\""); - - int pageCounter = 0; // the first produced page will be zero - string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); - debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName); - string lastPageFileName = testPageFileName; - - // Convert works by first calling imagemagick that creates /tmp/magick-* files - - int lastProgress = 0; - - while (pageCounter < currentFilePageCount) - { - while (!File.Exists(Document.StorageRoot + testPageFileName)) - { - // Wait for file to appear - - debugWriter.WriteLine("{0:D2}%, {2:O}, waiting for page #{1} to appear", progress, pageCounter + 1, DateTime.UtcNow); - debugWriter.Flush(); - GuidCache.Set("Pdf-" + guid + "-Progress", progress); - - if (!process.HasExited) - { - process.WaitForExit(250); - } - - if (pageCounter == 0) - { - // If first page hasn't appeared yet, check for the Magick temp files - - int currentMagickCount = Directory.GetFiles("/tmp", "magick-*").Count(); - int currentFilePercentage = currentMagickCount*50/currentFilePageCount; - if (currentFilePercentage > 50) - { - currentFilePercentage = 50; // we may be not the only one converting right now - } - - progress = progressFileStep*fileIndex + currentFilePercentage*100/progressFileStep; - if (progress > lastProgress) // can't use Not-Equal; temp files slowly deleted before next step - { - BroadcastGuidProgress(organization, guid, progress); - lastProgress = progress; - } - } - } - - progress = progressFileStep * fileIndex + progressFileStep / 2 + currentFilePageStepMilli * (pageCounter + 1) / 2000; - if (progress != lastProgress) - { - BroadcastGuidProgress(organization, guid, progress); - lastProgress = progress; - } - - debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter + 1); - - // If the page# file that has appeared is 1+, then the preceding file is ready - - if (pageCounter > 0) - { - long fileLength = new FileInfo(Document.StorageRoot + lastPageFileName).Length; - debugWriter.WriteLine("{0:D2}%, saving page #{1}, bytecount {2}", progress, pageCounter, fileLength); - - Document.Create(lastPageFileName, pdfClientNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), - fileLength, guid, null, person); - - // Set to readonly, lock out changes, permit all read - - Syscall.chmod(Document.StorageRoot + lastPageFileName, - FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); - - // Prepare to save the next file - lastPageFileName = testPageFileName; - } - - // Increase the page counter and the file we're looking for - - pageCounter++; - testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); - debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName); - } - - // We've seen the last page being written -- wait for process to exit to assure it's complete - debugWriter.WriteLine("{0:D2}%, waiting for process exit", progress); - - if (!process.HasExited) - { - process.WaitForExit(); - } - - // Save the last page - - long fileLengthLastPage = new FileInfo(Document.StorageRoot + lastPageFileName).Length; - debugWriter.WriteLine("{0:D2}%, saving last page #{1}, bytecount {2}", progress, pageCounter, fileLengthLastPage); - - lastDocument = Document.Create(lastPageFileName, - pdfClientNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), - fileLengthLastPage, guid, null, person); - - // Set to readonly, lock out changes, permit all read - - Syscall.chmod(Document.StorageRoot + lastPageFileName, - FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); - - // Finally, ask the backend to do the high-res conversions, but now we have the basic, fast ones - - RasterizeDocumentHiresOrder backendOrder = new RasterizeDocumentHiresOrder(lastDocument); - backendOrder.Create(); - + // Bad PDF file + failedConversionFileNames.Add( + ((string[])GuidCache.Get("PdfClientNames-" + guid))[fileIndex].Replace("'", "") + .Replace("\"", "")); // caution; we're displaying user input, guard against XSS + continue; } - } - catch (Exception e) - { - debugWriter.WriteLine("Exception thrown: " + e.ToString()); + // Read the resulting page count from the file we piped - throw; - } - finally - { - debugWriter.WriteLine("Handler exiting"); + using (StreamReader pageCountReader = new StreamReader(pageCountFileName)) + { + string line = pageCountReader.ReadLine().Trim(); + while (line.StartsWith("WARNING") || line.StartsWith("qpdf:")) + { + line = pageCountReader.ReadLine().Trim(); // ignore warnings and chatter + } + currentFilePageCount = Int32.Parse(line); + currentFilePageStepMilli = progressFileStep * 1000 / currentFilePageCount; + } + + File.Delete(pageCountFileName); + + // Begin the conversion + + // Density 75 means 75dpi means conversion + // Hires 600dpi conversion is also made, but from backend after this conversion + + process = Process.Start("bash", + "-c \"convert -density 75 -background white -alpha remove " + Document.StorageRoot + relativeFileName + + " " + Document.StorageRoot + relativeFileName + "-%04d.png\""); + + int pageCounter = 0; // the first produced page will be zero + string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + string lastPageFileName = testPageFileName; + + // Convert works by first calling imagemagick that creates /tmp/magick-* files + + int lastProgress = 0; + + while (pageCounter < currentFilePageCount) + { + while (!File.Exists(Document.StorageRoot + testPageFileName)) + { + // Wait for file to appear + + if (!process.HasExited) + { + process.WaitForExit(250); + } + + if (pageCounter == 0) + { + // If first page hasn't appeared yet, check for the Magick temp files + + int currentMagickCount = Directory.GetFiles("/tmp", "magick-*").Count(); + int currentFilePercentage = currentMagickCount*50/currentFilePageCount; + if (currentFilePercentage > 50) + { + currentFilePercentage = 50; // we may be not the only one converting right now + } + + progress = progressFileStep*fileIndex + currentFilePercentage*100/progressFileStep; + if (progress > lastProgress) // can't use Not-Equal; temp files slowly deleted before next step + { + BroadcastGuidProgress(organization, guid, progress); + lastProgress = progress; + } + } + } + + progress = progressFileStep * fileIndex + progressFileStep / 2 + currentFilePageStepMilli * (pageCounter + 1) / 2000; + if (progress != lastProgress) + { + BroadcastGuidProgress(organization, guid, progress); + lastProgress = progress; + } + + // If the page# file that has appeared is 1+, then the preceding file is ready + + if (pageCounter > 0) + { + long fileLength = new FileInfo(Document.StorageRoot + lastPageFileName).Length; + + Document.Create(lastPageFileName, pdfClientNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), + fileLength, guid, null, person); + + // Set to readonly, lock out changes, permit all read + + Syscall.chmod(Document.StorageRoot + lastPageFileName, + FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); + + // Prepare to save the next file + lastPageFileName = testPageFileName; + } + + // Increase the page counter and the file we're looking for + + pageCounter++; + testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + } + + // We've seen the last page being written -- wait for process to exit to assure it's complete + + if (!process.HasExited) + { + process.WaitForExit(); + } + + // Save the last page + + long fileLengthLastPage = new FileInfo(Document.StorageRoot + lastPageFileName).Length; + + lastDocument = Document.Create(lastPageFileName, + pdfClientNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture), + fileLengthLastPage, guid, null, person); + + // Set to readonly, lock out changes, permit all read + + Syscall.chmod(Document.StorageRoot + lastPageFileName, + FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); + + // Finally, ask the backend to do the high-res conversions, but now we have the basic, fast ones + + RasterizeDocumentHiresOrder backendOrder = new RasterizeDocumentHiresOrder(lastDocument); + backendOrder.Create(); - BroadcastGuidProgress(organization, guid, 100); } + } - } + catch (Exception e) + { + throw; + } + finally + { + BroadcastGuidProgress(organization, guid, 100); + } + }*/ - private void BroadcastGuidProgress(Organization organization, string guid, int progress) + private void BroadcastGuidProgress(object sender, ProgressEventArgs args) { JObject json = new JObject(); json["MessageType"] = "ProgressUpdate"; - json["Guid"] = guid.Replace("-", "_"); // necessary to be a JS token - json["Progress"] = progress; + json["Guid"] = args.Guid.Replace("-", "_"); // necessary to be a JS token + json["Progress"] = args.Progress; - FrontendLoop.BroadcastToOrganization(organization, json); + FrontendLoop.BroadcastToOrganization(args.Organization, json); } public Authority Authority { get { return this._authority; } } diff --git a/Logic/Financial/ExpenseClaim.cs b/Logic/Financial/ExpenseClaim.cs index a88e54fc..2e6b0dfb 100644 --- a/Logic/Financial/ExpenseClaim.cs +++ b/Logic/Financial/ExpenseClaim.cs @@ -42,58 +42,70 @@ namespace Swarmops.Logic.Financial } public static ExpenseClaim Create (Person claimer, Organization organization, FinancialAccount budget, - DateTime expenseDate, string description, Int64 amountCents, Int64 vatCents) + DateTime expenseDate, string description, Int64 amountCents, Int64 vatCents, ExpenseClaimGroup group = null) { ExpenseClaim newClaim = FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() - .CreateExpenseClaim (claimer.Identity, organization.Identity, - budget.Identity, expenseDate, description, amountCents)); + .CreateExpenseClaim (claimer.Identity, organization?.Identity ?? 0, + budget?.Identity ?? 0, expenseDate, description, amountCents)); // budget can be 0 initially if created with a group if (vatCents > 0) { newClaim.VatCents = vatCents; } - // Create the financial transaction with rows - - string transactionDescription = "Expense #" + newClaim.OrganizationSequenceId + ": " + description; // TODO: Localize - - if (transactionDescription.Length > 64) + if (group != null) { - transactionDescription = transactionDescription.Substring (0, 61) + "..."; + newClaim.Group = group; } - FinancialTransaction transaction = - FinancialTransaction.Create (organization.Identity, DateTime.Now, - transactionDescription); - - transaction.AddRow (organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); - if (vatCents > 0) + if (budget != null && organization != null) { - transaction.AddRow(budget, amountCents - vatCents, claimer); - transaction.AddRow(organization.FinancialAccounts.AssetsVatInboundUnreported, vatCents, claimer); + // Create the financial transaction with rows + + string transactionDescription = "Expense #" + newClaim.OrganizationSequenceId + ": " + description; + // TODO: Localize + + if (transactionDescription.Length > 64) + { + transactionDescription = transactionDescription.Substring(0, 61) + "..."; + } + + FinancialTransaction transaction = + FinancialTransaction.Create(organization.Identity, DateTime.Now, + transactionDescription); + + transaction.AddRow(organization.FinancialAccounts.DebtsExpenseClaims, -amountCents, claimer); + if (vatCents > 0) + { + transaction.AddRow(budget, amountCents - vatCents, claimer); + transaction.AddRow(organization.FinancialAccounts.AssetsVatInboundUnreported, vatCents, claimer); + } + else + { + transaction.AddRow(budget, amountCents, claimer); + } + + // Make the transaction dependent on the expense claim + + transaction.Dependency = newClaim; + + // Create notifications + + OutboundComm.CreateNotificationAttestationNeeded(budget, claimer, string.Empty, + newClaim.BudgetAmountCents/100.0, + description, NotificationResource.ExpenseClaim_Created); + // Slightly misplaced logic, but failsafer here + OutboundComm.CreateNotificationFinancialValidationNeeded(organization, newClaim.AmountCents/100.0, + NotificationResource.Receipts_Filed); + SwarmopsLogEntry.Create(claimer, + new ExpenseClaimFiledLogEntry(claimer /*filing person*/, claimer /*beneficiary*/, + newClaim.BudgetAmountCents/100.0, + vatCents/100.0, budget, description), newClaim); + + // Clear a cache + FinancialAccount.ClearAttestationAdjustmentsCache(organization); } - else - { - transaction.AddRow(budget, amountCents, claimer); - } - - // Make the transaction dependent on the expense claim - - transaction.Dependency = newClaim; - - // Create notifications - - OutboundComm.CreateNotificationAttestationNeeded (budget, claimer, string.Empty, newClaim.BudgetAmountCents/100.0, - description, NotificationResource.ExpenseClaim_Created); // Slightly misplaced logic, but failsafer here - OutboundComm.CreateNotificationFinancialValidationNeeded (organization, newClaim.AmountCents/100.0, - NotificationResource.Receipts_Filed); - SwarmopsLogEntry.Create (claimer, - new ExpenseClaimFiledLogEntry (claimer /*filing person*/, claimer /*beneficiary*/, newClaim.BudgetAmountCents/100.0, - vatCents / 100.0, budget, description), newClaim); - - // Clear a cache - FinancialAccount.ClearAttestationAdjustmentsCache(organization); return newClaim; } @@ -167,6 +179,28 @@ namespace Swarmops.Logic.Financial get { return Organization.FromIdentity (OrganizationId); } } + public ExpenseClaimGroup Group + { + get + { + if (this.GroupId == 0) + { + return null; + } + + return ExpenseClaimGroup.FromIdentity(this.GroupId); + } + set + { + int newGroupId = value?.Identity ?? 0; + + if (this.GroupId != newGroupId) + { + SwarmDb.GetDatabaseForWriting().SetExpenseClaimGroup(this.Identity, newGroupId); + } + } + } + public FinancialTransaction FinancialTransaction { get @@ -175,7 +209,7 @@ namespace Swarmops.Logic.Financial if (transactions.Count == 0) { - return null; // not possible from July 26 onwards, but some grandfather work + return null; // Only for grouped transactions that are still under construction } if (transactions.Count == 1) diff --git a/Logic/Financial/ExpenseClaimGroup.cs b/Logic/Financial/ExpenseClaimGroup.cs new file mode 100644 index 00000000..94fb73e5 --- /dev/null +++ b/Logic/Financial/ExpenseClaimGroup.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Basic.Types.Financial; +using Swarmops.Common.Enums; +using Swarmops.Database; +using Swarmops.Logic.Swarm; +using Swarmops.Logic.Structure; + +namespace Swarmops.Logic.Financial +{ + public class ExpenseClaimGroup: BasicExpenseClaimGroup + { + private ExpenseClaimGroup(BasicExpenseClaimGroup basic) + : base (basic) + { + // private ctor + } + + public static ExpenseClaimGroup FromBasic(BasicExpenseClaimGroup basic) + { + return new ExpenseClaimGroup(basic); + } + + public static ExpenseClaimGroup FromIdentity(int expenseClaimGroupId) + { + return FromBasic(SwarmDb.GetDatabaseForReading().GetExpenseClaimGroup(expenseClaimGroupId)); + } + + internal static ExpenseClaimGroup FromIdentityAggressive(int expenseClaimGroupId) + { + return FromBasic(SwarmDb.GetDatabaseForWriting().GetExpenseClaimGroup(expenseClaimGroupId)); // "writing" intentional + } + + public static ExpenseClaimGroup Create(Organization organization, Person creatingPerson, ExpenseClaimGroupType groupType, + string rawGroupData) + { + return FromIdentityAggressive(SwarmDb.GetDatabaseForWriting().CreateExpenseClaimGroup(organization.Identity, creatingPerson.Identity, groupType, rawGroupData)); + } + + public new bool Open + { + get { return base.Open; } + set + { + if (value != base.Open) + { + // change of boolean value + + if (!base.Open) + { + // only one direction permitted + } + + SwarmDb.GetDatabaseForWriting().SetExpenseClaimGroupClosed(this.Identity); + base.Open = false; + } + } + } + } +} diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index b76f236f..cdb56250 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -134,6 +134,7 @@ + diff --git a/Logic/Support/Document.cs b/Logic/Support/Document.cs index e12d4d8d..6faa87cb 100644 --- a/Logic/Support/Document.cs +++ b/Logic/Support/Document.cs @@ -73,6 +73,39 @@ namespace Swarmops.Logic.Support } } + public static string DailyStorageFolder + { + get + { + DateTime utcNow = DateTime.UtcNow; + + string root = Document.StorageRoot; + + string dayFolder = utcNow.Year.ToString("0000") + Path.DirectorySeparatorChar + + utcNow.Month.ToString("00") + Path.DirectorySeparatorChar + + utcNow.Day.ToString("00"); + + string wholePath = root + dayFolder; + + if (!Directory.Exists(wholePath)) + { + Directory.CreateDirectory(wholePath); + + // Set folder permissions to rwxrwxrwx if live environment + // (backend must be able to create new files) + + if (!Debugger.IsAttached) // check if live environment + { + Syscall.chmod(wholePath, + FilePermissions.S_IRWXU | FilePermissions.S_IRWXO | FilePermissions.S_IRWXG); + } + + } + + return wholePath + Path.DirectorySeparatorChar; + } + } + public static Document FromIdentity (int documentId) { return FromBasic (SwarmDb.GetDatabaseForReading().GetDocument (documentId)); diff --git a/Logic/Support/PdfProcessor.cs b/Logic/Support/PdfProcessor.cs index 391c9efd..4f51f134 100644 --- a/Logic/Support/PdfProcessor.cs +++ b/Logic/Support/PdfProcessor.cs @@ -8,7 +8,12 @@ using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; +using Mono.Unix.Native; +using Swarmops.Logic.Cache; +using Swarmops.Logic.Structure; using Swarmops.Logic.Support; +using Swarmops.Logic.Support.BackendServices; +using Swarmops.Logic.Swarm; namespace Swarmops.Logic.Support { @@ -16,6 +21,9 @@ namespace Swarmops.Logic.Support { private static readonly string StorageRoot = Document.StorageRoot; + public delegate void ProgressEventHandler(object sender, ProgressEventArgs args); + public event ProgressEventHandler RasterizationProgress; + [Flags] public enum PdfProcessorOptions { @@ -24,6 +32,250 @@ namespace Swarmops.Logic.Support ForceOrphans = 0x0002 }; + public static int GetPageCount(string fullyQualifiedFileName) + { + if (Debugger.IsAttached) + { + // This call is intended for live environments only; if a debugger is attached, break because something's wrong + + Debugger.Break(); + } + + // If we have the page count in cache, use it + + object cachedObject = GuidCache.Get("PdfPageCount-" + fullyQualifiedFileName); + if (cachedObject != null) + { + return (int) cachedObject; + } + + // Use qpdf to determine the number of pages in the PDF + + string pageCountFileName = "/tmp/pagecount-" + Guid.NewGuid().ToString() + ".txt"; + + Process process = Process.Start("bash", + "-c \"qpdf --show-npages " + fullyQualifiedFileName + " > " + pageCountFileName + + "\""); + + process.WaitForExit(); + int pdfPageCount = 0; + + if (process.ExitCode == 2) // error code for qpdf + { + throw new FormatException("Bad PDF file"); + } + + // Read the resulting page count from the file we piped + + using (StreamReader pageCountReader = new StreamReader(pageCountFileName)) + { + string line = pageCountReader.ReadLine().Trim(); + while (line.StartsWith("WARNING") || line.StartsWith("qpdf:")) + { + line = pageCountReader.ReadLine().Trim(); // ignore warnings and chatter + } + pdfPageCount = Int32.Parse(line); + } + + File.Delete(pageCountFileName); + + GuidCache.Set("PdfPageCount-" + fullyQualifiedFileName, pdfPageCount); + + return pdfPageCount; + } + + + public Documents RasterizeMany(RasterizationTarget[] targets, string guid, Person uploader, + Organization organization) + { + Documents result = new Documents(); + + int pageCountTotal = 0; + int pageCountRunning = 0; + + + foreach (RasterizationTarget target in targets) + { + pageCountTotal += GetPageCount(target.FullyQualifiedFileName); + } + + + foreach (RasterizationTarget target in targets) + { + int pdfPageCount = GetPageCount(target.FullyQualifiedFileName); // cached + + // Create progress range + + ProgressRange range = new ProgressRange + { + Minimum = pageCountRunning * 100 / pageCountTotal, + Maximum = (pageCountRunning + pdfPageCount) * 100 / pageCountTotal + }; + + // Request one conversion + + Documents docs = RasterizeOne(target.FullyQualifiedFileName, target.ClientFileName, guid, uploader, + organization, range); + + // Update pages converted + + pageCountRunning += pdfPageCount; + + // Finally, ask the backend to do the high-res conversions, but now we have the basic, fast ones + + if (docs.Count > 0) + { + RasterizeDocumentHiresOrder backendOrder = new RasterizeDocumentHiresOrder(docs[0]); + backendOrder.Create(); + } + } + + + return result; + } + + + + public Documents RasterizeOne (string fullyQualifiedFileName, string clientFileName, string guid, Person uploader, Organization organization = null, ProgressRange progressRange = null) + { + int pdfPageCount = GetPageCount(fullyQualifiedFileName); + string relativeFileName = fullyQualifiedFileName.Substring(Document.StorageRoot.Length); + + Process process = Process.Start("bash", + "-c \"convert -density 75 -background white -alpha remove " + fullyQualifiedFileName + + " " + fullyQualifiedFileName + "-%04d.png\""); + + Documents documents = new Documents(); + + if (progressRange == null) + { + progressRange = new ProgressRange(); + } + + int pageCounter = 0; // the first produced page will be zero + string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + string lastPageFileName = testPageFileName; + + // Convert works by first calling imagemagick that creates /tmp/magick-* files + + int lastProgress = progressRange.Minimum; + int progress = progressRange.Minimum; + + while (pageCounter < pdfPageCount) + { + while (!File.Exists(Document.StorageRoot + testPageFileName)) + { + // Wait for file to appear + + if (!process.HasExited) + { + process.WaitForExit(250); + } + + if (pageCounter == 0) + { + // If first page hasn't appeared yet, check for the Magick temp files + + int currentMagickCount = Directory.GetFiles("/tmp", "magick-*").Count(); + int currentFilePercentage = currentMagickCount * 50 / pdfPageCount; + if (currentFilePercentage > 50) + { + currentFilePercentage = 50; // we may be not the only one converting right now + } + + progress = progressRange.Minimum + currentFilePercentage * 100 / progressRange.Range; + if (progress > lastProgress) // can't use Not-Equal; temp files slowly deleted before next step + { + BroadcastProgress(organization, guid, progress); + lastProgress = progress; + } + } + } + + progress = progressRange.Minimum + progressRange.Range / 2 + (pageCounter + 1) * progressRange.Range / pdfPageCount; + if (progress > lastProgress) + { + BroadcastProgress(organization, guid, progress); + lastProgress = progress; + } + + // If the page# file that has appeared is 1+, then the preceding file is ready + + if (pageCounter > 0) + { + long fileLength = new FileInfo(Document.StorageRoot + lastPageFileName).Length; + + documents.Add( Document.Create(lastPageFileName, + clientFileName + " " + (pageCounter + 1).ToString(CultureInfo.InvariantCulture) + "/" + pdfPageCount.ToString(CultureInfo.InvariantCulture), + fileLength, guid, null, uploader)); + + // Set to readonly, lock out changes, permit all read + + Syscall.chmod(Document.StorageRoot + lastPageFileName, + FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); + + // Prepare to save the next file + lastPageFileName = testPageFileName; + } + + // Increase the page counter and the file we're looking for + + pageCounter++; + testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + } + + // We've seen the last page being written -- wait for process to exit to assure it's complete + + if (!process.HasExited) + { + process.WaitForExit(); + } + + // Save the last page + + long fileLengthLastPage = new FileInfo(Document.StorageRoot + lastPageFileName).Length; + + documents.Add(Document.Create(lastPageFileName, + clientFileName + " " + (pageCounter + 1).ToString(CultureInfo.InvariantCulture) + "/" + pdfPageCount.ToString(CultureInfo.InvariantCulture), + fileLengthLastPage, guid, null, uploader)); + + // Set to readonly, lock out changes, permit all read + + Syscall.chmod(Document.StorageRoot + lastPageFileName, + FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); + + + /* -- OLD CODE BELOW -- + process.WaitForExit(); + + int pageCounter = 0; // the first produced page will be zero + + // Create all document records + + + while (pageCounter < pdfPageCount) + { + string pageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); + + if (File.Exists(Document.StorageRoot + pageFileName)) + { + long fileLength = new FileInfo(Document.StorageRoot + pageFileName).Length; + + documents.Add(Document.Create(pageFileName, + clientFileName + " " + (pageCounter + 1).ToString(CultureInfo.InvariantCulture) + "/" + pdfPageCount.ToString(CultureInfo.InvariantCulture), + fileLength, guid, null, uploader)); + + Syscall.chmod(Document.StorageRoot + pageFileName, + FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); + + } + + pageCounter++; + } */ + + return documents; + } + public static void RerasterizeAll() { // Because of a bug with transparent-background PDFs converting to black-background bitmaps, all PDFs imaged before @@ -186,5 +438,46 @@ namespace Swarmops.Logic.Support return tempFileName; } + + private void BroadcastProgress(Organization organization, string guid, int progress) + { + if (RasterizationProgress != null) + { + RasterizationProgress(this, new ProgressEventArgs + { + Guid = guid, + Organization = organization, + Progress = progress + }); + } + } } + + public class RasterizationTarget + { + public string FullyQualifiedFileName { get; set; } + public string ClientFileName { get; set; } + } + + public class ProgressRange + { + public ProgressRange() // default values + { + this.Minimum = 0; + this.Maximum = 100; + } + + public int Minimum { get; set; } + public int Maximum { get; set; } + + public int Range => Maximum - Minimum; + } + + public class ProgressEventArgs : EventArgs + { + public Organization Organization { get; set; } + public string Guid { get; set; } + public int Progress { get; set; } + } + } diff --git a/Site/Automation/UploadFileHandler.ashx b/Site/Automation/UploadFileHandler.ashx index c720fdc4..7b2145d8 100644 --- a/Site/Automation/UploadFileHandler.ashx +++ b/Site/Automation/UploadFileHandler.ashx @@ -28,13 +28,6 @@ namespace Swarmops.Frontend.Automation { private readonly JavaScriptSerializer js = new JavaScriptSerializer(); - public static string StorageRoot = Document.StorageRoot; - - private bool WeAreInDebugEnvironment - { - get { return Debugger.IsAttached; } - } - #region IHttpHandler Members public new bool IsReusable @@ -92,7 +85,7 @@ namespace Swarmops.Frontend.Automation // Delete file from the server private void DeleteFile(HttpContext context) { - string filePath = StorageRoot + context.Request["f"]; + string filePath = Document.StorageRoot + context.Request["f"]; if (File.Exists(filePath)) { File.Delete(filePath); @@ -124,7 +117,7 @@ namespace Swarmops.Frontend.Automation 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); + string fullName = Document.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."); @@ -212,35 +205,15 @@ namespace Swarmops.Frontend.Automation string fileNameBase = guid + "-" + uploadingPerson.Identity.ToString("X8").ToLowerInvariant() + "-" + currentOrg.Identity.ToString("X4").ToLowerInvariant(); - DateTime utcNow = DateTime.UtcNow; - - string fileFolder = utcNow.Year.ToString("0000") + Path.DirectorySeparatorChar + - utcNow.Month.ToString("00") + Path.DirectorySeparatorChar + - utcNow.Day.ToString("00"); - - if (!Directory.Exists(StorageRoot + fileFolder)) - { - Directory.CreateDirectory(StorageRoot + fileFolder); - - // Set folder permissions to rwxrwxrwx if live environment - // (backend must be able to create new files) - - if (!WeAreInDebugEnvironment) - { - Syscall.chmod(StorageRoot + fileFolder, - FilePermissions.S_IRWXU | FilePermissions.S_IRWXO| FilePermissions.S_IRWXG); - } - - } - int fileCounter = 0; - string fileName = string.Empty; + string fileName; + string storageFolder = Document.DailyStorageFolder; do { fileCounter++; fileName = fileNameBase + "-" + fileCounter.ToString("X2").ToLowerInvariant(); - } while (File.Exists(StorageRoot + fileFolder + Path.DirectorySeparatorChar + fileName) && + } while (File.Exists(storageFolder + Path.DirectorySeparatorChar + fileName) && fileCounter < 512); if (fileCounter >= 512) @@ -249,18 +222,19 @@ namespace Swarmops.Frontend.Automation "File name determination failed; probable file system permissions error"); } - string relativeFileName = fileFolder + Path.DirectorySeparatorChar + fileName; + string fullyQualifiedFileName = storageFolder + Path.DirectorySeparatorChar + fileName; + string relativeFileName = fullyQualifiedFileName.Substring(Document.StorageRoot.Length); file.InputStream.Position = 0; - file.SaveAs(StorageRoot + relativeFileName); + file.SaveAs(fullyQualifiedFileName); // Set file permissions to -r--r--r-- if live environment - if (!WeAreInDebugEnvironment) + if (!Debugger.IsAttached) { // Set to readonly, lock out changes, permit all read - Syscall.chmod(StorageRoot + relativeFileName, + Syscall.chmod(fullyQualifiedFileName, FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); } @@ -271,12 +245,11 @@ namespace Swarmops.Frontend.Automation Process process = null; - if (WeAreInDebugEnvironment) + if (Debugger.IsAttached) // Windows environment { process = Process.Start("cmd.exe", - "/c convert -background white -flatten " + StorageRoot + relativeFileName + " " + - StorageRoot + relativeFileName + - "-%04d.png"); + "/c convert -background white -flatten " + fullyQualifiedFileName + " " + + fullyQualifiedFileName + "-%04d.png"); process.WaitForExit(); @@ -297,20 +270,22 @@ namespace Swarmops.Frontend.Automation } else // live environment, not debug { - // Use qpdf to determine the number of pages in the PDF - - string pageCountFileName = "/tmp/pagecount-" + guid + ".txt"; - - process = Process.Start("bash", - "-c \"qpdf --show-npages " + StorageRoot + relativeFileName + " > " + pageCountFileName + - "\""); - - process.WaitForExit(); int pdfPageCount = 0; + bool exceptionThrown = false; - if (process.ExitCode == 2) // error code for qpdf + try + { + pdfPageCount = PdfProcessor.GetPageCount(fullyQualifiedFileName); + } + catch (FormatException) + { + exceptionThrown = true; + } + + if (exceptionThrown || pdfPageCount == 0) { // Bad PDF file + FilesStatus errorStatus = new FilesStatus(fullName, -1); //file.ContentLength); errorStatus.error = "ERR_BAD_PDF"; errorStatus.url = string.Empty; @@ -322,85 +297,22 @@ namespace Swarmops.Frontend.Automation continue; } - // Read the resulting page count from the file we piped - - using (StreamReader pageCountReader = new StreamReader(pageCountFileName)) - { - string line = pageCountReader.ReadLine().Trim(); - while (line.StartsWith("WARNING") || line.StartsWith("qpdf:")) - { - line = pageCountReader.ReadLine().Trim(); // ignore warnings and chatter - } - pdfPageCount = Int32.Parse(line); - } - - - File.Delete(pageCountFileName); - if (pdfPageCount < 10) { // Small file, so convert immediately instead of deferring - process = Process.Start("bash", - "-c \"convert -density 75 -background white -alpha remove " + Document.StorageRoot + relativeFileName + - " " + Document.StorageRoot + relativeFileName + "-%04d.png\""); + Documents docs = new PdfProcessor().RasterizeOne (fullyQualifiedFileName, file.FileName, guid, authData.CurrentUser); - process.WaitForExit(); + // Ask backend for high-res conversion -- assumes at least one page - int pageCounter = 0; // the first produced page will be zero - Document lastDocument = null; - - // Create all document records - - while (pageCounter < pdfPageCount) - { - string pageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter); - - if (File.Exists(Document.StorageRoot + pageFileName)) - { - long fileLength = new FileInfo(Document.StorageRoot + pageFileName).Length; - - lastDocument = Document.Create(pageFileName, - file.FileName + (pageCounter + 1).ToString(CultureInfo.InvariantCulture), - fileLength, guid, null, authData.CurrentUser); - - if (!WeAreInDebugEnvironment) - { - // Set to readonly, lock out changes, permit all read - - Syscall.chmod(Document.StorageRoot + pageFileName, - FilePermissions.S_IRUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH); - } - - } - - pageCounter++; - } - - // Ask backend for high-res conversion - - RasterizeDocumentHiresOrder backendOrder = new RasterizeDocumentHiresOrder(lastDocument); + RasterizeDocumentHiresOrder backendOrder = new RasterizeDocumentHiresOrder(docs[0]); backendOrder.Create(); - /* - using (WebSocket socket = - new WebSocket("ws://localhost:" + SystemSettings.WebsocketPortFrontend + "/Front?Auth=" + - Uri.EscapeDataString(authData.Authority.ToEncryptedXml()))) - { - socket.Connect(); - JObject data = new JObject(); - data["ServerRequest"] = "ConvertPdfHires"; - data["DocumentId"] = lastDocument.Identity; - socket.Send(data.ToString()); - socket.Ping(); // wait a little little while for send to work - socket.Close(); - }*/ - statuses.Add(new FilesStatus(fullName, file.ContentLength)); } else { - // Defer to backend + // Defer low-res conversion to frontend daemon (called from client) FilesStatus requiresConversion = new FilesStatus(fullName, -1); requiresConversion.requiresPdfConversion = true; @@ -417,7 +329,7 @@ namespace Swarmops.Frontend.Automation { // In all cases except PDF deferred, create the document - Document.Create(fileFolder + Path.DirectorySeparatorChar + fileName, file.FileName, + Document.Create(fullyQualifiedFileName, file.FileName, file.ContentLength, guid, null, authData.CurrentUser); @@ -446,6 +358,7 @@ namespace Swarmops.Frontend.Automation socket.Ping(); // wait a little little while for send to work socket.Close(); } + } } @@ -465,19 +378,6 @@ namespace Swarmops.Frontend.Automation public string[] FailFileNames { get; set; } } - private static void ConvertPdfThread(object args) - { - ProcessThreadArguments argsProper = (ProcessThreadArguments) args; - } - - - private class ProcessThreadArguments - { - public string Guid { get; set; } - public Organization Organization { get; set; } - public Person CurrentUser { get; set; } - } - private void WriteJsonIframeSafe(HttpContext context, List statuses) { @@ -506,7 +406,7 @@ namespace Swarmops.Frontend.Automation private void DeliverFile(HttpContext context) { string filename = context.Request["f"]; - string filePath = StorageRoot + filename; + string filePath = Document.StorageRoot + filename; if (File.Exists(filePath)) { @@ -522,7 +422,7 @@ namespace Swarmops.Frontend.Automation private void ListCurrentFiles(HttpContext context) { FileInfo[] files = - new DirectoryInfo(StorageRoot) + new DirectoryInfo(Document.StorageRoot) .GetFiles("*", SearchOption.TopDirectoryOnly); // completely wrong, redo from scratch diff --git a/Site/Pages/v5/Financial/FileExpenseClaim.aspx.cs b/Site/Pages/v5/Financial/FileExpenseClaim.aspx.cs index 96a71652..4eb7ee4f 100644 --- a/Site/Pages/v5/Financial/FileExpenseClaim.aspx.cs +++ b/Site/Pages/v5/Financial/FileExpenseClaim.aspx.cs @@ -1,19 +1,25 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Globalization; using System.IO; +using System.Net; +using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Web.Services; +using Newtonsoft.Json.Linq; using Swarmops.Interface.Support; using Swarmops.Logic.Cache; using Swarmops.Logic.Financial; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Support; +using Swarmops.Logic.Support.BackendServices; using Swarmops.Logic.Swarm; using Swarmops.Site.Pages.Ledgers; + namespace Swarmops.Frontend.Pages.v5.Financial { public partial class FileExpenseClaim : PageV5Base @@ -276,13 +282,17 @@ namespace Swarmops.Frontend.Pages.v5.Financial // TODO: Much more general-case error conditions if not all fields are filled - if (organization.VatEnabled || !fieldMap.ContainsKey(ExpensifyColumns.VatFloat)) + bool vatEnabled = organization.VatEnabled; + + if (vatEnabled && !fieldMap.ContainsKey(ExpensifyColumns.VatFloat)) { // Error: Organization needs a VAT field // TODO // Set result to bad // Set progress to complete // Abort + + throw new BarfException(); } List recordList = new List(); @@ -302,11 +312,11 @@ namespace Swarmops.Frontend.Pages.v5.Financial ExpensifyRecord newRecord = new ExpensifyRecord(); newRecord.AmountCents = - Formatting.ParseDoubleStringAsCents(recordFields[fieldMap[ExpensifyColumns.AmountFloat]]); + Formatting.ParseDoubleStringAsCents(recordFields[fieldMap[ExpensifyColumns.AmountFloat]], CultureInfo.InvariantCulture); newRecord.OriginalCurrency = Currency.FromCode(recordFields[fieldMap[ExpensifyColumns.OriginalCurrency]]); newRecord.OriginalAmountCents = Formatting.ParseDoubleStringAsCents( - recordFields[fieldMap[ExpensifyColumns.OriginalCurrencyAmountFloat]]); + recordFields[fieldMap[ExpensifyColumns.OriginalCurrencyAmountFloat]], CultureInfo.InvariantCulture); newRecord.Description = recordFields[fieldMap[ExpensifyColumns.Merchant]]; @@ -319,6 +329,15 @@ namespace Swarmops.Frontend.Pages.v5.Financial newRecord.CategoryStandard = recordFields[fieldMap[ExpensifyColumns.CategoryStandard]]; newRecord.ReceiptUrl = recordFields[fieldMap[ExpensifyColumns.ReceiptUrl]]; + newRecord.Timestamp = DateTime.Parse(recordFields[fieldMap[ExpensifyColumns.Timestamp]]); + + if (vatEnabled) + { + newRecord.VatCents = + Formatting.ParseDoubleStringAsCents(recordFields[fieldMap[ExpensifyColumns.VatFloat]], + CultureInfo.InvariantCulture); + } + recordList.Add(newRecord); } @@ -351,7 +370,78 @@ namespace Swarmops.Frontend.Pages.v5.Financial throw new BarfException(); // TODO: ASK USER } + // We now need to get all the receipt images. This is a little tricky as we don't have the URL + // of the receipt directly, we only have the URL of a webpage that contains JavaScript code + // to fetch the receipt image. + // Get relative date part + + string relativePath = Document.DailyStorageFolder.Substring(Document.StorageRoot.Length); + + // Get all receipts + + + + for (int loop = 0; loop < recordList.Count; loop++) + { + using (WebClient client = new WebClient()) + { + string receiptResource = client.DownloadString(recordList[loop].ReceiptUrl); + + // We now have the web page which holds information about where the actual receipt is located. + + Regex regex = new Regex("^\\svar transaction\\s*=(?.*);", RegexOptions.Multiline); + Match match = regex.Match(receiptResource); + if (match.Success) + { + string txInfoString = match.Groups["jsonTxInfo"].ToString(); + JObject txInfo = JObject.Parse(txInfoString); + recordList[loop].ExtendedInfo = txInfoString; + + string expensifyFileName = (string) txInfo["receiptFilename"]; + string actualReceiptUrl = "https://s3.amazonaws.com/receipts.expensify.com/" + expensifyFileName; + string newGuidString = Guid.NewGuid().ToString(); + + string fullyQualifiedFileName = Document.DailyStorageFolder + newGuidString; + string relativeFileName = relativePath + newGuidString; + + client.DownloadFile(actualReceiptUrl, fullyQualifiedFileName); + recordList[loop].ReceiptFileNameHere = newGuidString; + + // If original file name ends in PDF, initiate conversion. + + if (expensifyFileName.ToLowerInvariant().EndsWith(".pdf")) + { + // Convert low resolution + + Documents docs = new PdfProcessor().RasterizeOne(fullyQualifiedFileName, recordList[loop].Description, newGuidString, currentUser, organization); + + // Ask backend for high-res conversion + + RasterizeDocumentHiresOrder backendOrder = + new RasterizeDocumentHiresOrder(docs[0]); + backendOrder.Create(); + } + else + { + Document doc = Document.Create(relativePath + newGuidString, expensifyFileName, 0, newGuidString, null, + currentUser); + } + } + } + } + + + + + + // TODO: Get all receipts + + // TODO: Present report to user + + // TODO: Let user confirm budgets + + // TODO: Once user has confirmed budgets, save expenses } @@ -383,6 +473,9 @@ namespace Swarmops.Frontend.Pages.v5.Financial public Currency OriginalCurrency { get; set; } public Int64 OriginalAmountCents { get; set; } public string ReceiptUrl { get; set; } + public DateTime Timestamp { get; set; } + public string ExtendedInfo { get; set; } + public string ReceiptFileNameHere { get; set; } } diff --git a/Site/Scripts/ScriptLicenses.txt b/Site/Scripts/ScriptLicenses.txt index a3e6420c..f4675833 100644 --- a/Site/Scripts/ScriptLicenses.txt +++ b/Site/Scripts/ScriptLicenses.txt @@ -1,6 +1,6 @@ Some of these scripts are not in the public domain. -jQuery is licensed as MIT License (free to use for any purpose). So is FancyBox, Alertify, Superfish, HoverIntent, jQuery JSON, and jQuery SwitchButton. +jQuery is licensed as MIT License (free to use for any purpose). So is FancyBox, Alertify, Superfish, HoverIntent, jQuery JSON, BCHAddr, and jQuery SwitchButton. SmartWizard is licensed under Creative Commons Attribution-ShareAlike. diff --git a/Site/Site.csproj b/Site/Site.csproj index eba06eec..e757aeb2 100644 --- a/Site/Site.csproj +++ b/Site/Site.csproj @@ -1206,6 +1206,7 @@ +