diff --git a/src/main/java/com/health/HealthNutrition.java b/src/main/java/com/health/HealthNutrition.java index 32383c52..21234a26 100644 --- a/src/main/java/com/health/HealthNutrition.java +++ b/src/main/java/com/health/HealthNutrition.java @@ -59,6 +59,7 @@ public void run(String... args) throws Exception { try { taskProcessingService.createOutlineFile(); + taskProcessingService.addTokenInTrainingResource(); taskProcessingService.addAllBrochureToQueue(); taskProcessingService.addAllResearchPapertoQueue(); taskProcessingService.addAllTuttorialsToQueue(); diff --git a/src/main/java/com/health/config/SecurityConfig.java b/src/main/java/com/health/config/SecurityConfig.java index 89a57846..7322c8d4 100644 --- a/src/main/java/com/health/config/SecurityConfig.java +++ b/src/main/java/com/health/config/SecurityConfig.java @@ -46,20 +46,21 @@ public static BCryptPasswordEncoder passwordEncoder() { "/tutorial_view/**", "/getConsultantDetails/**", "/reset/**", "/resetPassword/**", "/getCatAndLan/**", "/getTopicOnCatAndLan/**", "/getRolesOnCatLanUser/**", "/getTutorial/**", "/statistics", "/statistics/**", "/tutCountOnCat/**", "/tutCountOnLan/**", "/cdContentInfo/**", "/getContributorByTutLanUser/**", - "/showConsultant/**", "/showLanguages/**", "/unpublishTutorial/**", "/loadTopicByCategory/**", - "/loadLanguageByCategoryTopic/**", "/loadTopicAndLanguageByCategory/**", - "/loadCategoryAndLanguageByTopic/**", "/loadCategoryAndTopicByLanguage/**", "/tutorialsSearch/**", - "/tutorialsSearch1/**", "/checkTutorial/**", "/Slide/**", "/TimeScript/**", "/OriginalScript/**", - "/Brochure-English/**", "/Brochure/**", "/ResearchPaper/**", "/downloads", - "/loadLanguageByCategoryResource", "/autosuggest/**", "/loadLanguageAndTopicByCategoryResource", - "/loadTutorialCountByTopicAndLanguage", "/loadTutorialCountByTopics", "/downloadResources", "/citations", - "/api/scriptPublished/**", "/loadLanguageByPackage/**", "/promoVideoView/**", "/trainingModules/**", - "/downloadTrainingModules", "/loadMessageByPackageAndLan/**", "/loadLanguageByWeek/**", - "/loadWeekByLanguage/**", "/trainingTutorials/**", "/hstTrainingModuleView/**", "/downloadManager/**", - "/downloadManagerforhst/**", "/downloadHealthTutorials/**", "/Training-Resource/**", - "/Training-Resources/**", "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", - "/loadTopicAndLanByFileType/**", "/downloadTrainingResource/**", "/shared-Training-Resource/**", - "/shared-training-resource-file/**", "/check-deployment" }; + + "/showConsultant/**", "/showLanguages/**", "/loadTopicByCategory/**", "/loadLanguageByCategoryTopic/**", + "/loadTopicAndLanguageByCategory/**", "/loadCategoryAndLanguageByTopic/**", + "/loadCategoryAndTopicByLanguage/**", "/tutorialsSearch/**", "/tutorialsSearch1/**", "/checkTutorial/**", + "/Slide/**", "/TimeScript/**", "/OriginalScript/**", "/Brochure-English/**", "/Brochure/**", + "/ResearchPaper/**", "/downloads", "/loadLanguageByCategoryResource", "/autosuggest/**", + "/loadLanguageAndTopicByCategoryResource", "/loadTutorialCountByTopicAndLanguage", + "/loadTutorialCountByTopics", "/downloadResources", "/citations", "/api/scriptPublished/**", + "/loadLanguageByPackage/**", "/promoVideoView/**", "/trainingModules/**", "/downloadTrainingModules", + "/loadMessageByPackageAndLan/**", "/loadLanguageByWeek/**", "/loadWeekByLanguage/**", + "/trainingTutorials/**", "/hstTrainingModuleView/**", "/downloadManager/**", "/downloadManagerforhst/**", + "/downloadHealthTutorials/**", "/Training-Resource/**", "/Training-Resources/**", + "/loadLanAndFileTypeByTopic/**", "/loadTopicAndFileTypeByLan/**", "/loadTopicAndLanByFileType/**", + "/downloadTrainingResource/**", "/shared-Training-Resource/**", "/shared-training-resource-file/**", + "/check-deployment", "/training-resources/view-share/**" }; /** * url matcher for SUPERADMIN @@ -67,14 +68,10 @@ public static BCryptPasswordEncoder passwordEncoder() { public static final String[] SUPERUSER_URL = { "/addCategory/**", "/updateCategory/**", "/category/edit/**", "/addOrganizationRole/**", "/organization_role/edit/**", "/update_organization_role/**", "/addLanguage/**", "/language/edit/**", "/updateLanguage/**", "/addRole/**", "/addTopic/**", "/topic/edit/**", - "/updateTopic/**", "/uploadQuestion/**", "/question/edit/**", "/updateQuestion/**", "/addBrochure/**", - "/addCarousel/**", "/approveRole/**", "/assignTutorialToContributor/**", "/assignContributor/edit/**", - "/enableRoleById/**", "/deleteMasterRole/**", "/viewTrainee/**", "/details/**", "/tutorialStatus/**", - "/users/**", "/unpublishTopic/**", "/clearAllCaches/**", "/addConsultant/**", - "/enableDisableCourseCatTopic", "/delete-category-topic-from-course", "/createCourse", - "/courseName/edit/**", "/updateCourseName", - -// "/unpublishTutorial/**" + "/updateTopic/**", "/uploadQuestion/**", "/question/edit/**", "/updateQuestion/**", "/approveRole/**", + "/assignTutorialToContributor/**", "/assignContributor/edit/**", "/enableRoleById/**", + "/deleteMasterRole/**", "/viewTrainee/**", "/details/**", "/tutorialStatus/**", "/users/**", + "/unpublishTopic/**", "/clearAllCaches/**", }; @@ -95,13 +92,6 @@ public static BCryptPasswordEncoder passwordEncoder() { public static final String[] CONTRIBUTOR_URL = { "/uploadTutorial/**", "/addOutline/**", "/addKeyword**", "/addPreRequisticWhenNotRequired/**", "/addPreRequistic/**", "/addVideo/**", "/addSlide/**", "/addScript/**", "/listTutorialForContributorReview/**", "/Contributor/review/**", "/uploadTimescript/**", - "/addLiveTutorial", "/updateLiveTutorial", "/addSpokenVideo", "/spokenVideo/edit/**", "/addVideoResource", - "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", - - "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/enableDisableCourseCatTopic", - "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", "/updateCourseName", - "/addTrainingResource", "/trainingReource/view/**", "/trainingReourceAdminView/**", - "/trainingReource/edit/**", "/enableDisableTrainingResource", "/delete-trainingResource", }; @@ -160,13 +150,25 @@ protected void configure(HttpSecurity http) throws Exception { .antMatchers("/addBrochure/**", "/addCarousel/**", "/addConsultant/**", "/addEvent/**", "/addTestimonial/**", "/addPromoVideo/**", "/addResearchPaper/**", "/brochure/edit/**", "/promoVideo/edit/**", "/carousel/edit/**", "/event/edit/**", "/testimonial/edit/**", - "/createPackage", "/packageName/edit/**", "/updatePackageName", "/weekTitleVideo/editTitle/**", + "/createPackage/**", "/packageName/edit/**", "/updatePackageName/**", + "/weekTitleVideo/editTitle/**", - "/updateTitle", "/weekTitleVideo/editWeek/**", "/updateWeek", "/researchPaper/edit/**", + "/updateTitle/**", "/weekTitleVideo/editWeek/**", "/updateWeek/**", "/researchPaper/edit/**", "/enableDisableBrouchure/**", "/enableDisableConsultant/**", "/enableDisableTestimonial/**", - "/addCitation/**", "/citation/edit/**", "/enableDisableCourseCatTopic", - "/delete-category-topic-from-course", "/createCourse", "/courseName/edit/**", - "/updateCourseName", "/addTrainingResource") + "/addCitation/**", "/citation/edit/**", "/enableDisableCourseCatTopic/**", + "/delete-category-topic-from-course/**", "/createCourse/**", "/courseName/edit/**", + "/enableDisablePromoVideo/**", "/enableDisablePacakgeLanguage/**", + "/enableDisableResearchPaper/**", "/enableDisableEvent/**", "/enableDisableCarousel/**", + "/updateCourseName/**", "/addTrainingResource/**", "/updateCitation/**", "/updateConsultant/**", + "/updateSpokenVideo/**", "/updateTrainingResource/**", "/updateEvent/**", + "/updatePromoVideo/**", "/updateBrochure/**", "/updateResearchPaper/**", "/updateCarousel/**", + "/updateTestimonial/**", "/addLiveTutorial/**", "/updateLiveTutorial/**", "/addSpokenVideo/**", + "/spokenVideo/edit/**", "/addVideoResource/**", "/trainingReource/view/**", + "/trainingReourceAdminView/**", "/trainingReource/edit/**", "/enableDisableTrainingResource/**", + "/delete-trainingResource/**", "/addProjectReport/**", "/projectReportAdminView/**", + "/projectReport/edit/**", "/enableDisableProjectReport/**", "/delete-projectReport/**" + + ) .hasAnyAuthority("SUPER_USER", "CONTRIBUTOR").antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest() .authenticated().and().exceptionHandling().accessDeniedPage("/access-denied"); diff --git a/src/main/java/com/health/controller/AjaxController.java b/src/main/java/com/health/controller/AjaxController.java index 06647767..6ea4db11 100644 --- a/src/main/java/com/health/controller/AjaxController.java +++ b/src/main/java/com/health/controller/AjaxController.java @@ -32,6 +32,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.core.env.Environment; +import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; @@ -42,6 +43,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -72,6 +74,7 @@ import com.health.model.PackageContainer; import com.health.model.PackageLanguage; import com.health.model.PathofPromoVideo; +import com.health.model.ProjectReport; import com.health.model.PromoVideo; import com.health.model.ResearchPaper; import com.health.model.State; @@ -110,6 +113,7 @@ import com.health.service.PackageContainerService; import com.health.service.PackageLanguageService; import com.health.service.PathofPromoVideoService; +import com.health.service.ProjectReportService; import com.health.service.PromoVideoService; import com.health.service.ResearchPaperService; import com.health.service.RoleService; @@ -293,6 +297,9 @@ public class AjaxController { @Autowired private EventService eventService; + @Autowired + private ProjectReportService projectReportService; + @Value("${downloadLimit}") private int downloadLimit; @@ -2133,11 +2140,80 @@ public ResponseEntity deleteTrainingResource(@RequestParam("trainingReso } + /* + * @GetMapping("/downloadTrainingResource") public ResponseEntity + * downloadTrainingResourcePost(@RequestParam(name = "filePath") String + * filePath) { + * + * try { + * + * String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + * + * Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), + * finalUrl); + * + * if (!Files.exists(path)) { return + * ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); } + * + * Resource resource = new UrlResource(path.toUri()); + * + * String contentType = Files.probeContentType(path); if (contentType == null) { + * contentType = "application/octet-stream"; } + * + * String originalFilename = path.getFileName().toString(); + * + * String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + * + * String encodedFilename = URLEncoder.encode(safeFilename, + * "UTF-8").replace("+", "%20"); + * + * return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + * .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + + * encodedFilename) .body(resource); + * + * } catch (Exception e) { logger.error("Error in download", e); return + * ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } + */ + @GetMapping("/downloadTrainingResource") - public ResponseEntity downloadTrainingResourcePost(@RequestParam(name = "filePath") String filePath) { + public ResponseEntity downloadTrainingResource(@RequestParam(name = "fileType") String fileTypeString, + @RequestParam(name = "token") String token) { try { + int fileType = ServiceUtility.getFileTypeIdByValue(fileTypeString); + TrainingResource tr = null; + + if (fileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (fileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (fileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + + String filePath = null; + + if (fileType == CommonData.DOC) { + filePath = tr.getDocPath(); + } else if (fileType == CommonData.EXCEL) { + filePath = tr.getExcelPath(); + } else if (fileType == CommonData.PDF) { + filePath = tr.getPdfPath(); + } else if (fileType == CommonData.IMAGE) { + filePath = tr.getImgPath(); + } + + if (filePath == null || filePath.trim().isEmpty()) { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).build(); + } + String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalUrl); @@ -2164,7 +2240,80 @@ public ResponseEntity downloadTrainingResourcePost(@RequestParam(name .body(resource); } catch (Exception e) { - logger.error("Error in download", e); + logger.error("Error while downloading training resource", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); + } + } + + @GetMapping("/training-resources/view-share/{topic}/{lang}/{fileType}/{token}/{page}/{fileName}") + public ResponseEntity viewOrSharePdfOrImage(@PathVariable String topic, @PathVariable String lang, + @PathVariable String fileType, @PathVariable String token, @PathVariable int page, + @PathVariable String fileName) { + + try { + + int fileTypeId = ServiceUtility.getFileTypeIdByValue(fileType); + + TrainingResource tr = null; + if (fileTypeId == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (fileTypeId == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } + + if (tr == null) { + return ResponseEntity.notFound().build(); + } + + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, fileTypeId); + + List filePaths = new ArrayList<>(); + if (filePath.toLowerCase().endsWith(".zip")) { + List extracted = ServiceUtility.extractZipIfNeeded(filePath, env); + List sorted = ServiceUtility.sortFilePathsNumericOtherwiseLexical(extracted); + + if (fileType.equalsIgnoreCase("Pdf")) { + for (String str : sorted) { + if (!str.endsWith(".png")) { + filePaths.add(str); + } + } + } else { + filePaths.addAll(sorted); + } + + } else { + filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); + } + + if (page < 0 || page >= filePaths.size()) { + return ResponseEntity.badRequest().build(); + } + + String finalFilePath = filePaths.get(page); + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), finalFilePath); + + if (!Files.exists(path)) { + return ResponseEntity.notFound().build(); + } + + String contentType = Files.probeContentType(path); + if (contentType == null) { + contentType = "application/octet-stream"; + } + + String originalFilename = path.getFileName().toString(); + String safeFilename = originalFilename.replaceAll("[\\\\/:*?\"<>|]", "_"); + String encodedFilename = URLEncoder.encode(safeFilename, "UTF-8").replace("+", "%20"); + + InputStreamResource resource = new InputStreamResource(Files.newInputStream(path)); + + return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename*=UTF-8''" + encodedFilename) + .body(resource); + + } catch (Exception e) { + logger.error("Error viewing shared file", e); return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build(); } } @@ -2192,6 +2341,111 @@ public ResponseEntity downloadTrainingResourcePost(@RequestParam(name * Training Resource End *************************************************************/ + /********************************** + * Projet Report Start + *************************/ + + @RequestMapping("/loadDistrictByStateforPR") + public @ResponseBody TreeMap loadDistrictByStateforPR(@RequestParam(value = "stateId") int stateId, + @RequestParam(value = "allDisId") int allDisId) { + TreeMap districtMaps = new TreeMap<>(); + + if (allDisId != 0) { + District allDistrict = disService.findById(allDisId); + if (allDistrict != null) + districtMaps.put(allDistrict.getDistrictName(), allDistrict.getId()); + + } + + State state = stateService.findById(stateId); + if (state != null) { + List disList = disService.findAllByState(state); + for (District temp : disList) { + + districtMaps.put(temp.getDistrictName(), temp.getId()); + + } + + } + + return districtMaps; + } + + @GetMapping("/enableDisableProjectReport") + public @ResponseBody boolean enableDisableProjectReport(int projectReportId) { + ProjectReport pr = projectReportService.findByProjectReportId(projectReportId); + + try { + if (pr.isStatus()) { + pr.setStatus(false); + projectReportService.save(pr); + return true; + + } else { + pr.setStatus(true); + projectReportService.save(pr); + return true; + + } + + } catch (Exception e) { + + logger.error("Error in Enable Disbale Project Report: {}", pr, e); + return false; + } + + } + + @RequestMapping("/delete-projectReport") + public ResponseEntity deleteProjectReport(@RequestParam("projectReportId") int projectReportId, + @RequestParam("fileType") String fileType) { + + try { + ProjectReport pr = projectReportService.findByProjectReportId(projectReportId); + String filePath = ""; + if (pr != null) { + switch (fileType.toLowerCase()) { + case "image": + filePath = pr.getImgPath(); + pr.setImgPath(""); + break; + case "pdf": + filePath = pr.getPdfPath(); + pr.setPdfPath(""); + break; + case "doc": + filePath = pr.getDocPath(); + pr.setDocPath(""); + break; + case "excel": + filePath = pr.getExcelPath(); + pr.setExcelPath(""); + break; + default: + return ResponseEntity.badRequest().body("Unsupported file type: " + fileType); + } + + if (!filePath.isEmpty() && filePath.endsWith(".zip")) { + String extractDir = filePath.replace(".zip", ""); + + Path extractDirPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), extractDir); + FileUtils.deleteDirectory(extractDirPath.toFile()); + } + + projectReportService.save(pr); + return ResponseEntity.ok("Deleted successfully"); + } else { + return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).body("Project Report not found"); + } + + } catch (Exception e) { + logger.error("Error in deleting project report", e); + return ResponseEntity.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).body("Error in deleting!"); + } + } + + /********************************** Projet Report End *************************/ + @RequestMapping("/loadTopicByCategoryInAssignContri") public @ResponseBody HashMap getTopicByCategoryAssignContri(@RequestParam(value = "id") int id) { diff --git a/src/main/java/com/health/controller/HomeController.java b/src/main/java/com/health/controller/HomeController.java index 3ee7205a..d4863f0b 100644 --- a/src/main/java/com/health/controller/HomeController.java +++ b/src/main/java/com/health/controller/HomeController.java @@ -29,6 +29,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; +import java.util.stream.IntStream; import javax.servlet.http.HttpServletRequest; @@ -96,6 +97,7 @@ import com.health.model.ContributorAssignedTutorial; import com.health.model.Course; import com.health.model.CourseCatTopicMapping; +import com.health.model.District; import com.health.model.DocumentSearch; import com.health.model.Event; import com.health.model.FeedbackMasterTrainer; @@ -110,11 +112,13 @@ import com.health.model.PackageLanguage; import com.health.model.PathofPromoVideo; import com.health.model.PostQuestionaire; +import com.health.model.ProjectReport; import com.health.model.PromoVideo; import com.health.model.Question; import com.health.model.ResearchPaper; import com.health.model.SpokenVideo; import com.health.model.State; +import com.health.model.StateDistrictMapping; import com.health.model.Testimonial; import com.health.model.Topic; import com.health.model.TopicCategoryMapping; @@ -157,11 +161,13 @@ import com.health.service.PackageLanguageService; import com.health.service.PathofPromoVideoService; import com.health.service.PostQuestionaireService; +import com.health.service.ProjectReportService; import com.health.service.PromoVideoService; import com.health.service.QuestionService; import com.health.service.ResearchPaperService; import com.health.service.RoleService; import com.health.service.SpokenVideoService; +import com.health.service.StateDistrictMappingService; import com.health.service.StateService; import com.health.service.TestimonialService; import com.health.service.TopicCategoryMappingService; @@ -264,6 +270,12 @@ public class HomeController { @Autowired private LanguageService lanService; + @Autowired + private ProjectReportService projectReportService; + + @Autowired + private StateDistrictMappingService stateDistrictMappingService; + @Autowired private CategoryService catService; @@ -5365,6 +5377,22 @@ private List getEnglishTrainingMouduleFirst(List * Assign Tutorial on Week And Package End ********************/ + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + @GetMapping("/addTrainingResource") public String addTrainingResourceGet(HttpServletRequest req, Principal principal, Model model) { User usr = getUser(principal); @@ -5480,10 +5508,11 @@ public String addTrainingResourcePost(HttpServletRequest req, Model model, Princ Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trId), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String token = generateUniqueTokenForTrainingResource(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); Set extentions = new HashSet<>(); String document = ""; @@ -5509,6 +5538,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { @@ -5521,6 +5551,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { @@ -5533,6 +5564,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { @@ -5545,6 +5577,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { @@ -5562,6 +5595,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); tr.setPdfPath(document); + tr.setPdfToken(token); } else if (ext.equals(CommonData.DOC_EXTENSION)) { @@ -5574,6 +5608,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, docFolder); tr.setDocPath(document); + tr.setDocToken(token); } else if (ext.equals(CommonData.EXCEL_EXTENSION)) { @@ -5586,6 +5621,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, excelFolder); tr.setExcelPath(document); + tr.setExcelToken(token); } else if (ext.equals(CommonData.IMAGE_EXTENSION)) { @@ -5598,6 +5634,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION)) { } document = ServiceUtility.uploadMediaFile(file, env, imageFolder); tr.setImgPath(document); + tr.setImgToken(token); } else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { @@ -5900,11 +5937,13 @@ public String updateTrainingResourcePost(HttpServletRequest req, Model model, Pr } boolean fileMatch = false; + String token = ""; if (fileType.equals("Doc")) { originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getDocPath(); + token = oldTrainingResource.getDocToken(); } } @@ -5912,6 +5951,7 @@ else if (fileType.equals("Pdf")) { originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getPdfPath(); + token = oldTrainingResource.getPdfToken(); } } @@ -5919,12 +5959,14 @@ else if (fileType.equals("Image")) { originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getImgPath(); + token = oldTrainingResource.getImgToken(); } } else if (fileType.equals("Excel")) { originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; if (oldTrainingResource != null) { oldPath = oldTrainingResource.getExcelPath(); + token = oldTrainingResource.getExcelToken(); } } @@ -5966,16 +6008,16 @@ else if (fileType.equals("Image")) { } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); // To get exact Id of new trainining Resource Data if (newTrainingData) { - + newTrainingResource.setDateAdded(dateAdded); trainingResourceService.save(newTrainingResource); trIdInt = newTrainingResource.getTrainingResourceId(); + token = generateUniqueTokenForTrainingResource(); } @@ -5985,10 +6027,10 @@ else if (fileType.equals("Image")) { Path rootPath = Paths.get(CommonData.uploadTrainingResource, String.valueOf(trIdInt), langName); - String pdfFolder = Paths.get(rootPath.toString(), "pdf").toString(); - String docFolder = Paths.get(rootPath.toString(), "docx_or_odt").toString(); - String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv").toString(); - String imageFolder = Paths.get(rootPath.toString(), "image").toString(); + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); boolean fileFlag = false; if (!file.isEmpty()) { @@ -6009,6 +6051,7 @@ else if (fileExtention.equals(CommonData.PDF_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) oldTrainingResource.setPdfPath(""); fileMatch = true; @@ -6018,6 +6061,7 @@ else if (fileExtention.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) oldTrainingResource.setDocPath(""); fileMatch = true; @@ -6027,6 +6071,7 @@ else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) oldTrainingResource.setExcelPath(""); fileMatch = true; @@ -6036,6 +6081,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) oldTrainingResource.setImgPath(""); fileMatch = true; @@ -6050,6 +6096,7 @@ else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); if (newTrainingData) { oldTrainingResource.setPdfPath(""); } @@ -6062,6 +6109,7 @@ else if (ext.equals(CommonData.DOC_EXTENSION) && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { document = ServiceUtility.uploadMediaFile(file, env, docFolder); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); if (newTrainingData) { oldTrainingResource.setDocPath(""); } @@ -6073,6 +6121,7 @@ else if (ext.equals(CommonData.EXCEL_EXTENSION) && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { document = ServiceUtility.uploadMediaFile(file, env, excelFolder); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); if (newTrainingData) { oldTrainingResource.setExcelPath(""); } @@ -6084,6 +6133,7 @@ else if (ext.equals(CommonData.IMAGE_EXTENSION) && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { document = ServiceUtility.uploadMediaFile(file, env, imageFolder); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); if (newTrainingData) { oldTrainingResource.setImgPath(""); } @@ -6118,14 +6168,18 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { FileUtils.deleteDirectory(extractDirPath.toFile()); } + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } - newTrainingResource.setDateAdded(dateAdded); newTrainingResource.setTopicLanMapping(topicLan); newTrainingResource.setUser(usr); newTrainingResource.setCategory(cat); if (fileMatch) { - newTrainingResource.setDateAdded(dateAdded); + if (newTrainingData) { + newTrainingResource.setDateAdded(dateAdded); + } newTrainingResource.setTopicLanMapping(topicLan); trainingResourceService.save(newTrainingResource); if (newTrainingData) { @@ -6155,6 +6209,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); newTrainingResource.setDocPath(document); + newTrainingResource.setDocToken(token); oldTrainingResource.setDocPath(""); } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { @@ -6163,6 +6218,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { env); newTrainingResource.setExcelPath(document); + newTrainingResource.setExcelToken(token); oldTrainingResource.setExcelPath(""); } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { @@ -6170,6 +6226,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); newTrainingResource.setPdfPath(document); + newTrainingResource.setPdfToken(token); oldTrainingResource.setPdfPath(""); } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { @@ -6177,6 +6234,7 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, env); newTrainingResource.setImgPath(document); + newTrainingResource.setImgToken(token); oldTrainingResource.setImgPath(""); } @@ -6204,13 +6262,23 @@ else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { return trainingResourceEditGet(originalFileType, oldtrId, req, model, principal); } - private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, int trId, + private String sharedTrainingResourceTemplate(String topicName, String fileType, String langName, String token, Principal principal, Model model) { int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); logger.info("FileType:{}", fileType); logger.info("intFileType:{}", intFileType); - TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + + TrainingResource tr = null; + if (intFileType == CommonData.DOC) { + tr = trainingResourceService.findByDocToken(token); + } else if (intFileType == CommonData.EXCEL) { + tr = trainingResourceService.findByExcelToken(token); + } else if (intFileType == CommonData.PDF) { + tr = trainingResourceService.findByPdfToken(token); + } else if (intFileType == CommonData.IMAGE) { + tr = trainingResourceService.findByImgToken(token); + } boolean isZipFile = false; String filePath = ""; @@ -6229,6 +6297,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("topicName", topic_name); model.addAttribute("langName", lang_name); model.addAttribute("fileTypeString", fileType); + model.addAttribute("token", token); Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), filePath); String fileName = path.getFileName().toString(); @@ -6245,7 +6314,7 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, model.addAttribute("isZipFile", isZipFile); String res = ServiceUtility.convertFilePathToUrl(filePath); - model.addAttribute("filePath", res); + // model.addAttribute("filePath", res); if (res == null || res.trim().isEmpty()) { @@ -6255,7 +6324,17 @@ private String sharedTrainingResourceTemplate(String topicName, String fileType, return "sharedTrainingResource"; } res = ServiceUtility.convertFilePathToUrlWithUTFforBrowserRedirect(filePath); - return "redirect:/files/" + res; + String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + String encodedFileName = ""; + try { + encodedFileName = URLEncoder.encode(fileName, "UTF-8"); + } catch (UnsupportedEncodingException e) { + + logger.error("Exception", e); + } + + return "redirect:" + normalizedBaseUrl + "/training-resources/view-share/" + topicName + "/" + langName + "/" + + fileType + "/" + token + "/" + 0 + "/" + encodedFileName; } @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}/{trId}") @@ -6263,10 +6342,39 @@ public String getShareLinkofTrainingResource(HttpServletRequest req, @PathVariab @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceByToken(req, topicName, fileType, langName, token, principal, model); + } + + } + + @GetMapping("/shared-Training-Resource/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Image") || fileType.equals("Pdf")) { return res; } else { @@ -6280,10 +6388,40 @@ public String getShareLinkofTrainingResourceDoc_Excel(HttpServletRequest req, @P @PathVariable String fileType, @PathVariable String langName, @PathVariable int trId, Principal principal, Model model) { + TrainingResource tr = trainingResourceService.findByTrainingResourceId(trId); + if (tr.isAfterImplementationDate()) { + return "redirect:/error"; + } else { + int intFileType = ServiceUtility.getFileTypeIdByValue(fileType); + logger.info("FileType:{}", fileType); + logger.info("intFileType:{}", intFileType); + + String token = ""; + if (intFileType == CommonData.DOC) { + token = tr.getDocToken(); + } else if (intFileType == CommonData.EXCEL) { + token = tr.getExcelToken(); + } else if (intFileType == CommonData.PDF) { + token = tr.getPdfToken(); + } else if (intFileType == CommonData.IMAGE) { + token = tr.getImgToken(); + } + + return getShareLinkofTrainingResourceDoc_ExcelByToken(req, topicName, fileType, langName, token, principal, + model); + } + + } + + @GetMapping("/shared-training-resource-file/{topicName}/{fileType}/{langName}") + public String getShareLinkofTrainingResourceDoc_ExcelByToken(HttpServletRequest req, @PathVariable String topicName, + @PathVariable String fileType, @PathVariable String langName, @RequestParam String token, + Principal principal, Model model) { + User usr = getUser(principal); logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); - String res = sharedTrainingResourceTemplate(topicName, fileType, langName, trId, principal, model); + String res = sharedTrainingResourceTemplate(topicName, fileType, langName, token, principal, model); if (fileType.equals("Doc") || fileType.equals("Excel")) { return "sharedTrainingResource"; } else { @@ -6373,6 +6511,18 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, TrainingResource tr = trList.get(0); int trId = tr.getTrainingResourceId(); model.addAttribute("trId", trId); + + String token = ""; + if (fileTypeString.equals("Doc")) { + token = tr.getDocToken(); + } else if (fileTypeString.equals("Excel")) { + token = tr.getExcelToken(); + } else if (fileTypeString.equals("Pdf")) { + token = tr.getPdfToken(); + } else if (fileTypeString.equals("Image")) { + token = tr.getImgToken(); + } + String filePath = ServiceUtility.getTrainingResourceFilePath(tr, inputFileType); if (filePath.isEmpty()) { getModelTrainingResource(model); @@ -6381,10 +6531,23 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, } String finalUrl = ServiceUtility.convertFilePathToUrl(filePath); + boolean allowed = true; + + if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + + allowed = false; + + } + + if (allowed) { + model.addAttribute("token", token); + } else { + model.addAttribute("token", ""); + } if (action != null && !action.isEmpty() && action.equals("download")) { model.addAttribute("action", action); - if ((fileTypeString.equals("Doc") || fileTypeString.equals("Excel")) && (usr == null || !authorizedUsr)) { + if (!allowed) { model.addAttribute("error_msg", "Authentication Error"); @@ -6394,9 +6557,14 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, String normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; - return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?filePath=" - + URLEncoder.encode(finalUrl, "UTF-8"); - } catch (UnsupportedEncodingException e) { + // return "redirect:" + normalizedBaseUrl + + // "/downloadTrainingResource?filePath=" + // + URLEncoder.encode(finalUrl, "UTF-8"); + + return "redirect:" + normalizedBaseUrl + "/downloadTrainingResource?fileType=" + fileTypeString + + "&token=" + token; + + } catch (Exception e) { logger.error("Error in Download Package", e); } } @@ -6441,7 +6609,22 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, filePaths.add(ServiceUtility.convertFilePathToUrl(filePath)); } - model.addAttribute("filePaths", filePaths); + List fileNames = new ArrayList<>(); + for (String str : filePaths) { + + Path path = Paths.get(env.getProperty("spring.applicationexternalPath.name"), str); + String fileName = path.getFileName().toString(); + + fileNames.add(fileName); + + } + List pageIndexes = IntStream.range(0, filePaths.size()).boxed().collect(Collectors.toList()); + + if (allowed) { + model.addAttribute("pageIndexes", pageIndexes); + // model.addAttribute("filePaths", filePaths); + model.addAttribute("fileNames", fileNames); + } model.addAttribute("action", action); } @@ -6449,8 +6632,8 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, if (action != null && !action.isEmpty() && action.equals("share")) { model.addAttribute("action", action); - - model.addAttribute("shareUrl", finalUrl); + if (allowed) + model.addAttribute("shareUrl", finalUrl); } @@ -6476,6 +6659,781 @@ public String viewAndDownloadTrainingResource(HttpServletRequest req, return "trainingResources"; } + /************************ Project Report Start ******************************/ + + private String generateUniqueTokenForProjectReport() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!projectReportService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + + @GetMapping("/addProjectReport") + public String addProjectReportGet(HttpServletRequest req, Principal principal, Model model) { + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + List states = stateService.findAll(); + states.sort(Comparator.comparing(State::getStateName)); + model.addAttribute("states", states); + + Optional allDis = districtService.findByDistrictNameIgnoreCase(CommonData.ALL_DISTRICTS); + + int allDisId = allDis.map(District::getId).orElse(0); + + model.addAttribute("allDisId", allDisId); + + List projectReportList = new ArrayList<>(); + List tempProjectReportList = projectReportService.findAll(); + for (ProjectReport temp : tempProjectReportList) { + if (ServiceUtility.hasAnyProjectReportFile(temp)) { + projectReportList.add(temp); + } + } + + model.addAttribute("projectReportList", projectReportList); + + return "addProjectReport"; + } + + @PostMapping("/addProjectReport") + public String addProjectReportPost(HttpServletRequest req, Model model, Principal principal, + @RequestParam(name = "stateIdPR") int stateId, + @RequestParam(name = "districtIdPR") List districtIds, + @RequestParam(name = "filePR") List files) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + boolean viewSection = false; + + if (stateId == 0) { + model.addAttribute("error_msg", "State should not be null"); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addProjectReportGet(req, principal, model); + } + + if (districtIds.isEmpty() || files.isEmpty()) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", "District and Files should not be null"); + return addProjectReportGet(req, principal, model); + } + + State state = stateService.findById(stateId); + String stateName = state.getStateName(); + String state_dir = stateName.replace(" ", "_"); + + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + Set addedDistrict = new HashSet<>(); + Map> ErrorsforExistingFiles = new LinkedHashMap<>(); + boolean savedFlag = false; + + try { + + for (int i = 0; i < districtIds.size(); i++) { + if (i < files.size()) + logger.info("File: {}", files.get(i).getOriginalFilename()); + if (districtIds.get(i) != 0 && !files.get(i).isEmpty()) { + + District district = districtService.findById(districtIds.get(i)); + + if (district != null) { + String districtName = district.getDistrictName(); + if (!CommonData.ALL_DISTRICTS.equalsIgnoreCase(districtName)) { + int tempStateId = district.getState().getId(); + if (stateId != tempStateId) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", "District does not belong to the selected state"); + return addProjectReportGet(req, principal, model); + } + } + + Set existingFiles = ErrorsforExistingFiles.computeIfAbsent(districtName, + k -> new LinkedHashSet<>()); + StateDistrictMapping stateDistrictMapping = stateDistrictMappingService + .findByStateAndDistrict(state, district); + + boolean addedDistrictFlag = addedDistrict.add(district); + + if (stateDistrictMapping == null && addedDistrictFlag) { + stateDistrictMapping = new StateDistrictMapping(dateAdded, state, district); + + stateDistrictMappingService.save(stateDistrictMapping); + logger.info(" iter:{} stateDistrictMapping :{}", i, stateDistrictMapping); + } + + List prList = projectReportService + .findByStateDistrictMapping(stateDistrictMapping); + ProjectReport pr = null; + boolean oldPRFlag = false; + String oldPath = ""; + + if (prList.isEmpty()) { + pr = new ProjectReport(); + logger.info("iter:{} ProjectReport :{}", i, pr); + + } else { + pr = prList.get(0); + oldPRFlag = true; + } + + pr.setDateAdded(dateAdded); + pr.setStateDistrictMapping(stateDistrictMapping); + pr.setUser(usr); + + projectReportService.save(pr); // Saved first to get exact Id + int prId = pr.getProjectReportId(); + + String district_dir = districtName.replace(" ", "_"); + + Path rootPath = Paths.get(CommonData.uploadProjectReport, String.valueOf(prId), state_dir, + district_dir); + + String token = generateUniqueTokenForProjectReport(); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); + + Set extentions = new HashSet<>(); + String document = ""; + + MultipartFile file = files.get(i); + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file Error at District:" + districtName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addProjectReportGet(req, principal, model); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getPdfPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.PDF_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + pr.setPdfPath(document); + pr.setPdfToken(token); + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getDocPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.DOC_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + pr.setDocPath(document); + pr.setDocToken(token); + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getExcelPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.EXCEL_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + pr.setExcelPath(document); + pr.setExcelToken(token); + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getImgPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.IMAGE_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + pr.setImgPath(document); + pr.setImgToken(token); + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getPdfPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.PDF_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + pr.setPdfPath(document); + pr.setPdfToken(token); + } + + else if (ext.equals(CommonData.DOC_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getDocPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.DOC_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + pr.setDocPath(document); + pr.setDocToken(token); + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getExcelPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.EXCEL_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + pr.setExcelPath(document); + pr.setExcelToken(token); + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION)) { + if (oldPRFlag) { + oldPath = pr.getImgPath(); + if (oldPath != null && !oldPath.trim().isEmpty()) { + existingFiles.add(CommonData.IMAGE_EXTENSION); + continue; + } + } + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + pr.setImgPath(document); + pr.setImgToken(token); + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + viewSection = true; + model.addAttribute("viewSection", viewSection); + model.addAttribute("error_msg", + "Unsupported file Error at District:" + districtName); + + return addProjectReportGet(req, principal, model); + } + + } + } + + else { + model.addAttribute("error_msg", + "Zip contains different types of files Error at language:" + districtName); + viewSection = true; + model.addAttribute("viewSection", viewSection); + return addProjectReportGet(req, principal, model); + } + + } + + if (oldPath != null && !oldPath.trim().isEmpty()) { + + continue; + } + + pr.setUser(usr); + projectReportService.save(pr); + savedFlag = true; + + } + + } + + } + + } catch (Exception e) { + model.addAttribute("error_msg", "Some errors occurred, please contact the Admin"); + logger.error("Error:", e); + return addProjectReportGet(req, principal, model); + } + + model.addAttribute("viewSection", viewSection); + StringBuilder errorMsg = new StringBuilder(); + + for (Map.Entry> entry : ErrorsforExistingFiles.entrySet()) { + if (!entry.getValue().isEmpty()) { + errorMsg.append(entry.getKey()).append(": ").append(String.join(", ", entry.getValue())).append("
"); + } + } + + if (errorMsg.length() > 0) { + + String finalErrorMessage = "The following files types already exist. To update them, please go to the Edit section.”:
" + + errorMsg.toString(); + model.addAttribute("error_msg", finalErrorMessage); + } + + if (savedFlag) { + model.addAttribute("success_msg", CommonData.RECORD_SAVE_SUCCESS_MSG); + } + return addProjectReportGet(req, principal, model); + } + + @GetMapping("/projectReport/edit/{fileType}/{id}") + public String projectReportEditGet(@PathVariable String fileType, @PathVariable int id, HttpServletRequest req, + Model model, Principal principal) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + model.addAttribute("userInfo", usr); + + ProjectReport pr = projectReportService.findByProjectReportId(id); + + if (pr == null) { + + return "redirect:/addProjectReport"; + } + State state = pr.getStateDistrictMapping().getState(); + District district = pr.getStateDistrictMapping().getDistrict(); + List states = stateService.findAll(); + + List projectReportList = new ArrayList<>(); + List tempProjectReportList = projectReportService.findAll(); + for (ProjectReport temp : tempProjectReportList) { + if (ServiceUtility.hasAnyProjectReportFile(temp)) { + projectReportList.add(temp); + } + } + model.addAttribute("states", states); + model.addAttribute("projectReportList", projectReportList); + model.addAttribute("ProjectReport", pr); + model.addAttribute("state", state); + model.addAttribute("district", district); + + model.addAttribute("id", id); + String filePath = ""; + + if (fileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + filePath = pr.getDocPath(); + model.addAttribute("fileType", "Doc"); + + } + + else if (fileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + filePath = pr.getPdfPath(); + model.addAttribute("fileType", "Pdf"); + } + + else if (fileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + filePath = pr.getImgPath(); + model.addAttribute("fileType", "Image"); + } + + else if (fileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + filePath = pr.getExcelPath(); + model.addAttribute("fileType", "Excel"); + } + + if (filePath.toLowerCase().endsWith(".zip")) { + model.addAttribute("zipFile", filePath); + } + + else { + model.addAttribute("nonZipFile", filePath); + + } + + return "updateProjectReport"; + } + + @PostMapping("/updateProjectReport") + public String updateProjectReportPost(HttpServletRequest req, Model model, Principal principal, + @RequestParam("file") MultipartFile file) { + + User usr = getUser(principal); + logger.info("{} {} {}", usr.getUsername(), req.getMethod(), req.getRequestURI()); + + model.addAttribute("userInfo", usr); + + String prId = req.getParameter("prId"); + String stateId = req.getParameter("stateId"); + String districtId = req.getParameter("districtId"); + String fileType = req.getParameter("fileType"); + int prIdInt = Integer.parseInt(prId); + int stateIdInt = Integer.parseInt(stateId); + int districtIdInt = Integer.parseInt(districtId); + int oldprId = prIdInt; + + ProjectReport oldProjectReport = projectReportService.findByProjectReportId(prIdInt); + String originalFileType = ""; + String oldPath = ""; + + boolean fileMatch = false; + String token = ""; + + if (oldProjectReport == null) { + model.addAttribute("error_msg", "Project Report doesn't exist"); + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + if (fileType.equals("Doc")) { + originalFileType = CommonData.Doc_OR_ZIP_OF_DOCS; + if (oldProjectReport != null) { + oldPath = oldProjectReport.getDocPath(); + token = oldProjectReport.getDocToken(); + } + } + + else if (fileType.equals("Pdf")) { + originalFileType = CommonData.PDF_OR_ZIP_OF_PDFS; + if (oldProjectReport != null) { + oldPath = oldProjectReport.getPdfPath(); + token = oldProjectReport.getPdfToken(); + } + } + + else if (fileType.equals("Image")) { + originalFileType = CommonData.image_OR_ZIP_OF_IMAGES; + if (oldProjectReport != null) { + oldPath = oldProjectReport.getImgPath(); + token = oldProjectReport.getImgToken(); + } + + } else if (fileType.equals("Excel")) { + originalFileType = CommonData.Excel_OR_ZIP_OF_EXCELS; + if (oldProjectReport != null) { + oldPath = oldProjectReport.getExcelPath(); + token = oldProjectReport.getExcelToken(); + } + } + + State state = stateService.findById(stateIdInt); + District district = districtService.findById(districtIdInt); + if (state == null || district == null) { + model.addAttribute("error_msg", "state or distrct missing"); + return projectReportEditGet(fileType, oldprId, req, model, principal); + } + String districtName = district.getDistrictName(); + if (!CommonData.ALL_DISTRICTS.equalsIgnoreCase(districtName)) { + int tempStateId = district.getState().getId(); + if (stateIdInt != tempStateId) { + model.addAttribute("error_msg", "District doesn't belong to selected state"); + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + } + + StateDistrictMapping stateDistrict = stateDistrictMappingService.findByStateAndDistrict(state, district); + Timestamp dateAdded = ServiceUtility.getCurrentTime(); + + if (oldPath == null || oldPath.isEmpty()) { + model.addAttribute("error_msg", + "The data has already moved to another Project Report. Please check the View section to edit."); + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + ProjectReport newProjectReport; + boolean newProjectData = true; + + if (stateDistrict != null) { + List prList = projectReportService.findByStateDistrictMapping(stateDistrict); + + if (prList.isEmpty()) { + newProjectReport = new ProjectReport(); + logger.info("new Project Report Data"); + + } else if (!prList.contains(oldProjectReport)) { + newProjectReport = prList.get(0); + logger.info("new Project Report Data from prList"); + } else { + newProjectData = false; + newProjectReport = oldProjectReport; + logger.info("old Project Report data"); + } + } else { + + stateDistrict = new StateDistrictMapping(dateAdded, state, district); + + stateDistrictMappingService.save(stateDistrict); + newProjectReport = new ProjectReport(); + + } + + newProjectReport.setStateDistrictMapping(stateDistrict); + newProjectReport.setUser(usr); + + // To get exact Id of new project Report Data + if (newProjectData) { + newProjectReport.setDateAdded(dateAdded); + projectReportService.save(newProjectReport); + prIdInt = newProjectReport.getProjectReportId(); + token = generateUniqueTokenForProjectReport(); + + } + + try { + + String district_dir = districtName.replace(" ", "_"); + String stateName = state.getStateName(); + String state_dir = stateName.replace(" ", "_"); + + Path rootPath = Paths.get(CommonData.uploadProjectReport, String.valueOf(prId), state_dir, district_dir); + + String pdfFolder = Paths.get(rootPath.toString(), "pdf", token).toString(); + String docFolder = Paths.get(rootPath.toString(), "docx_or_odt", token).toString(); + String excelFolder = Paths.get(rootPath.toString(), "excel_or_csv", token).toString(); + String imageFolder = Paths.get(rootPath.toString(), "image", token).toString(); + boolean fileFlag = false; + + if (!file.isEmpty()) { + fileFlag = true; + + Set extentions = new HashSet<>(); + String document = ""; + + String fileExtention = ServiceUtility.checkFileExtensions(file); + + if (fileExtention.equals(CommonData.UNSUPPORTED_EXTENSION)) { + model.addAttribute("error_msg", "Unsupported file"); + + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + else if (fileExtention.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newProjectReport.setPdfPath(document); + newProjectReport.setPdfToken(token); + if (newProjectData) + oldProjectReport.setPdfPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newProjectReport.setDocPath(document); + newProjectReport.setDocToken(token); + if (newProjectData) + oldProjectReport.setDocPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newProjectReport.setExcelPath(document); + newProjectReport.setExcelToken(token); + if (newProjectData) + oldProjectReport.setExcelPath(""); + fileMatch = true; + } + + else if (fileExtention.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newProjectReport.setImgPath(document); + newProjectReport.setImgToken(token); + if (newProjectData) + oldProjectReport.setImgPath(""); + fileMatch = true; + } + + if (fileExtention.equals(CommonData.ZIP_EXTENSION)) { + + extentions = ServiceUtility.checkFileExtentionsInZip(file); + if (extentions.size() == 1) { + for (String ext : extentions) { + if (ext.equals(CommonData.PDF_EXTENSION) + && originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + document = ServiceUtility.uploadMediaFile(file, env, pdfFolder); + newProjectReport.setPdfPath(document); + newProjectReport.setPdfToken(token); + if (newProjectData) { + oldProjectReport.setPdfPath(""); + } + + fileMatch = true; + + } + + else if (ext.equals(CommonData.DOC_EXTENSION) + && originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + document = ServiceUtility.uploadMediaFile(file, env, docFolder); + newProjectReport.setDocPath(document); + newProjectReport.setDocToken(token); + if (newProjectData) { + oldProjectReport.setDocPath(""); + } + + fileMatch = true; + } + + else if (ext.equals(CommonData.EXCEL_EXTENSION) + && originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + document = ServiceUtility.uploadMediaFile(file, env, excelFolder); + newProjectReport.setExcelPath(document); + newProjectReport.setExcelToken(token); + if (newProjectData) { + oldProjectReport.setExcelPath(""); + } + + fileMatch = true; + } + + else if (ext.equals(CommonData.IMAGE_EXTENSION) + && originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + document = ServiceUtility.uploadMediaFile(file, env, imageFolder); + newProjectReport.setImgPath(document); + newProjectReport.setImgToken(token); + if (newProjectData) { + oldProjectReport.setImgPath(""); + } + + fileMatch = true; + + } + + else if (ext.equals(CommonData.UNSUPPORTED_EXTENSION)) { + + model.addAttribute("error_msg", "Unsupported file Error "); + + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + } + } + + else { + model.addAttribute("error_msg", "Zip contains different types of files Error"); + + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + } + + if (oldPath != null && oldPath.endsWith(".zip")) { + + String extractDir = oldPath.replace(".zip", ""); + + Path extractDirPath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), extractDir); + FileUtils.deleteDirectory(extractDirPath.toFile()); + + } + if (newProjectData) { + newProjectReport.setDateAdded(dateAdded); + } + + newProjectReport.setStateDistrictMapping(stateDistrict); + newProjectReport.setUser(usr); + + if (fileMatch) { + if (newProjectData) { + newProjectReport.setDateAdded(dateAdded); + } + newProjectReport.setStateDistrictMapping(stateDistrict); + projectReportService.save(newProjectReport); + if (newProjectData) { + logger.info("1st old data save is called"); + oldProjectReport.setUser(usr); + projectReportService.save(oldProjectReport); + } + } else { + model.addAttribute("error_msg", "Please upload a file of the same type. E.g., DOC for DOC type."); + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + } + + // File Empty + else { + if (newProjectData && !fileFlag && oldPath != null && !oldPath.isEmpty()) { + + Path sourcePath = Paths.get(env.getProperty("spring.applicationexternalPath.name"), oldPath); + File sourceFile = sourcePath.toFile(); + String fileName = sourcePath.getFileName().toString(); + + String document = ""; + + if (sourceFile.exists()) { + if (originalFileType.equals(CommonData.Doc_OR_ZIP_OF_DOCS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, docFolder, fileName, env); + + newProjectReport.setDocPath(document); + newProjectReport.setDocToken(token); + oldProjectReport.setDocPath(""); + + } else if (originalFileType.equals(CommonData.Excel_OR_ZIP_OF_EXCELS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, excelFolder, fileName, + env); + + newProjectReport.setExcelPath(document); + newProjectReport.setExcelToken(token); + oldProjectReport.setExcelPath(""); + + } else if (originalFileType.equals(CommonData.PDF_OR_ZIP_OF_PDFS)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, pdfFolder, fileName, env); + + newProjectReport.setPdfPath(document); + newProjectReport.setPdfToken(token); + oldProjectReport.setPdfPath(""); + + } else if (originalFileType.equals(CommonData.image_OR_ZIP_OF_IMAGES)) { + + document = ServiceUtility.copyFileAndGetRelativePath(sourceFile, imageFolder, fileName, + env); + newProjectReport.setImgPath(document); + newProjectReport.setImgToken(token); + oldProjectReport.setImgPath(""); + + } + + newProjectReport.setDateAdded(dateAdded); + newProjectReport.setUser(usr); + + projectReportService.save(newProjectReport); + logger.info("2nd old data save is called"); + projectReportService.save(oldProjectReport); + } + + } + } + + } catch (Exception e) { + logger.error("Exception while updating Project Report: {} {} {}", state, district, file, e); + model.addAttribute("error_msg", CommonData.RECORD_ERROR); + + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + model.addAttribute("success_msg", CommonData.RECORD_UPDATE_SUCCESS_MSG); + + return projectReportEditGet(originalFileType, oldprId, req, model, principal); + } + + /************************ Project Report End ********************************/ + @GetMapping("/trainingModules") public String hstTrainingModules(@RequestParam(name = "week", required = false, defaultValue = "") String weekName, @RequestParam(name = "lan", required = false, defaultValue = "") String langName, HttpServletRequest req, diff --git a/src/main/java/com/health/model/City.java b/src/main/java/com/health/model/City.java index 9a697fe3..f3efbd5f 100644 --- a/src/main/java/com/health/model/City.java +++ b/src/main/java/com/health/model/City.java @@ -46,7 +46,7 @@ public class City implements Comparable, Serializable { @JoinColumn(name = "district_id") private District district; - @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set events = new HashSet(); public int getId() { diff --git a/src/main/java/com/health/model/District.java b/src/main/java/com/health/model/District.java index 2d66ad38..a9a03bbb 100644 --- a/src/main/java/com/health/model/District.java +++ b/src/main/java/com/health/model/District.java @@ -50,12 +50,23 @@ public class District implements Comparable, Serializable { @JoinColumn(name = "state_id") private State state; - @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set cities = new HashSet(); - @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) Set events = new HashSet(); + @OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set stateDistrictMappings = new HashSet(); + + public Set getStateDistrictMappings() { + return stateDistrictMappings; + } + + public void setStateDistrictMappings(Set stateDistrictMappings) { + this.stateDistrictMappings = stateDistrictMappings; + } + public int getId() { return id; } diff --git a/src/main/java/com/health/model/ProjectReport.java b/src/main/java/com/health/model/ProjectReport.java new file mode 100644 index 00000000..07f0f5d5 --- /dev/null +++ b/src/main/java/com/health/model/ProjectReport.java @@ -0,0 +1,234 @@ + +package com.health.model; + +import java.io.Serializable; +import java.nio.file.Paths; +import java.sql.Timestamp; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "project_report") +public class ProjectReport implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "project_rep_id", nullable = false, updatable = false) + private int projectReportId; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @Column(name = "pdf_path", length = 1000) + private String pdfPath; + + @Column(name = "doc_path", length = 1000) + private String docPath; + + @Column(name = "excel_path", length = 1000) + private String excelPath; + + @Column(name = "img_path", length = 1000) + private String imgPath; + + @Column(unique = true, length = 1000) + private String pdfToken; + + @Column(unique = true, length = 1000) + private String docToken; + + @Column(unique = true, length = 1000) + private String imgToken; + + @Column(unique = true, length = 1000) + private String excelToken; + + @ManyToOne + @JoinColumn(name = "state_district_id") + private StateDistrictMapping stateDistrictMapping; + + @ManyToOne + @JoinColumn(name = "user_id", nullable = false) + private User user; + + public int getProjectReportId() { + return projectReportId; + } + + public String getPdfToken() { + return pdfToken; + } + + public void setPdfToken(String pdfToken) { + this.pdfToken = pdfToken; + } + + public String getDocToken() { + return docToken; + } + + public void setDocToken(String docToken) { + this.docToken = docToken; + } + + public String getImgToken() { + return imgToken; + } + + public void setImgToken(String imgToken) { + this.imgToken = imgToken; + } + + public String getExcelToken() { + return excelToken; + } + + public void setExcelToken(String excelToken) { + this.excelToken = excelToken; + } + + public void setProjectReportId(int projectReportId) { + this.projectReportId = projectReportId; + } + + public StateDistrictMapping getStateDistrictMapping() { + return stateDistrictMapping; + } + + public void setStateDistrictMapping(StateDistrictMapping stateDistrictMapping) { + this.stateDistrictMapping = stateDistrictMapping; + } + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public String getPdfPath() { + return pdfPath; + } + + public void setPdfPath(String pdfPath) { + this.pdfPath = pdfPath; + } + + public String getDocPath() { + return docPath; + } + + public void setDocPath(String docPath) { + this.docPath = docPath; + } + + public String getExcelPath() { + return excelPath; + } + + public void setExcelPath(String excelPath) { + this.excelPath = excelPath; + } + + public String getImgPath() { + return imgPath; + } + + public void setImgPath(String imgPath) { + this.imgPath = imgPath; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getPdfFileNameWithorWitoutZip() { + if (pdfPath == null || pdfPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(pdfPath).getFileName().toString(); + return fileName; + } + + public String getDocFileNameWithorWitoutZip() { + if (docPath == null || docPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(docPath).getFileName().toString(); + return fileName; + } + + public String getExcelFileNameWithorWitoutZip() { + if (excelPath == null || excelPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(excelPath).getFileName().toString(); + return fileName; + } + + public String getImageFileNameWithorWitoutZip() { + if (imgPath == null || imgPath.trim().isEmpty()) { + return "NA"; + } + String fileName = Paths.get(imgPath).getFileName().toString(); + return fileName; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public ProjectReport(Timestamp dateAdded, String pdfPath, String docPath, String excelPath, String imgPath, + String pdfToken, String docToken, String imgToken, String excelToken, + StateDistrictMapping stateDistrictMapping, User user) { + super(); + this.dateAdded = dateAdded; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + this.pdfToken = pdfToken; + this.docToken = docToken; + this.imgToken = imgToken; + this.excelToken = excelToken; + this.stateDistrictMapping = stateDistrictMapping; + this.user = user; + } + + public ProjectReport(Timestamp dateAdded, StateDistrictMapping stateDistrictMapping, String pdfPath, String docPath, + String excelPath, String imgPath) { + + this.dateAdded = dateAdded; + this.stateDistrictMapping = stateDistrictMapping; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + } + + public ProjectReport() { + + } + +} diff --git a/src/main/java/com/health/model/State.java b/src/main/java/com/health/model/State.java index 9f5ac404..83eedac2 100644 --- a/src/main/java/com/health/model/State.java +++ b/src/main/java/com/health/model/State.java @@ -41,12 +41,23 @@ public class State implements Comparable, Serializable { */ private Timestamp dateAdded; - @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set Districts = new HashSet(); + @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set districts = new HashSet(); - @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set events = new HashSet(); + @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + private Set stateDistrictMappings = new HashSet(); + + public Set getStateDistrictMappings() { + return stateDistrictMappings; + } + + public void setStateDistrictMappings(Set stateDistrictMappings) { + this.stateDistrictMappings = stateDistrictMappings; + } + public int getId() { return id; } @@ -72,11 +83,11 @@ public void setDateAdded(Timestamp dateAdded) { } public Set getDistricts() { - return Districts; + return districts; } public void setDistricts(Set districts) { - Districts = districts; + this.districts = districts; } @Override diff --git a/src/main/java/com/health/model/StateDistrictMapping.java b/src/main/java/com/health/model/StateDistrictMapping.java new file mode 100644 index 00000000..9d8d28e0 --- /dev/null +++ b/src/main/java/com/health/model/StateDistrictMapping.java @@ -0,0 +1,119 @@ + +package com.health.model; + +import java.io.Serializable; +import java.sql.Timestamp; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "state_district_mapping") +public class StateDistrictMapping implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "state_dis_id", nullable = false, updatable = false) + private int stateDisId; + + @Column(name = "status", nullable = false) + private boolean status = true; + + @Column(name = "date_added", nullable = false) + private Timestamp dateAdded; + + @ManyToOne + @JoinColumn(name = "state_id") + private State state; + + @ManyToOne + @JoinColumn(name = "district_id") + private District district; + + @OneToMany(mappedBy = "stateDistrictMapping", cascade = CascadeType.ALL) + private Set projectReports = new HashSet(); + + public boolean isStatus() { + return status; + } + + public void setStatus(boolean status) { + this.status = status; + } + + public int getStateDisId() { + return stateDisId; + } + + public void setStateDisId(int stateDisId) { + this.stateDisId = stateDisId; + } + + public Set getProjectReports() { + return projectReports; + } + + public void setProjectReports(Set projectReports) { + this.projectReports = projectReports; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public District getDistrict() { + return district; + } + + public void setDistrict(District district) { + this.district = district; + } + + public Timestamp getDateAdded() { + return dateAdded; + } + + public void setDateAdded(Timestamp dateAdded) { + this.dateAdded = dateAdded; + } + + public StateDistrictMapping(Timestamp dateAdded, State state, District district) { + + this.dateAdded = dateAdded; + this.state = state; + this.district = district; + + } + + public StateDistrictMapping() { + + } + + public static Comparator SortByStateName = new Comparator() { + + @Override + public int compare(StateDistrictMapping sd1, StateDistrictMapping sd2) { + + return sd1.getState().getStateName().compareTo(sd2.getState().getStateName()); + + } + }; + +} diff --git a/src/main/java/com/health/model/TrainingResource.java b/src/main/java/com/health/model/TrainingResource.java index 33664880..1fff2802 100644 --- a/src/main/java/com/health/model/TrainingResource.java +++ b/src/main/java/com/health/model/TrainingResource.java @@ -3,6 +3,7 @@ import java.io.Serializable; import java.nio.file.Paths; import java.sql.Timestamp; +import java.time.LocalDate; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,6 +14,8 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; +import com.health.utility.CommonData; + @Entity @Table(name = "training_resource") public class TrainingResource implements Serializable { @@ -50,6 +53,18 @@ public class TrainingResource implements Serializable { @Column(name = "img_path", length = 1000) private String imgPath; + @Column(unique = true, length = 1000) + private String pdfToken; + + @Column(unique = true, length = 1000) + private String docToken; + + @Column(unique = true, length = 1000) + private String imgToken; + + @Column(unique = true, length = 1000) + private String excelToken; + @ManyToOne @JoinColumn(name = "user_id", nullable = false) private User user; @@ -126,6 +141,38 @@ public void setUser(User user) { this.user = user; } + public String getPdfToken() { + return pdfToken; + } + + public void setPdfToken(String pdfToken) { + this.pdfToken = pdfToken; + } + + public String getDocToken() { + return docToken; + } + + public void setDocToken(String docToken) { + this.docToken = docToken; + } + + public String getImgToken() { + return imgToken; + } + + public void setImgToken(String imgToken) { + this.imgToken = imgToken; + } + + public String getExcelToken() { + return excelToken; + } + + public void setExcelToken(String excelToken) { + this.excelToken = excelToken; + } + public String getPdfFileNameWithorWitoutZip() { if (pdfPath == null || pdfPath.trim().isEmpty()) { return "NA"; @@ -166,6 +213,31 @@ public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } + public boolean isAfterImplementationDate() { + + LocalDate resourceDate = this.dateAdded.toLocalDateTime().toLocalDate(); + + return !resourceDate.isBefore(CommonData.IMPL_DATE_TRAINING_RESOURCE); + } + + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, Category category, String pdfPath, + String docPath, String excelPath, String imgPath, String pdfToken, String docToken, String imgToken, + String excelToken, User user) { + super(); + this.dateAdded = dateAdded; + this.topicLanMapping = topicLanMapping; + this.category = category; + this.pdfPath = pdfPath; + this.docPath = docPath; + this.excelPath = excelPath; + this.imgPath = imgPath; + this.pdfToken = pdfToken; + this.docToken = docToken; + this.imgToken = imgToken; + this.excelToken = excelToken; + this.user = user; + } + public TrainingResource(Timestamp dateAdded, TopicLanMapping topicLanMapping, String pdfPath, String docPath, String excelPath, String imgPath) { diff --git a/src/main/java/com/health/model/User.java b/src/main/java/com/health/model/User.java index 64f261c5..e8868e76 100644 --- a/src/main/java/com/health/model/User.java +++ b/src/main/java/com/health/model/User.java @@ -183,6 +183,10 @@ public void setOrgRolev(OrganizationRole orgRolev) { @JsonIgnore private Set trainingResources = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JsonIgnore + private Set projectReports = new HashSet(); + @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonIgnore private Set topics = new HashSet(); @@ -287,6 +291,14 @@ public void setCourseCatTopicMappings(Set courseCatTopicM this.courseCatTopicMappings = courseCatTopicMappings; } + public Set getProjectReports() { + return projectReports; + } + + public void setProjectReports(Set projectReports) { + this.projectReports = projectReports; + } + @Override public String getPassword() { return password; diff --git a/src/main/java/com/health/repository/DistrictRepository.java b/src/main/java/com/health/repository/DistrictRepository.java index d804173c..509e11c6 100644 --- a/src/main/java/com/health/repository/DistrictRepository.java +++ b/src/main/java/com/health/repository/DistrictRepository.java @@ -1,7 +1,9 @@ package com.health.repository; import java.util.List; +import java.util.Optional; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.health.model.District; @@ -39,6 +41,13 @@ public interface DistrictRepository extends CrudRepository { * @param state state object * @return list of District object */ - List findAllBystate(State state); + List findAllByState(State state); + + Optional findByDistrictNameIgnoreCase(String districtName); + + @Query("SELECT d FROM District d ORDER BY d.districtName") + List findAllOrderByName(); + + List findAllByStateOrderByDistrictNameAsc(State state); } diff --git a/src/main/java/com/health/repository/ProjectReportRepository.java b/src/main/java/com/health/repository/ProjectReportRepository.java new file mode 100644 index 00000000..bb13c8cd --- /dev/null +++ b/src/main/java/com/health/repository/ProjectReportRepository.java @@ -0,0 +1,32 @@ + +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.ProjectReport; +import com.health.model.StateDistrictMapping; + +public interface ProjectReportRepository extends JpaRepository { + + ProjectReport findByProjectReportId(int projectReportId); + + List findByStateDistrictMapping(StateDistrictMapping stateDistrictMapping); + + List findByStateDistrictMappingInAndStatusTrue(List stateDistrictMappingList); + + List findAllByStatusTrue(); + + ProjectReport findByPdfToken(String pdfToken); + + ProjectReport findByDocToken(String docToken); + + ProjectReport findByExcelToken(String excelToken); + + ProjectReport findByImgToken(String docToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + +} diff --git a/src/main/java/com/health/repository/StateDistrictMappingRepository.java b/src/main/java/com/health/repository/StateDistrictMappingRepository.java new file mode 100644 index 00000000..4813039a --- /dev/null +++ b/src/main/java/com/health/repository/StateDistrictMappingRepository.java @@ -0,0 +1,22 @@ + +package com.health.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.health.model.District; +import com.health.model.State; +import com.health.model.StateDistrictMapping; + +public interface StateDistrictMappingRepository extends JpaRepository { + + StateDistrictMapping findByStateDisId(int stateDisId); + + List findByDistrict(District district); + + List findByState(State state); + + StateDistrictMapping findByStateAndDistrict(State state, District district); + +} diff --git a/src/main/java/com/health/repository/StateRepository.java b/src/main/java/com/health/repository/StateRepository.java index 8cc3d62a..3daef706 100644 --- a/src/main/java/com/health/repository/StateRepository.java +++ b/src/main/java/com/health/repository/StateRepository.java @@ -1,5 +1,8 @@ package com.health.repository; +import java.util.List; + +import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import com.health.model.State; @@ -22,4 +25,7 @@ public interface StateRepository extends CrudRepository { */ State findBystateName(String name); + @Query("SELECT s FROM State s ORDER BY s.stateName") + List findAllOrderByName(); + } diff --git a/src/main/java/com/health/repository/TrainingResourceRepository.java b/src/main/java/com/health/repository/TrainingResourceRepository.java index ac83a2fd..643f03a2 100644 --- a/src/main/java/com/health/repository/TrainingResourceRepository.java +++ b/src/main/java/com/health/repository/TrainingResourceRepository.java @@ -17,4 +17,15 @@ public interface TrainingResourceRepository extends JpaRepository findAllByStatusTrue(); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String docToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/DistrictService.java b/src/main/java/com/health/service/DistrictService.java index 911b696c..9e46cb9c 100644 --- a/src/main/java/com/health/service/DistrictService.java +++ b/src/main/java/com/health/service/DistrictService.java @@ -1,6 +1,7 @@ package com.health.service; import java.util.List; +import java.util.Optional; import com.health.model.District; import com.health.model.State; @@ -45,4 +46,6 @@ public interface DistrictService { */ List findAllByState(State state); + Optional findByDistrictNameIgnoreCase(String districtName); + } diff --git a/src/main/java/com/health/service/ProjectReportService.java b/src/main/java/com/health/service/ProjectReportService.java new file mode 100644 index 00000000..ca4acd87 --- /dev/null +++ b/src/main/java/com/health/service/ProjectReportService.java @@ -0,0 +1,36 @@ + +package com.health.service; + +import java.util.List; + +import com.health.model.ProjectReport; +import com.health.model.StateDistrictMapping; + +public interface ProjectReportService { + + ProjectReport findByProjectReportId(int projectReportId); + + List findByStateDistrictMapping(StateDistrictMapping stateDistrictMapping); + + List findByStateDistrictMappingInAndStatusTrue(List stateDistrictMappingList); + + List findAll(); + + List findAllByStatusTrue(); + + void save(ProjectReport projectReport); + + void saveAll(List projectReportList); + + ProjectReport findByPdfToken(String pdfToken); + + ProjectReport findByDocToken(String docToken); + + ProjectReport findByExcelToken(String excelToken); + + ProjectReport findByImgToken(String imgToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + +} diff --git a/src/main/java/com/health/service/StateDistrictMappingService.java b/src/main/java/com/health/service/StateDistrictMappingService.java new file mode 100644 index 00000000..dd18ee5f --- /dev/null +++ b/src/main/java/com/health/service/StateDistrictMappingService.java @@ -0,0 +1,26 @@ + +package com.health.service; + +import java.util.List; + +import com.health.model.District; +import com.health.model.State; +import com.health.model.StateDistrictMapping; + +public interface StateDistrictMappingService { + + StateDistrictMapping findByStateDistrictId(int stateDisId); + + List findByDistrict(District district); + + List findByState(State state); + + StateDistrictMapping findByStateAndDistrict(State state, District district); + + List findAll(); + + void save(StateDistrictMapping stateDistrictMapping); + + void saveAll(List stateDistrictMappingList); + +} diff --git a/src/main/java/com/health/service/TrainingResourceService.java b/src/main/java/com/health/service/TrainingResourceService.java index c82f9b29..4a7f7691 100644 --- a/src/main/java/com/health/service/TrainingResourceService.java +++ b/src/main/java/com/health/service/TrainingResourceService.java @@ -21,4 +21,15 @@ public interface TrainingResourceService { void saveAll(List trainingResourceList); + TrainingResource findByPdfToken(String pdfToken); + + TrainingResource findByDocToken(String docToken); + + TrainingResource findByExcelToken(String excelToken); + + TrainingResource findByImgToken(String imgToken); + + boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken); + } diff --git a/src/main/java/com/health/service/impl/DistrictServiceImpl.java b/src/main/java/com/health/service/impl/DistrictServiceImpl.java index 7e45986f..0195b302 100644 --- a/src/main/java/com/health/service/impl/DistrictServiceImpl.java +++ b/src/main/java/com/health/service/impl/DistrictServiceImpl.java @@ -1,6 +1,5 @@ package com.health.service.impl; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -60,10 +59,8 @@ public District findById(int id) { */ @Override public List findAll() { - // TODO Auto-generated method stub - List local = (List) distRepo.findAll(); - Collections.sort(local); - return local; + + return distRepo.findAllOrderByName(); } /** @@ -71,10 +68,14 @@ public List findAll() { */ @Override public List findAllByState(State state) { - // TODO Auto-generated method stub - List local = distRepo.findAllBystate(state); - Collections.sort(local); - return local; + + return distRepo.findAllByStateOrderByDistrictNameAsc(state); + } + + @Override + public Optional findByDistrictNameIgnoreCase(String districtName) { + + return distRepo.findByDistrictNameIgnoreCase(districtName); } } diff --git a/src/main/java/com/health/service/impl/ProjectReportServiceImpl.java b/src/main/java/com/health/service/impl/ProjectReportServiceImpl.java new file mode 100644 index 00000000..6ace7143 --- /dev/null +++ b/src/main/java/com/health/service/impl/ProjectReportServiceImpl.java @@ -0,0 +1,98 @@ + +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.ProjectReport; +import com.health.model.StateDistrictMapping; +import com.health.repository.ProjectReportRepository; +import com.health.service.ProjectReportService; + +@Service +public class ProjectReportServiceImpl implements ProjectReportService { + + private static final Logger logger = LoggerFactory.getLogger(ProjectReportServiceImpl.class); + + @Autowired + private ProjectReportRepository repo; + + @Override + public ProjectReport findByProjectReportId(int projectReportId) { + + return repo.findByProjectReportId(projectReportId); + } + + @Override + public List findByStateDistrictMapping(StateDistrictMapping stateDistrictMapping) { + + return repo.findByStateDistrictMapping(stateDistrictMapping); + } + + @Override + public List findByStateDistrictMappingInAndStatusTrue( + List stateDistrictMappingList) { + + return repo.findByStateDistrictMappingInAndStatusTrue(stateDistrictMappingList); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public List findAllByStatusTrue() { + + return repo.findAllByStatusTrue(); + } + + @Override + public void save(ProjectReport projectReport) { + repo.save(projectReport); + + } + + @Override + public void saveAll(List projectReportList) { + repo.saveAll(projectReportList); + + } + + @Override + public ProjectReport findByPdfToken(String pdfToken) { + + return repo.findByPdfToken(pdfToken); + } + + @Override + public ProjectReport findByDocToken(String docToken) { + + return repo.findByDocToken(docToken); + } + + @Override + public ProjectReport findByExcelToken(String excelToken) { + + return repo.findByExcelToken(excelToken); + } + + @Override + public ProjectReport findByImgToken(String imgToken) { + + return repo.findByImgToken(imgToken); + } + + @Override + public boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken) { + + return repo.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(pdfToken, docToken, excelToken, imgToken); + } + +} diff --git a/src/main/java/com/health/service/impl/StateDistrictMappingServiceImpl.java b/src/main/java/com/health/service/impl/StateDistrictMappingServiceImpl.java new file mode 100644 index 00000000..41a079dc --- /dev/null +++ b/src/main/java/com/health/service/impl/StateDistrictMappingServiceImpl.java @@ -0,0 +1,67 @@ + +package com.health.service.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.health.model.District; +import com.health.model.State; +import com.health.model.StateDistrictMapping; +import com.health.repository.StateDistrictMappingRepository; +import com.health.service.StateDistrictMappingService; + +@Service +public class StateDistrictMappingServiceImpl implements StateDistrictMappingService { + + private static final Logger logger = LoggerFactory.getLogger(StateDistrictMappingServiceImpl.class); + + @Autowired + private StateDistrictMappingRepository repo; + + @Override + public StateDistrictMapping findByStateDistrictId(int stateDisId) { + + return repo.findByStateDisId(stateDisId); + } + + @Override + public List findByDistrict(District district) { + + return repo.findByDistrict(district); + } + + @Override + public List findByState(State state) { + + return repo.findByState(state); + } + + @Override + public StateDistrictMapping findByStateAndDistrict(State state, District district) { + + return repo.findByStateAndDistrict(state, district); + } + + @Override + public List findAll() { + + return repo.findAll(); + } + + @Override + public void save(StateDistrictMapping stateDistrictMapping) { + repo.save(stateDistrictMapping); + + } + + @Override + public void saveAll(List stateDistrictMappingList) { + repo.saveAll(stateDistrictMappingList); + + } + +} diff --git a/src/main/java/com/health/service/impl/StateServiceImpl.java b/src/main/java/com/health/service/impl/StateServiceImpl.java index ad6523cd..fed25c24 100644 --- a/src/main/java/com/health/service/impl/StateServiceImpl.java +++ b/src/main/java/com/health/service/impl/StateServiceImpl.java @@ -1,6 +1,5 @@ package com.health.service.impl; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; @@ -60,10 +59,9 @@ public State findById(int id) { */ @Override public List findAll() { - // TODO Auto-generated method stub - List local = (List) stateRepo.findAll(); - Collections.sort(local); - return local; + + return stateRepo.findAllOrderByName(); + } /** diff --git a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java index 5fcf20a1..c2814063 100644 --- a/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java +++ b/src/main/java/com/health/service/impl/TrainingReourceServiceImpl.java @@ -62,4 +62,35 @@ public List findAllByStatusTrue() { return repo.findAllByStatusTrue(); } + @Override + public TrainingResource findByPdfToken(String pdfToken) { + + return repo.findByPdfToken(pdfToken); + } + + @Override + public TrainingResource findByDocToken(String docToken) { + + return repo.findByDocToken(docToken); + } + + @Override + public TrainingResource findByExcelToken(String excelToken) { + + return repo.findByExcelToken(excelToken); + } + + @Override + public TrainingResource findByImgToken(String imgToken) { + + return repo.findByImgToken(imgToken); + } + + @Override + public boolean existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(String pdfToken, String docToken, String excelToken, + String imgToken) { + + return repo.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(pdfToken, docToken, excelToken, imgToken); + } + } diff --git a/src/main/java/com/health/threadpool/TaskProcessingService.java b/src/main/java/com/health/threadpool/TaskProcessingService.java index 7034d12e..16065329 100644 --- a/src/main/java/com/health/threadpool/TaskProcessingService.java +++ b/src/main/java/com/health/threadpool/TaskProcessingService.java @@ -43,6 +43,7 @@ import com.health.model.QueueManagement; import com.health.model.ResearchPaper; import com.health.model.TopicCategoryMapping; +import com.health.model.TrainingResource; import com.health.model.Tutorial; import com.health.model.Version; import com.health.repository.QueueManagementRepository; @@ -55,6 +56,7 @@ import com.health.service.QueueManagementService; import com.health.service.ResearchPaperService; import com.health.service.TopicCategoryMappingService; +import com.health.service.TrainingResourceService; import com.health.service.TutorialService; import com.health.utility.CommonData; import com.health.utility.ServiceUtility; @@ -79,6 +81,9 @@ public class TaskProcessingService { @Autowired private ThreadPoolTaskExecutor taskExecutor; + @Autowired + private TrainingResourceService trainingResourceService; + @Autowired private QueueManagementService queueService; @@ -962,4 +967,51 @@ public void stop() { logger.info("stopping QueueProcessor thread"); taskExecutor.shutdown(); } + + private String generateUniqueTokenForTrainingResource() { + + final int MAX_ATTEMPTS = 10; + + for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { + + String token = ServiceUtility.generateToken(); + + if (!trainingResourceService.existsByPdfTokenOrDocTokenOrExcelTokenOrImgToken(token, token, token, token)) { + return token; + } + } + + throw new IllegalStateException("Token not generated after " + MAX_ATTEMPTS + " attempts"); + } + + public void addTokenInTrainingResource() { + + List trList = trainingResourceService.findAll(); + + for (TrainingResource temp : trList) { + + if ((temp.getPdfToken() == null || temp.getPdfToken().isEmpty()) + && (temp.getPdfPath() != null && !temp.getPdfPath().isEmpty())) { + temp.setPdfToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getDocToken() == null || temp.getDocToken().isEmpty()) + && (temp.getDocPath() != null && !temp.getDocPath().isEmpty())) { + temp.setDocToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getExcelToken() == null || temp.getExcelToken().isEmpty()) + && (temp.getExcelPath() != null && !temp.getExcelPath().isEmpty())) { + temp.setExcelToken(generateUniqueTokenForTrainingResource()); + } + + if ((temp.getImgToken() == null || temp.getImgToken().isEmpty()) + && (temp.getImgPath() != null && !temp.getImgPath().isEmpty())) { + temp.setImgToken(generateUniqueTokenForTrainingResource()); + } + + trainingResourceService.save(temp); + } + } + } diff --git a/src/main/java/com/health/utility/CommonData.java b/src/main/java/com/health/utility/CommonData.java index 33a013fe..9927e659 100644 --- a/src/main/java/com/health/utility/CommonData.java +++ b/src/main/java/com/health/utility/CommonData.java @@ -1,5 +1,7 @@ package com.health.utility; +import java.time.LocalDate; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -165,6 +167,8 @@ public class CommonData { public static String uploadTrainingResource = "Media/Content/TrainingResource/"; + public static String uploadProjectReport = "Media/Content/ProjectReport/"; + public static String uploadPromoVideo = "Media/Content/PromoVideo/"; public static String uploadVersion = "Media/Content/Version/"; @@ -313,6 +317,10 @@ public class CommonData { public static final String PDF_OR_ZIP_OF_PDFS = "pdfOrZipOfPdfs"; public static final String Excel_OR_ZIP_OF_EXCELS = "excelOrZipOfexcels"; + public static final LocalDate IMPL_DATE_TRAINING_RESOURCE = LocalDate.of(2026, 3, 5); + + public static final String ALL_DISTRICTS = "All Districts"; + public static final String DOCUMENT_ID_TUTORIAL_TIMESCRIPT = "Tts"; public static final String DOCUMENT_ID_TUTORIAL_ORIGINAL_SCRIPT = "Tos"; public static final String DOCUMENT_ID_BROCHURE = "Bro"; diff --git a/src/main/java/com/health/utility/ServiceUtility.java b/src/main/java/com/health/utility/ServiceUtility.java index 35545363..5a0b4866 100644 --- a/src/main/java/com/health/utility/ServiceUtility.java +++ b/src/main/java/com/health/utility/ServiceUtility.java @@ -18,12 +18,14 @@ import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; +import java.security.SecureRandom; import java.sql.Timestamp; import java.text.Normalizer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collections; import java.util.Comparator; import java.util.Date; @@ -74,9 +76,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.health.model.ProjectReport; import com.health.model.TrainingResource; import com.health.model.User; import com.health.repository.UserRepository; +import com.health.service.TrainingResourceService; import com.health.threadpool.TimeoutOutputStream; /** @@ -100,6 +104,9 @@ public class ServiceUtility { @Autowired private JavaMailSender mailSender; + @Autowired + private TrainingResourceService trainingResourceService; + public static Timestamp getCurrentTime() { // Current Date Date date = new Date(); @@ -1261,6 +1268,27 @@ public static String copyFileAndGetRelativePath(File sourceFile, String destinat return resultantPath; } + public static String generateToken() { + byte[] bytes = new byte[8]; + new SecureRandom().nextBytes(bytes); + + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes).substring(0, 10); + } + + public static boolean hasAnyProjectReportFile(ProjectReport pr) { + boolean hasData = true; + if ((pr.getPdfPath() == null || pr.getPdfPath().isEmpty()) + && (pr.getDocPath() == null || pr.getDocPath().isEmpty()) + && (pr.getExcelPath() == null || pr.getExcelPath().isEmpty()) + && (pr.getImgPath() == null || pr.getImgPath().isEmpty())) { + + hasData = false; + } + + return hasData; + + } + public static boolean hasAnyResourceFile(TrainingResource tr) { boolean hasData = true; if ((tr.getPdfPath() == null || tr.getPdfPath().isEmpty()) diff --git a/src/main/resources/static/js/ajaxSupport.js b/src/main/resources/static/js/ajaxSupport.js index 6679e6e0..16e9cf51 100644 --- a/src/main/resources/static/js/ajaxSupport.js +++ b/src/main/resources/static/js/ajaxSupport.js @@ -3356,6 +3356,174 @@ $(document).ready(function () { /******************************** Training Resource End ****************************************/ + + +/******************************** Project Report Start *****************************/ + + $("#stateIdPR").change(function() { + + var stateId = $(this).find(":selected").val(); + var allDisId = $("#allDistrict").val(); + + + $.ajax({ + type : "GET", + url : projectPath+"loadDistrictByStateforPR", + data : { + "stateId" : stateId, + "allDisId" : allDisId, + + + }, + contentType : "application/json", + success : function(result) { + + var html = ''; + html += ''; + var len = result.length; + $.each(result , function( key, value ) { + html += ''; + }) + + $(".district-select-pr").prop('disabled',false); + $('.district-select-pr').html(html); + + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + + } + + }); + + }); + +$('.enableProjetcReport').click(function() { + + var test_id=$(this).attr('value'); + + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableProjectReport", + data : { + "projectReportId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + $('#'+test_id).addClass('fas fa-times-circle'); + $('#'+test_id).removeClass('fas fa-check-circle'); + $('#'+test_id).css({"color": "red"}); + $('#Success').css({"display": "block"}); + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + $('.disableProjetcReport').click(function() { + + var test_id=$(this).attr('value'); + + $('#Success').css({"display": "none"}); + $('#Failure').css({"display": "none"}); + + $.ajax({ + type : "GET", + url : projectPath+"enableDisableProjectReport", + data : { + "projectReportId" : test_id + }, + contentType : "application/json", + success : function(data) { + if(data){ + + $('#'+test_id).addClass('fas fa-check-circle'); + $('#'+test_id).removeClass('fas fa-times-circle'); + $('#'+test_id).css({"color": "green"}); + $('#Success').css({"display": "block"}); + + + }else{ + $('#Failure').css({"display": "block"}); + } + }, + + error : function(err) { + console.log("not working. ERROR: "+ JSON.stringify(err)); + } + + }); + + }); + + + + $(".deleteProjectReport-btn").click(function(){ + var row = $(this).closest("tr"); + var projectReportId = $(this).data("projectreportid"); + var stateName = $(this).data("statename"); + var districtName = $(this).data("districtname"); + var fileName = $(this).data("filename"); + var fileType = $(this).data("filetype"); + + + Swal.fire({ + title: "Are you sure?", + html: "Do you want to delete this Project Report?

" + + "State: " + stateName + "
" + + "District: " + districtName + "
" + + "file Type: " + fileType + "
" + + "file Name: " + fileName, + + icon: "warning", + showCancelButton: true, + confirmButtonText: "Yes", + cancelButtonText: "No", + dangerMode: true + }).then((result) => { + if (result.isConfirmed) { + $.ajax({ + url: "/delete-projectReport/", + data: { + + + "projectReportId": projectReportId, + "fileType": fileType + }, + type: "DELETE", + success: function(result) { + Swal.fire("Deleted!", "Deleted successfully!", "success"); + $("#" + fileType + projectReportId).text("Deleted"); + }, + error: function(err) { + Swal.fire("Error!", "Error in deleting!", "error"); + } + }); + } + }); +}); + + + + +/******************************** Project Report End *******************************/ /***************** changes made by om prakash *********************************************/ diff --git a/src/main/resources/templates/addProjectReport.html b/src/main/resources/templates/addProjectReport.html new file mode 100644 index 00000000..8fbfd476 --- /dev/null +++ b/src/main/resources/templates/addProjectReport.html @@ -0,0 +1,424 @@ + + + + + + +
+
+
+
+
+
+
+
+ + +
+ +
+
+
+
+

Add Project Report

+
+
+
+
+ +
+
+ +
+ +
+ + +
+ + + + + + + + + +
+ +
+ +
+
+ +
+ + +
+ +
+ + + +
+ +
+ + + + (.jpg or .png or .pdf or .docx or .odt or .xlsx or .csv or .zip Only) + Max file size : 700 MB + +
+ +
+
+
+ + + + + + +
+
+
+ + + + +
+ + +
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Date AddedStateDistrictEnable/DisablePdf FileDoc FileExcel FileImage File
+ +
+ +
+
+ +
+ +
+
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Pdf available +
+
+
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Doc available +
+
+ +
+ +
+
+ + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Excel available +
+
+ + +
+
+
+ + + +
+ + View + +   + + Edit + +   + +
+ + +
+ No Image available +
+
+ + +
+
+ + + + + +
+ + + +
+ +
+ + +
+ + +
+ + + + + + + diff --git a/src/main/resources/templates/common/sidebar.html b/src/main/resources/templates/common/sidebar.html index c3afe394..d97788a4 100644 --- a/src/main/resources/templates/common/sidebar.html +++ b/src/main/resources/templates/common/sidebar.html @@ -307,7 +307,15 @@ + + @@ -440,12 +448,13 @@ - - +