From dee4f209093665f1b0e2380cb5fe6da3324d230f Mon Sep 17 00:00:00 2001 From: DanielJoo Date: Mon, 13 Nov 2023 13:03:27 -0800 Subject: [PATCH 1/3] added lastMailedDate. created mailFormService. Not tested yet --- src/main/Config/AppConfig.java | 1 + src/main/Form/Form.java | 7 ++ src/main/Form/FormController.java | 37 ++++++- src/main/Form/FormMessage.java | 4 +- src/main/Form/Services/MailFormService.java | 105 ++++++++++++++++++++ 5 files changed, 152 insertions(+), 2 deletions(-) create mode 100644 src/main/Form/Services/MailFormService.java diff --git a/src/main/Config/AppConfig.java b/src/main/Config/AppConfig.java index 9c80f26c..5a69735b 100644 --- a/src/main/Config/AppConfig.java +++ b/src/main/Config/AppConfig.java @@ -115,6 +115,7 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/upload-form", formController.formUpload); app.post("/get-form", formController.formGet); app.post("/delete-form/", formController.formDelete); + app.post("/mail-form", formController.formMail); /* -------------- USER AUTHENTICATION/USER RELATED ROUTES-------------- */ app.post("/login", userController.loginUser); diff --git a/src/main/Form/Form.java b/src/main/Form/Form.java index a2fbb6f4..bfa93b21 100644 --- a/src/main/Form/Form.java +++ b/src/main/Form/Form.java @@ -34,6 +34,9 @@ public class Form implements Comparable
{ @BsonProperty(value = "isTemplate") private boolean isTemplate; + @BsonProperty(value = "lastMailedAt") + private LocalDateTime lastMailedAt; + @BsonProperty(value = "conditionalFieldId") private ObjectId conditionalFieldId; @@ -111,6 +114,8 @@ public boolean isTemplate() { return isTemplate; } + public LocalDateTime getLastMailedAt() { return lastMailedAt; } + public FormMetadata getMetadata() { return metadata; } @@ -164,6 +169,8 @@ public void setBody(FormSection body) { this.body = body; } + public void setLastMailedAt(LocalDateTime lastMailedAt) {this.lastMailedAt = lastMailedAt;} + public void setConditionalFieldId(ObjectId fieldId) { this.conditionalFieldId = fieldId; } diff --git a/src/main/Form/FormController.java b/src/main/Form/FormController.java index 80859e69..c211caf9 100644 --- a/src/main/Form/FormController.java +++ b/src/main/Form/FormController.java @@ -5,6 +5,7 @@ import Form.Services.DeleteFormService; import Form.Services.GetFormService; import Form.Services.UploadFormService; +import Form.Services.MailFormService; import Security.EncryptionController; import User.User; import User.UserMessage; @@ -177,7 +178,41 @@ public FormController(MongoDatabase db, FormDao formDao) { ctx.result(response.toResponseString()); }; - public User userCheck(String req) { + public Handler formMail = + ctx -> { + String username; + UserType userType; + JSONObject req = new JSONObject(ctx.body()); + User check = userCheck(ctx.body()); + if (check == null && req.has("targetUser")) { + ctx.result(UserMessage.USER_NOT_FOUND.toJSON().toString()); + } else { + boolean orgFlag; + if (check != null && req.has("targetUser")) { + log.info("Target form found"); + username = check.getUsername(); + userType = check.getUserType(); + orgFlag = check.getOrganization().equals(ctx.sessionAttribute("orgName")); + } else { + username = ctx.sessionAttribute("username"); + userType = ctx.sessionAttribute("privilegeLevel"); + orgFlag = true; + } + + if (orgFlag) { + String formIDStr = req.getString("formId"); + ObjectId formId = new ObjectId(formIDStr); + + MailFormService mailFormService = + new MailFormService(formDao, formId, username, userType); + ctx.result(mailFormService.executeAndGetResponse().toResponseString()); + } else { + ctx.result(UserMessage.CROSS_ORG_ACTION_DENIED.toResponseString()); + } + } + }; + + public User userCheck(String req) { log.info("userCheck Helper started"); String username; User user = null; diff --git a/src/main/Form/FormMessage.java b/src/main/Form/FormMessage.java index 40b28afa..244231c5 100644 --- a/src/main/Form/FormMessage.java +++ b/src/main/Form/FormMessage.java @@ -12,7 +12,9 @@ public enum FormMessage implements Message { INSUFFICIENT_PRIVILEGE("INSUFFICIENT_PRIVILEGE:Privilege level too low."), SUCCESS("SUCCESS:Success."), NO_SUCH_FILE("NO_SUCH_FILE:Form does not exist"), - ENCRYPTION_ERROR("ENCRYPTION_ERROR:Error encrypting/decrypting"); + ALREADY_MAILED_RECENTLY("ALREADY_MAILED_RECENTLY:The form has been mailed recently and cannot be mailed again so soon."); + + //ENCRYPTION_ERROR("ENCRYPTION_ERROR:Error encrypting/decrypting"); private String errorMessage; diff --git a/src/main/Form/Services/MailFormService.java b/src/main/Form/Services/MailFormService.java new file mode 100644 index 00000000..40a0e494 --- /dev/null +++ b/src/main/Form/Services/MailFormService.java @@ -0,0 +1,105 @@ +package Form.Services; + +import Config.Message; +import Config.Service; +import Database.Form.FormDao; +import Form.Form; +import Form.FormMessage; +import User.UserType; +import java.time.LocalDateTime; +import java.util.Optional; +import kong.unirest.HttpResponse; +import kong.unirest.Unirest; +import org.json.JSONArray; +import org.json.JSONObject; +import Issue.IssueReportMessage; + +import org.bson.types.ObjectId; +import static Issue.IssueController.issueReportActualURL; + +public class MailFormService implements Service { + + private ObjectId formId; + private String username; + private UserType privilegeLevel; + private FormDao formDao; + + public MailFormService(FormDao formDao, ObjectId formId, String username, UserType privilegeLevel) { + this.formDao = formDao; + this.formId = formId; + this.username = username; + this.privilegeLevel = privilegeLevel; + } + + @Override + public Message executeAndGetResponse() { + if (formId == null) { + return FormMessage.INVALID_PARAMETER; + } else { + // Check for sufficient privileges + if (privilegeLevel == UserType.Admin || privilegeLevel == UserType.Director || privilegeLevel == UserType.Developer) { + try { + Optional maybeForm = formDao.get(formId); + if (maybeForm.isPresent()) { + Form form = maybeForm.get(); + if (shouldMail(form)) { + // Add logic to mail the form + Message slackResponse = sendSlackNotification("Form Mailing Request", "A form is requested to be mailed."); + + // Handle the Slack response + if (slackResponse != IssueReportMessage.SUCCESS) { + return slackResponse; + } + + form.setLastMailedAt(LocalDateTime.now()); + formDao.update(form); // Assuming FormDao has an update method + return FormMessage.SUCCESS; + } else { + return FormMessage.ALREADY_MAILED_RECENTLY; + } + } else { + return FormMessage.INVALID_FORM; + } + } catch (Exception e) { + return FormMessage.SERVER_ERROR; + } + } else { + return FormMessage.INSUFFICIENT_PRIVILEGE; + } + } + } + + //want to remove this for the future + private Message sendSlackNotification(String title, String description) { + JSONArray blocks = new JSONArray(); + JSONObject titleJson = new JSONObject(); + titleJson.put("type", "section"); + titleJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Title: * " + title)); + blocks.put(titleJson); + + JSONObject desJson = new JSONObject(); + desJson.put("type", "section"); + desJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Description: * " + description)); + blocks.put(desJson); + + JSONObject input = new JSONObject(); + input.put("blocks", blocks); + + HttpResponse posted = Unirest.post(issueReportActualURL) + .header("accept", "application/json") + .body(input.toString()) + .asEmpty(); + + if (!posted.isSuccess()) { + return IssueReportMessage.SLACK_FAILED; + } + return IssueReportMessage.SUCCESS; + } + + private boolean shouldMail(Form form) { + LocalDateTime lastMailedAt = form.getLastMailedAt(); + // Logic to decide if the form should be mailed again + // Example: mail if lastMailedAt is null or more than 1 day ago + return lastMailedAt == null || LocalDateTime.now().isAfter(lastMailedAt.plusDays(1)); + } +} From a1bbd8a0b55b249f6814cd5be74d38355cbb0be7 Mon Sep 17 00:00:00 2001 From: DanielJoo Date: Mon, 13 Nov 2023 18:19:42 -0800 Subject: [PATCH 2/3] migrated from form to file. FileDao does not work with old PDFController implementation. Consider finishing logic after migration or other workaround --- src/main/Config/AppConfig.java | 2 +- src/main/File/File.java | 2 + src/main/File/FileController.java | 21 ++++ src/main/File/FileMessage.java | 3 +- src/main/File/Services/MailFileService.java | 96 ++++++++++++++++++ src/main/Form/Form.java | 8 -- src/main/Form/FormController.java | 35 ------- src/main/Form/FormMessage.java | 4 +- src/main/Form/Services/MailFormService.java | 105 -------------------- 9 files changed, 123 insertions(+), 153 deletions(-) create mode 100644 src/main/File/Services/MailFileService.java delete mode 100644 src/main/Form/Services/MailFormService.java diff --git a/src/main/Config/AppConfig.java b/src/main/Config/AppConfig.java index 5a69735b..e8011715 100644 --- a/src/main/Config/AppConfig.java +++ b/src/main/Config/AppConfig.java @@ -103,6 +103,7 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/get-documents", pdfController.pdfGetFilesInformation); app.post("/get-application-questions", pdfController.getApplicationQuestions); app.post("/fill-application", pdfController.fillPDFForm); + app.post("/mail-file", fileController.fileMail); /* -------------- FILE MANAGEMENT v2 --------------------- */ app.post("/upload-file", fileController.fileUpload); @@ -115,7 +116,6 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/upload-form", formController.formUpload); app.post("/get-form", formController.formGet); app.post("/delete-form/", formController.formDelete); - app.post("/mail-form", formController.formMail); /* -------------- USER AUTHENTICATION/USER RELATED ROUTES-------------- */ app.post("/login", userController.loginUser); diff --git a/src/main/File/File.java b/src/main/File/File.java index bce7ad78..68845083 100644 --- a/src/main/File/File.java +++ b/src/main/File/File.java @@ -8,6 +8,7 @@ import org.bson.types.ObjectId; import java.io.InputStream; +import java.time.LocalDateTime; import java.util.Date; import java.util.Objects; @@ -21,6 +22,7 @@ public class File { @Getter @Setter private Date uploadedAt; @Getter @Setter private String username; @Getter @Setter private String organizationName; + @Getter @Setter private LocalDateTime lastMailedAt; @Getter @Setter diff --git a/src/main/File/FileController.java b/src/main/File/FileController.java index 1b17415f..17fc3c4e 100644 --- a/src/main/File/FileController.java +++ b/src/main/File/FileController.java @@ -1,6 +1,7 @@ package File; import static User.UserController.mergeJSON; +import static com.mongodb.client.model.Filters.eq; import Config.Message; import Database.File.FileDao; @@ -11,6 +12,7 @@ import User.User; import User.UserMessage; import User.UserType; +import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import io.javalin.http.Handler; import io.javalin.http.UploadedFile; @@ -23,6 +25,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; +import org.bson.types.ObjectId; import org.json.JSONException; import org.json.JSONObject; @@ -466,6 +469,24 @@ public FileController(MongoDatabase db, UserDao userDao, FileDao fileDao) { } }; + public Handler fileMail = + ctx -> { + String username; + UserType userType; + JSONObject req = new JSONObject(ctx.body()); + username = ctx.sessionAttribute("username"); + userType = ctx.sessionAttribute("privilegeLevel"); + //file ID is still not working. Not used + String fileIDStr = req.getString("fileId"); + ObjectId fileId = new ObjectId(fileIDStr); + Optional maybefile = fileDao.get(fileId); + String description = req.getString("description"); + + MailFileService mailFileService = + new MailFileService(fileDao, fileId, username, userType, description); + ctx.result(mailFileService.executeAndGetResponse().toResponseString()); + }; + public static String getPDFTitle(String fileName, PDDocument pdfDocument) { String title = fileName; pdfDocument.setAllSecurityToBeRemoved(true); diff --git a/src/main/File/FileMessage.java b/src/main/File/FileMessage.java index bde7acbd..9c9e99c7 100644 --- a/src/main/File/FileMessage.java +++ b/src/main/File/FileMessage.java @@ -13,7 +13,8 @@ public enum FileMessage implements Message { SUCCESS("SUCCESS:Success."), NO_SUCH_FILE("NO_SUCH_FILE:PDF does not exist"), ENCRYPTION_ERROR("ENCRYPTION_ERROR:Error encrypting/decrypting"), - FILE_EXISTS("ERROR: File already exists!"); + FILE_EXISTS("ERROR: File already exists!"), + ALREADY_MAILED_RECENTLY("ALREADY_MAILED_RECENTLY:The form has been mailed recently and cannot be mailed again so soon."); private String errorMessage; private String fileId; // optional diff --git a/src/main/File/Services/MailFileService.java b/src/main/File/Services/MailFileService.java new file mode 100644 index 00000000..44c31123 --- /dev/null +++ b/src/main/File/Services/MailFileService.java @@ -0,0 +1,96 @@ +package File.Services; + +import Config.Message; +import Config.Service; +import Database.File.FileDao; +import File.File; +import File.FileMessage; +import User.UserType; +import java.time.LocalDateTime; +import java.util.Optional; +import kong.unirest.HttpResponse; +import kong.unirest.Unirest; +import org.json.JSONArray; +import org.json.JSONObject; +import Issue.IssueReportMessage; + +import org.bson.types.ObjectId; +import static Issue.IssueController.issueReportActualURL; +import static io.javalin.Javalin.log; + +public class MailFileService implements Service { + + private ObjectId fileId; + private String username; + private UserType privilegeLevel; + private FileDao fileDao; + private String description; + + public MailFileService(FileDao fileDao, ObjectId fileId, String username, UserType privilegeLevel, String description) { + this.fileDao = fileDao; + this.fileId = fileId; + this.username = username; + this.privilegeLevel = privilegeLevel; + this.description = description; + } + + @Override + public Message executeAndGetResponse() { + //fileDao was not used for the ViewDocuments, so seeing completed applications is difficult. Add these checks when they work +// try { +// Optional maybefile = fileDao.get(fileId); +// if (maybefile.isPresent()) { +// File file = maybefile.get(); +// if (shouldMail(file)) { + Message slackResponse = sendSlackNotification("file Mailing Request", this.description); + if (slackResponse != IssueReportMessage.SUCCESS) { + return slackResponse; + } +// file.setLastMailedAt(LocalDateTime.now()); +// fileDao.update(file); // Assuming fileDao has an update method + return FileMessage.SUCCESS; +// } else { +// return FileMessage.ALREADY_MAILED_RECENTLY; +// } +// } else { +// return FileMessage.INVALID_FILE; +// } +// } catch (Exception e) { +// return FileMessage.SERVER_ERROR; +// } + } + + //want to remove this for the future + private Message sendSlackNotification(String title, String description) { + JSONArray blocks = new JSONArray(); + JSONObject titleJson = new JSONObject(); + titleJson.put("type", "section"); + titleJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Title: * " + title)); + blocks.put(titleJson); + + JSONObject desJson = new JSONObject(); + desJson.put("type", "section"); + desJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Description: * " + description)); + blocks.put(desJson); + + JSONObject input = new JSONObject(); + input.put("blocks", blocks); + + HttpResponse posted = Unirest.post(issueReportActualURL) + .header("accept", "application/json") + .body(input.toString()) + .asEmpty(); + + if (!posted.isSuccess()) { + return IssueReportMessage.SLACK_FAILED; + } + return IssueReportMessage.SUCCESS; + } + + private boolean shouldMail(File file) { + LocalDateTime lastMailedAt = file.getLastMailedAt(); + // Logic to decide if the file should be mailed again + // Example: mail if lastMailedAt is null or more than 1 day ago + return lastMailedAt == null || LocalDateTime.now().isAfter(lastMailedAt.plusDays(1)); + } +} diff --git a/src/main/Form/Form.java b/src/main/Form/Form.java index bfa93b21..c1ac0d2f 100644 --- a/src/main/Form/Form.java +++ b/src/main/Form/Form.java @@ -34,9 +34,6 @@ public class Form implements Comparable { @BsonProperty(value = "isTemplate") private boolean isTemplate; - @BsonProperty(value = "lastMailedAt") - private LocalDateTime lastMailedAt; - @BsonProperty(value = "conditionalFieldId") private ObjectId conditionalFieldId; @@ -113,9 +110,6 @@ public String getUploaderUsername() { public boolean isTemplate() { return isTemplate; } - - public LocalDateTime getLastMailedAt() { return lastMailedAt; } - public FormMetadata getMetadata() { return metadata; } @@ -169,8 +163,6 @@ public void setBody(FormSection body) { this.body = body; } - public void setLastMailedAt(LocalDateTime lastMailedAt) {this.lastMailedAt = lastMailedAt;} - public void setConditionalFieldId(ObjectId fieldId) { this.conditionalFieldId = fieldId; } diff --git a/src/main/Form/FormController.java b/src/main/Form/FormController.java index c211caf9..52697aa7 100644 --- a/src/main/Form/FormController.java +++ b/src/main/Form/FormController.java @@ -5,7 +5,6 @@ import Form.Services.DeleteFormService; import Form.Services.GetFormService; import Form.Services.UploadFormService; -import Form.Services.MailFormService; import Security.EncryptionController; import User.User; import User.UserMessage; @@ -178,40 +177,6 @@ public FormController(MongoDatabase db, FormDao formDao) { ctx.result(response.toResponseString()); }; - public Handler formMail = - ctx -> { - String username; - UserType userType; - JSONObject req = new JSONObject(ctx.body()); - User check = userCheck(ctx.body()); - if (check == null && req.has("targetUser")) { - ctx.result(UserMessage.USER_NOT_FOUND.toJSON().toString()); - } else { - boolean orgFlag; - if (check != null && req.has("targetUser")) { - log.info("Target form found"); - username = check.getUsername(); - userType = check.getUserType(); - orgFlag = check.getOrganization().equals(ctx.sessionAttribute("orgName")); - } else { - username = ctx.sessionAttribute("username"); - userType = ctx.sessionAttribute("privilegeLevel"); - orgFlag = true; - } - - if (orgFlag) { - String formIDStr = req.getString("formId"); - ObjectId formId = new ObjectId(formIDStr); - - MailFormService mailFormService = - new MailFormService(formDao, formId, username, userType); - ctx.result(mailFormService.executeAndGetResponse().toResponseString()); - } else { - ctx.result(UserMessage.CROSS_ORG_ACTION_DENIED.toResponseString()); - } - } - }; - public User userCheck(String req) { log.info("userCheck Helper started"); String username; diff --git a/src/main/Form/FormMessage.java b/src/main/Form/FormMessage.java index 244231c5..40b28afa 100644 --- a/src/main/Form/FormMessage.java +++ b/src/main/Form/FormMessage.java @@ -12,9 +12,7 @@ public enum FormMessage implements Message { INSUFFICIENT_PRIVILEGE("INSUFFICIENT_PRIVILEGE:Privilege level too low."), SUCCESS("SUCCESS:Success."), NO_SUCH_FILE("NO_SUCH_FILE:Form does not exist"), - ALREADY_MAILED_RECENTLY("ALREADY_MAILED_RECENTLY:The form has been mailed recently and cannot be mailed again so soon."); - - //ENCRYPTION_ERROR("ENCRYPTION_ERROR:Error encrypting/decrypting"); + ENCRYPTION_ERROR("ENCRYPTION_ERROR:Error encrypting/decrypting"); private String errorMessage; diff --git a/src/main/Form/Services/MailFormService.java b/src/main/Form/Services/MailFormService.java deleted file mode 100644 index 40a0e494..00000000 --- a/src/main/Form/Services/MailFormService.java +++ /dev/null @@ -1,105 +0,0 @@ -package Form.Services; - -import Config.Message; -import Config.Service; -import Database.Form.FormDao; -import Form.Form; -import Form.FormMessage; -import User.UserType; -import java.time.LocalDateTime; -import java.util.Optional; -import kong.unirest.HttpResponse; -import kong.unirest.Unirest; -import org.json.JSONArray; -import org.json.JSONObject; -import Issue.IssueReportMessage; - -import org.bson.types.ObjectId; -import static Issue.IssueController.issueReportActualURL; - -public class MailFormService implements Service { - - private ObjectId formId; - private String username; - private UserType privilegeLevel; - private FormDao formDao; - - public MailFormService(FormDao formDao, ObjectId formId, String username, UserType privilegeLevel) { - this.formDao = formDao; - this.formId = formId; - this.username = username; - this.privilegeLevel = privilegeLevel; - } - - @Override - public Message executeAndGetResponse() { - if (formId == null) { - return FormMessage.INVALID_PARAMETER; - } else { - // Check for sufficient privileges - if (privilegeLevel == UserType.Admin || privilegeLevel == UserType.Director || privilegeLevel == UserType.Developer) { - try { - Optional maybeForm = formDao.get(formId); - if (maybeForm.isPresent()) { - Form form = maybeForm.get(); - if (shouldMail(form)) { - // Add logic to mail the form - Message slackResponse = sendSlackNotification("Form Mailing Request", "A form is requested to be mailed."); - - // Handle the Slack response - if (slackResponse != IssueReportMessage.SUCCESS) { - return slackResponse; - } - - form.setLastMailedAt(LocalDateTime.now()); - formDao.update(form); // Assuming FormDao has an update method - return FormMessage.SUCCESS; - } else { - return FormMessage.ALREADY_MAILED_RECENTLY; - } - } else { - return FormMessage.INVALID_FORM; - } - } catch (Exception e) { - return FormMessage.SERVER_ERROR; - } - } else { - return FormMessage.INSUFFICIENT_PRIVILEGE; - } - } - } - - //want to remove this for the future - private Message sendSlackNotification(String title, String description) { - JSONArray blocks = new JSONArray(); - JSONObject titleJson = new JSONObject(); - titleJson.put("type", "section"); - titleJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Title: * " + title)); - blocks.put(titleJson); - - JSONObject desJson = new JSONObject(); - desJson.put("type", "section"); - desJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Description: * " + description)); - blocks.put(desJson); - - JSONObject input = new JSONObject(); - input.put("blocks", blocks); - - HttpResponse posted = Unirest.post(issueReportActualURL) - .header("accept", "application/json") - .body(input.toString()) - .asEmpty(); - - if (!posted.isSuccess()) { - return IssueReportMessage.SLACK_FAILED; - } - return IssueReportMessage.SUCCESS; - } - - private boolean shouldMail(Form form) { - LocalDateTime lastMailedAt = form.getLastMailedAt(); - // Logic to decide if the form should be mailed again - // Example: mail if lastMailedAt is null or more than 1 day ago - return lastMailedAt == null || LocalDateTime.now().isAfter(lastMailedAt.plusDays(1)); - } -} From 9e9593c65a191e990a87722fb5573ca141b38d4a Mon Sep 17 00:00:00 2001 From: DanielJoo Date: Sun, 21 Jan 2024 17:50:03 -0800 Subject: [PATCH 3/3] Added Mail file service and mail information service --- src/main/Config/AppConfig.java | 4 +- src/main/File/File.java | 2 +- src/main/File/FileController.java | 63 +++-- .../Services/GetMailInformationService.java | 46 ++++ src/main/File/Services/MailFileService.java | 220 ++++++++++++------ 5 files changed, 240 insertions(+), 95 deletions(-) create mode 100644 src/main/File/Services/GetMailInformationService.java diff --git a/src/main/Config/AppConfig.java b/src/main/Config/AppConfig.java index e8011715..a20256ab 100644 --- a/src/main/Config/AppConfig.java +++ b/src/main/Config/AppConfig.java @@ -34,10 +34,9 @@ import com.mongodb.client.MongoDatabase; import io.javalin.Javalin; import io.javalin.http.HttpResponseException; -import org.bson.types.ObjectId; - import java.util.HashMap; import java.util.Optional; +import org.bson.types.ObjectId; public class AppConfig { public static Long ASYNC_TIME_OUT = 10L; @@ -104,6 +103,7 @@ public static Javalin appFactory(DeploymentLevel deploymentLevel) { app.post("/get-application-questions", pdfController.getApplicationQuestions); app.post("/fill-application", pdfController.fillPDFForm); app.post("/mail-file", fileController.fileMail); + app.post("/get-mail-info", fileController.getMailInformation); /* -------------- FILE MANAGEMENT v2 --------------------- */ app.post("/upload-file", fileController.fileUpload); diff --git a/src/main/File/File.java b/src/main/File/File.java index 68845083..4bab274c 100644 --- a/src/main/File/File.java +++ b/src/main/File/File.java @@ -22,7 +22,7 @@ public class File { @Getter @Setter private Date uploadedAt; @Getter @Setter private String username; @Getter @Setter private String organizationName; - @Getter @Setter private LocalDateTime lastMailedAt; + @Getter @Setter private LocalDateTime lastMailedAt; // not used yet while mail form uses GridFS @Getter @Setter diff --git a/src/main/File/FileController.java b/src/main/File/FileController.java index 17fc3c4e..857c9f2e 100644 --- a/src/main/File/FileController.java +++ b/src/main/File/FileController.java @@ -1,7 +1,6 @@ package File; import static User.UserController.mergeJSON; -import static com.mongodb.client.model.Filters.eq; import Config.Message; import Database.File.FileDao; @@ -12,7 +11,6 @@ import User.User; import User.UserMessage; import User.UserType; -import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import io.javalin.http.Handler; import io.javalin.http.UploadedFile; @@ -35,9 +33,13 @@ public class FileController { private FileDao fileDao; private EncryptionController encryptionController; + // need to include while viewDocuments used PDF controller (for mailing) + private MongoDatabase db; + public FileController(MongoDatabase db, UserDao userDao, FileDao fileDao) { this.userDao = userDao; this.fileDao = fileDao; + this.db = db; try { this.encryptionController = new EncryptionController(db); } catch (Exception e) { @@ -469,23 +471,48 @@ public FileController(MongoDatabase db, UserDao userDao, FileDao fileDao) { } }; - public Handler fileMail = - ctx -> { - String username; - UserType userType; - JSONObject req = new JSONObject(ctx.body()); - username = ctx.sessionAttribute("username"); - userType = ctx.sessionAttribute("privilegeLevel"); - //file ID is still not working. Not used - String fileIDStr = req.getString("fileId"); - ObjectId fileId = new ObjectId(fileIDStr); - Optional maybefile = fileDao.get(fileId); - String description = req.getString("description"); + public Handler fileMail = + ctx -> { + String username = ctx.sessionAttribute("username"); + UserType userType = ctx.sessionAttribute("privilegeLevel"); + JSONObject req = new JSONObject(ctx.body()); + String fileIDStr = req.getString("fileId"); + String price = req.getString("price"); + String mailAddress = req.getString("mailAddress"); + String returnAddress = req.getString("returnAddress"); + ObjectId fileId = new ObjectId(fileIDStr); + String description = req.getString("description"); + + MailFileService mailFileService = + new MailFileService( + db, + fileId, + username, + userType, + description, + price, + mailAddress, + returnAddress, + encryptionController); - MailFileService mailFileService = - new MailFileService(fileDao, fileId, username, userType, description); - ctx.result(mailFileService.executeAndGetResponse().toResponseString()); - }; + Message response = mailFileService.executeAndGetResponse(); + ctx.result(response.toResponseString()); + }; + public Handler getMailInformation = + ctx -> { + log.error("hello"); + String username = ctx.sessionAttribute("username"); + String organization = ctx.sessionAttribute("organization"); + String applicationType = ctx.sessionAttribute("applicationType"); + + GetMailInformationService getMailInformationService = + new GetMailInformationService(username, organization, applicationType); + + Message response = getMailInformationService.executeAndGetResponse(); + if (response == FileMessage.SUCCESS) { + ctx.result(getMailInformationService.getMailInformation().toString()); + } + }; public static String getPDFTitle(String fileName, PDDocument pdfDocument) { String title = fileName; diff --git a/src/main/File/Services/GetMailInformationService.java b/src/main/File/Services/GetMailInformationService.java new file mode 100644 index 00000000..bf47a96f --- /dev/null +++ b/src/main/File/Services/GetMailInformationService.java @@ -0,0 +1,46 @@ +package File.Services; + +import static io.javalin.Javalin.log; + +import Config.Message; +import Config.Service; +import File.FileMessage; +import kong.unirest.json.JSONObject; + +public class GetMailInformationService implements Service { + private String username; + private String organization; + private String applicationType; + private String price; + private String mailAddress; + private String returnAddress; + + public GetMailInformationService(String applicationType, String username, String organization) { + this.applicationType = applicationType; + this.username = username; + this.organization = organization; + } + + @Override + public Message executeAndGetResponse() { + try { + this.mailAddress = "example street"; + this.returnAddress = "return street"; + this.price = "0.10"; + // Assuming Message is a type that can encapsulate a JSON response. + return FileMessage.SUCCESS; + } catch (Exception e) { + log.error("Error in executeAndGetResponse: " + e.getMessage(), e); + return FileMessage.SERVER_ERROR; + } + } + + public JSONObject getMailInformation() { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("price", "0.10"); + jsonResponse.put("mailAddress", "123 example street"); + jsonResponse.put("returnAddress", "456 return street"); + jsonResponse.put("status", "SUCCESS"); + return jsonResponse; + } +} diff --git a/src/main/File/Services/MailFileService.java b/src/main/File/Services/MailFileService.java index 44c31123..285b5fc0 100644 --- a/src/main/File/Services/MailFileService.java +++ b/src/main/File/Services/MailFileService.java @@ -1,96 +1,168 @@ package File.Services; +import static Issue.IssueController.issueReportActualURL; +import static io.javalin.Javalin.log; + import Config.Message; import Config.Service; -import Database.File.FileDao; -import File.File; import File.FileMessage; +import Issue.IssueReportMessage; +import Security.EncryptionController; import User.UserType; +import com.mongodb.MongoException; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.model.Updates; import java.time.LocalDateTime; -import java.util.Optional; import kong.unirest.HttpResponse; import kong.unirest.Unirest; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; import org.json.JSONArray; import org.json.JSONObject; -import Issue.IssueReportMessage; - -import org.bson.types.ObjectId; -import static Issue.IssueController.issueReportActualURL; -import static io.javalin.Javalin.log; public class MailFileService implements Service { - private ObjectId fileId; - private String username; - private UserType privilegeLevel; - private FileDao fileDao; - private String description; - - public MailFileService(FileDao fileDao, ObjectId fileId, String username, UserType privilegeLevel, String description) { - this.fileDao = fileDao; - this.fileId = fileId; - this.username = username; - this.privilegeLevel = privilegeLevel; - this.description = description; - } + private ObjectId fileId; + private String username; + private UserType privilegeLevel; + private MongoDatabase db; + private EncryptionController encryptionController; + private String description; + private String mailAddress; + private String returnAddress; + private String price; + private String applicationTitle; - @Override - public Message executeAndGetResponse() { - //fileDao was not used for the ViewDocuments, so seeing completed applications is difficult. Add these checks when they work -// try { -// Optional maybefile = fileDao.get(fileId); -// if (maybefile.isPresent()) { -// File file = maybefile.get(); -// if (shouldMail(file)) { - Message slackResponse = sendSlackNotification("file Mailing Request", this.description); - if (slackResponse != IssueReportMessage.SUCCESS) { - return slackResponse; - } -// file.setLastMailedAt(LocalDateTime.now()); -// fileDao.update(file); // Assuming fileDao has an update method - return FileMessage.SUCCESS; -// } else { -// return FileMessage.ALREADY_MAILED_RECENTLY; -// } -// } else { -// return FileMessage.INVALID_FILE; -// } -// } catch (Exception e) { -// return FileMessage.SERVER_ERROR; -// } + public MailFileService( + MongoDatabase db, + ObjectId fileId, + String username, + UserType privilegeLevel, + String description, + String price, + String mailAddress, + String returnAddress, + EncryptionController encryptionController) { + this.db = db; + this.fileId = fileId; + this.username = username; + this.privilegeLevel = privilegeLevel; + this.description = description; + this.applicationTitle = this.findApplicationTitle(fileId); + this.mailAddress = mailAddress; + this.returnAddress = returnAddress; + this.price = price; + this.encryptionController = encryptionController; + } + + @Override + public Message executeAndGetResponse() { + try { + MongoCollection mailCollection = db.getCollection("mail"); + + // if (shouldMail(mailCollection, fileId)) { + if (true) { + Message slackResponse = sendSlackNotification("File Mailing Request", this.description); + if (slackResponse != IssueReportMessage.SUCCESS) { + return slackResponse; + } + + updateLastMailedTime(mailCollection, fileId); + return FileMessage.SUCCESS; + } else { + return FileMessage.ALREADY_MAILED_RECENTLY; + } + } catch (Exception e) { + log.error("Error in executeAndGetResponse: " + e.getMessage(), e); + return FileMessage.SERVER_ERROR; } + } + + private String findApplicationTitle(ObjectId fileId) { + try { + MongoCollection completedApplicationsCollection = + db.getCollection("COMPLETED_APPLICATION.files"); - //want to remove this for the future - private Message sendSlackNotification(String title, String description) { - JSONArray blocks = new JSONArray(); - JSONObject titleJson = new JSONObject(); - titleJson.put("type", "section"); - titleJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Title: * " + title)); - blocks.put(titleJson); - - JSONObject desJson = new JSONObject(); - desJson.put("type", "section"); - desJson.put("text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Description: * " + description)); - blocks.put(desJson); - - JSONObject input = new JSONObject(); - input.put("blocks", blocks); - - HttpResponse posted = Unirest.post(issueReportActualURL) - .header("accept", "application/json") - .body(input.toString()) - .asEmpty(); - - if (!posted.isSuccess()) { - return IssueReportMessage.SLACK_FAILED; + // Find the document in the collection with the matching fileId + Document applicationDocument = + completedApplicationsCollection.find(Filters.eq("_id", fileId)).first(); + log.error(String.valueOf(applicationDocument)); + + if (applicationDocument != null) { + // Extract the applicationTitle field from the document + String applicationTitle = applicationDocument.getString("filename"); + if (applicationTitle != null) { + return applicationTitle; } - return IssueReportMessage.SUCCESS; + } + } catch (MongoException e) { + log.error("MongoDB error in findApplicationTitle: " + e.getMessage(), e); + } catch (Exception e) { + log.error("Error in findApplicationTitle: " + e.getMessage(), e); } - private boolean shouldMail(File file) { - LocalDateTime lastMailedAt = file.getLastMailedAt(); - // Logic to decide if the file should be mailed again - // Example: mail if lastMailedAt is null or more than 1 day ago - return lastMailedAt == null || LocalDateTime.now().isAfter(lastMailedAt.plusDays(1)); + // Return a default value or handle the case when the title is not found + return "No Title found"; + } + + private void updateLastMailedTime(MongoCollection mailCollection, ObjectId fileId) { + Bson filter = Filters.eq("fileId", fileId); + Bson updateOperation = + Updates.combine( + Updates.set("lastMailedAt", LocalDateTime.now().toString()), + Updates.set("applicationTitle", applicationTitle), + Updates.set("price", price), + Updates.set("mailAddress", mailAddress), + Updates.set("returnAddress", returnAddress)); + mailCollection.updateOne(filter, updateOperation, new UpdateOptions().upsert(true)); + } + + // want to remove this for the future + private Message sendSlackNotification(String title, String description) { + JSONArray blocks = new JSONArray(); + JSONObject titleJson = new JSONObject(); + titleJson.put("type", "section"); + titleJson.put( + "text", new JSONObject().put("type", "mrkdwn").put("text", "*Issue Title: * " + title)); + blocks.put(titleJson); + + JSONObject desJson = new JSONObject(); + desJson.put("type", "section"); + desJson.put( + "text", + new JSONObject().put("type", "mrkdwn").put("text", "*Issue Description: * " + description)); + blocks.put(desJson); + + JSONObject input = new JSONObject(); + input.put("blocks", blocks); + + HttpResponse posted = + Unirest.post(issueReportActualURL) + .header("accept", "application/json") + .body(input.toString()) + .asEmpty(); + + if (!posted.isSuccess()) { + return IssueReportMessage.SLACK_FAILED; + } + return IssueReportMessage.SUCCESS; + } + + private boolean shouldMail(MongoCollection mailCollection, ObjectId fileId) { + Document mailData = mailCollection.find(Filters.eq("fileId", fileId)).first(); + + if (mailData == null) { + // If no record exists, it means it hasn't been mailed before + return true; } + + String lastMailedAtStr = mailData.getString("lastMailedAt"); + LocalDateTime lastMailedAt = + lastMailedAtStr != null ? LocalDateTime.parse(lastMailedAtStr) : null; + return lastMailedAt == null || LocalDateTime.now().isAfter(lastMailedAt.plusDays(1)); + } }