diff --git a/pom.xml b/pom.xml index a0b8dcf6..707e18a2 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.1.0 + 3.8.0 war FLW-API @@ -252,6 +252,13 @@ 0.12.6 runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.6 + runtime + @@ -330,6 +337,32 @@ + + io.github.git-commit-id + git-commit-id-maven-plugin + 9.0.2 + + + get-the-git-infos + + revision + + initialize + + + + true + ${project.build.outputDirectory}/git.properties + + ^git.branch$ + ^git.commit.id.abbrev$ + ^git.build.version$ + ^git.build.time$ + + false + false + + org.apache.maven.plugins maven-antrun-plugin @@ -413,4 +446,4 @@ - \ No newline at end of file + diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index e069bede..b5aa3f02 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -16,8 +16,7 @@ secondary.datasource.password=@env.DATABASE_IDENTITY_PASSWORD@ secondary.datasource.url=@env.DATABASE_IDENTITY_URL@ secondary.datasource.driver-class-name=com.mysql.jdbc.Driver -springdoc.api-docs.enabled=@env.SWAGGER_DOC_ENABLED@ -springdoc.swagger-ui.enabled=@env.SWAGGER_DOC_ENABLED@ + #ELK logging file name logging.path=logs/ @@ -29,3 +28,12 @@ jwt.secret=@env.JWT_SECRET_KEY@ spring.redis.host=@env.REDIS_HOST@ cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ + +#### SMS Configuration +send-sms=@env.SEND_SMS@ +source-address=@env.SMS_CONSENT_SOURCE_ADDRESS@ +sms-username=@env.SMS_USERNAME@ +sms-password=@env.SMS_PASSWORD@ +send-message-url=@env.SMS_MESSAGE_URL@ + +#crash.logs.base.path=@env.CRASH_LOGS_PATH@ diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 0b04b964..befe0069 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -1,5 +1,5 @@ -fhir-url = ${FHIR_URL} -tm-url = ${TM_URL} +fhir-url = ${FHIR_API} +tm-url = ${TM_API} ##--------------------------------------------## Primary db------------------------------------------------------------------- @@ -15,8 +15,8 @@ secondary.datasource.password=${DATABASE_IDENTITY_PASSWORD} secondary.datasource.url=${DATABASE_IDENTITY_URL} secondary.datasource.driver-class-name=com.mysql.jdbc.Driver -springdoc.api-docs.enabled=false -springdoc.swagger-ui.enabled=false + + #ELK logging file name logging.path=logs/ @@ -25,4 +25,17 @@ logging.file.name=${FLW_API_LOGGING_FILE_NAME} jwt.secret=${JWT_SECRET_KEY} # Redis Config -spring.redis.host=${REDIS_HOST} \ No newline at end of file +spring.redis.host=${REDIS_HOST} + +#### SMS Configuration +send-sms=${SEND_SMS} +source-address=${SMS_CONSENT_SOURCE_ADDRESS} +sms-username=${SMS_USERNAME} +sms-password=${SMS_PASSWORD} + +send-message-url=${SMS_MESSAGE_URL} + +#crash.logs.base.path=${CRASH_LOGS_PATH} + + + diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index da750988..51873ab6 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -30,3 +30,15 @@ jwt.secret=my-32-character-ultra-secure-and-ultra-long-secret spring.redis.host=localhost cors.allowed-origins=http://localhost:* + +source-address= +sms-username= +sms-password= +send-message-url= + +crash.logs.base.path= + + + + + diff --git a/src/main/environment/common_local.properties b/src/main/environment/common_local.properties index 0d05ae5f..6e5bdd00 100644 --- a/src/main/environment/common_local.properties +++ b/src/main/environment/common_local.properties @@ -1,29 +1,45 @@ -server.port=8081 -# FHIR Config -fhir-url=http://localhost:8093/ - - # TM Config -tm-url=http://localhost:8089/ -##--------------------------------------------## Primary db------------------------------------------------------------------- - -spring.datasource.url=jdbc:mysql://localhost:3306/db_iemr -spring.datasource.username=root -spring.datasource.password=1234 -spring.datasource.driver-class-name=com.mysql.jdbc.Driver - -##--------------------------------------------## Secondary db------------------------------------------------------------------- - -secondary.datasource.url=jdbc:mysql://localhost:3306/db_identity -secondary.datasource.username=root -secondary.datasource.password=1234 -secondary.datasource.driver-class-name=com.mysql.jdbc.Driver - -springdoc.api-docs.enabled=true -springdoc.swagger-ui.enabled=true - -logging.path=logs/ -logging.file.name=logs/flw-api.log - -jwt.secret=my-32-character-ultra-secure-and-ultra-long-secret - -cors.allowed-origins=http://localhost:4208 \ No newline at end of file +spring.main.banner-mode=off +spring.data.jpa.repositories.enabled=true +#spring.jpa.hibernate.ddl-auto=none + +# Naming strategies +spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl +spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + +# The SQL dialect makes Hibernate generate better SQL for the chosen database +spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect + +#Below lines are added for security reasons + +spring.session.store-type=redis +spring.redis.password= +spring.redis.port=6379 + +## Below values are needed for extending the expiry time and extend expiry time. +iemr.extend.expiry.time=true +iemr.session.expiry.time=7200 +enableIPValidation=false + +#logging.pattern.level=DEBUG +logging.level.root=INFO +logging.level.org.springframework.web=INFO +logging.level.org.hibernate=INFO +logging.level.com.iemr=DEBUG +logging.level.org.springframework=INFO + +spring.datasource.tomcat.initial-size=5 +spring.datasource.tomcat.max-idle=15 +spring.datasource.tomcat.max-active=30 +spring.datasource.tomcat.min-idle=5 +spring.datasource.tomcat.min-evictable-idle-time-millis=15000 +spring.datasource.tomcat.remove-abandoned=true +spring.datasource.tomcat.logAbandoned=true +spring.datasource.continue-on-error=true +spring.datasource.tomcat.remove-abandoned-timeout=600 +door-to-door-page-size=10 + +#Get-HRP-Status +get-HRP-Status=ANC/getHRPStatus + +#Get Beneficiary ABHA +getHealthID=healthID/getBenhealthID diff --git a/src/main/java/com/iemr/flw/FlwApplication.java b/src/main/java/com/iemr/flw/FlwApplication.java index fac27988..23fc5352 100644 --- a/src/main/java/com/iemr/flw/FlwApplication.java +++ b/src/main/java/com/iemr/flw/FlwApplication.java @@ -1,21 +1,27 @@ package com.iemr.flw; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.utils.FLWApplBeans; +import jakarta.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @ComponentScan("com.iemr.flw.*") @EntityScan(basePackages = {"com.iemr.flw.domain.identity", "com.iemr.flw.domain.iemr"}) +@EnableScheduling public class FlwApplication extends SpringBootServletInitializer { public static void main(String[] args) { + + SpringApplication.run(applicationClass, args); } @@ -31,4 +37,5 @@ public FLWApplBeans instantiateBeans(){ return new FLWApplBeans(); } + } diff --git a/src/main/java/com/iemr/flw/controller/AdolescentHealthController.java b/src/main/java/com/iemr/flw/controller/AdolescentHealthController.java new file mode 100644 index 00000000..11cc5e57 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AdolescentHealthController.java @@ -0,0 +1,76 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.AdolescentHealthDTO; +import com.iemr.flw.service.AdolescentHealthService; +import com.iemr.flw.utils.response.OutputResponse; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@RestController +@RequestMapping(value = "/adolescentHealth", headers = "Authorization") +public class AdolescentHealthController { + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AdolescentHealthController.class); + + @Autowired + private AdolescentHealthService adolescentHealthService; + + @RequestMapping(value = "/saveAll", method = RequestMethod.POST, headers = "Authorization") + public ResponseEntity> saveAdolescentHealth(@RequestBody AdolescentHealthDTO adolescentHealthDTO) { + Map response = new HashMap<>(); + + try { + if (adolescentHealthDTO.getAdolescentHealths().size() != 0) { + String result = adolescentHealthService.saveAll(adolescentHealthDTO); + if (result != null) { + response.put("statusCode",200); + response.put("message",result); + + } + + } else { + response.put("statusCode", 500); + response.put("error", "Invalid/NULL request obj"); + } + } catch (Exception e) { + logger.error("Error in saving adolescent health data : " + e); + response.put("statusCode",500); + response.put("error","Error in saving adolescent health data : " + e); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "/getAll",method = RequestMethod.POST, headers = "Authorization") + public ResponseEntity> getAllAdolescentHealth(@RequestBody GetBenRequestHandler getBenRequestHandler) { + Map response = new HashMap<>(); + try { + List resultList = adolescentHealthService.getAllAdolescentHealth(getBenRequestHandler); + + if (resultList != null && !resultList.isEmpty()) { + response.put("statusCode",200); + response.put("data", resultList); + } else { + response.put("statusCode", 500); + response.put("error", "Invalid/NULL request obj"); + } + } catch (Exception e) { + logger.error("Error in get data : " + e); + response.put("statusCode",500); + response.put("error","Error in get data : " + e); + + } + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/com/iemr/flw/controller/AshaProfileController.java b/src/main/java/com/iemr/flw/controller/AshaProfileController.java new file mode 100644 index 00000000..1bda4499 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AshaProfileController.java @@ -0,0 +1,119 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.AshaWorker; +import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.dto.iemr.UserServiceRoleDTO; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.service.AshaProfileService; +import com.iemr.flw.service.EmployeeMasterInter; +import com.iemr.flw.service.UserService; +import io.lettuce.core.dynamic.annotation.Param; +import com.iemr.flw.utils.JwtUtil; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; + +import com.iemr.flw.utils.JwtAuthenticationUtil; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import io.jsonwebtoken.Claims; +import io.swagger.v3.oas.annotations.Operation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +@RestController +@RequestMapping(value = "/asha", produces = "application/json") +public class AshaProfileController { + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + @Autowired + AshaProfileService ashaProfileService; + private Map response = new HashMap<>(); + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + + private EmployeeMasterInter employeeMasterInter; + + @RequestMapping(value = "editProfile", method = {RequestMethod.POST}, produces = { + "application/json"}, consumes = "application/json") + + public ResponseEntity> editEmployee(@RequestBody AshaWorker editEmployee) { + + try { + System.out.println(editEmployee.toString()); + + AshaWorker ashaWorker = ashaProfileService.saveEditData(editEmployee); + response.put("data", ashaWorker); + response.put("statusCode", 200); + response.put("status", "Success"); + + } catch (Exception e) { + logger.error("Unexpected error:", e); + ResponseEntity.status(500).body(e.getMessage()); + + } + + return ResponseEntity.ok().body(response); + + } + + @RequestMapping(value = "getProfile", method = RequestMethod.GET) + public ResponseEntity> getProfile(HttpServletRequest request, @Param("employeeId") Integer employeeId) { + Map response = new HashMap<>(); + + try { + String jwtFromHeader = request.getHeader("JwtToken"); + + // Validate JWT header presence +// if (jwtFromHeader == null || jwtFromHeader.trim().isEmpty()) { +// response.put("statusCode", 401); +// response.put("status", "Unauthorized"); +// response.put("errorMessage", "JWT token is missing"); +// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response); +// } + + // Extract and validate user ID from JWT + // int userId = jwtUtil.extractUserId(jwtFromHeader); // Make sure this returns 0 or throws for invalid token + + if (employeeId == 0) { + response.put("statusCode", 401); + response.put("status", "Unauthorized"); + response.put("errorMessage", "Invalid JWT token"); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response); + } + + // Business logic + AshaWorker ashaWorker = ashaProfileService.getProfileData(employeeId); + logger.info("Asha Profile"+ashaWorker); + + response.put("statusCode", 200); + response.put("status", "Success"); + response.put("data", ashaWorker); + + if (ashaWorker == null) { + response.put("errorMessage", "Asha profile not found"); + } + + return ResponseEntity.ok().body(response); + + } catch (Exception e) { + logger.error("Unexpected error:", e); + response.put("statusCode", 500); + response.put("status", "Error"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } +} diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index dbcbc7cd..d7921ff0 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -1,18 +1,32 @@ package com.iemr.flw.controller; import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.EyeCheckupRequestDTO; +import com.iemr.flw.dto.iemr.IFAFormSubmissionRequest; +import com.iemr.flw.dto.iemr.MdaFormSubmissionRequest; +import com.iemr.flw.dto.iemr.SAMResponseDTO; +import com.iemr.flw.dto.iemr.SamDTO; import com.iemr.flw.service.BeneficiaryService; +import com.iemr.flw.service.IFAFormSubmissionService; +import com.iemr.flw.service.impl.MdaFormSubmissionService; +import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.sql.Timestamp; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; @RestController -@RequestMapping(value = "/beneficiary", headers = "Authorization", consumes = "application/json", produces = "application/json") +@RequestMapping(value = "/beneficiary", consumes = "application/json") public class BeneficiaryController { private final org.slf4j.Logger logger = LoggerFactory.getLogger(BeneficiaryController.class); @@ -20,12 +34,20 @@ public class BeneficiaryController { @Autowired BeneficiaryService beneficiaryService; + @Autowired + private IFAFormSubmissionService ifaFormSubmissionService; + + @Autowired + private MdaFormSubmissionService mdaFormSubmissionService; + @RequestMapping(value = "/getBeneficiaryData", method = RequestMethod.POST) @Operation(summary = "get beneficiary data for given user ") public String getBeneficiaryDataByAsha(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String authorization) { + @RequestHeader(value = "Authorization") String authorization) { OutputResponse response = new OutputResponse(); + try { + if (requestDTO != null) { logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); @@ -43,4 +65,91 @@ public String getBeneficiaryDataByAsha(@RequestBody GetBenRequestHandler request return response.toString(); } + @RequestMapping(value = {"/eye_surgery/saveAll"}, method = RequestMethod.POST) + public ResponseEntity saveEyeSurgery(@RequestBody List eyeCheckupRequestDTOS,@RequestHeader(value = "JwtToken") String token) { + Map response = new LinkedHashMap<>(); + logger.info("Eye Checkup Save Request: {}", eyeCheckupRequestDTOS); + + try { + if (eyeCheckupRequestDTOS == null || eyeCheckupRequestDTOS.isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Request body cannot be empty"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + String responseObject = beneficiaryService.saveEyeCheckupVsit(eyeCheckupRequestDTOS,token); + + if (responseObject != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save records"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + } catch (Exception e) { + logger.error("Error saving eye checkup visit:", e); + response.put("statusCode", 5000); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + + @RequestMapping(value = {"/eye_surgery/getAll"}, method = RequestMethod.POST) + public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler request,@RequestHeader(value = "JwtToken") String token) { + Map response = new LinkedHashMap<>(); + logger.info("Eye Checkup Get Request: {}", request); + + try { + List responseObject = beneficiaryService.getEyeCheckUpVisit(request,token); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", 5000); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error fetching eye checkup visit:", e); + response.put("statusCode", 5000); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + @RequestMapping(value = "/ifa/saveAll",method = RequestMethod.POST) + public ResponseEntity saveFormData(@RequestBody List requests) { + String message = ifaFormSubmissionService.saveFormData(requests); + return ResponseEntity.ok(Map.of("success", true, "message", message)); + } + + @RequestMapping(value = "ifa/getAll",method = RequestMethod.POST) + public ResponseEntity getFormData(@RequestBody GetBenRequestHandler getBenRequestHandler) { + var data = ifaFormSubmissionService.getFormData(getBenRequestHandler); + return ResponseEntity.ok(Map.of("success", true, "message", "Data fetched successfully", "data", data)); + } + + @RequestMapping(value = "/mda/saveAll", method = RequestMethod.POST) + public ResponseEntity saveFormData(@RequestBody List requests, + @RequestHeader(value = "Authorization") String authorization) { + String message = mdaFormSubmissionService.saveFormData(requests); + return ResponseEntity.ok(Map.of("success", true, "message", message)); + } + + @RequestMapping(value = "/mda/getAll", method = RequestMethod.POST) + public ResponseEntity getFormDataByCreatedBy(@RequestBody Map request, + @RequestHeader(value = "Authorization") String authorization) { + String userName = request.get("userName") ; + var data = mdaFormSubmissionService.getFormDataByUserName(userName); + return ResponseEntity.ok(Map.of("success", true, "message", "Data fetched successfully", "data", data)); + } + } diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java new file mode 100644 index 00000000..f5f13d69 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -0,0 +1,360 @@ +package com.iemr.flw.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.domain.iemr.FilariasisCampaign; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.service.CampaignService; +import com.iemr.flw.utils.exception.IEMRException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.util.*; + +@RestController +@RequestMapping(value = "/campaign") +public class CampaignController { + private final Logger logger = LoggerFactory.getLogger(CampaignController.class); + + @Autowired + private CampaignService campaignService; + + @PostMapping("/ors/distribution/saveAll") + public ResponseEntity> saveOrsDistribution( + @RequestPart("formDataJson") String fields, + @RequestHeader("jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + + // Validate input + if (fields == null || fields.trim().isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Form data is required"); + return ResponseEntity.badRequest().body(response); + } + + // Parse JSON to DTO + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + OrsCampaignDTO requestDTO = objectMapper.readValue(fields, OrsCampaignDTO.class); + + // Validate fields + if (requestDTO.getFields() == null) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Campaign fields are required"); + return ResponseEntity.badRequest().body(response); + } + + logger.info("Parsed DTO - Start Date: {}, End Date: {}, Families: {}, Photos: {}", + requestDTO.getFields().getStartDate(), + requestDTO.getFields().getEndDate(), + requestDTO.getFields().getNumberOfFamilies(), + requestDTO.getFields().getCampaignPhotos() + ); + + // Create DTO + OrsCampaignDTO campaignDTO = new OrsCampaignDTO(); + campaignDTO.setFields(requestDTO.getFields()); + + List orsCampaignDTOList = Collections.singletonList(campaignDTO); + + // Save to database + List result = campaignService.saveOrsCampaign(orsCampaignDTOList, token); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "Campaign saved successfully"); + response.put("data", result); + return ResponseEntity.status(HttpStatus.OK).body(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save campaign"); + return ResponseEntity.badRequest().body(response); + } + + } catch (JsonProcessingException e) { + logger.error("JSON parsing error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Invalid JSON format"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (IEMRException e) { + logger.error("Business logic error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (Exception e) { + logger.error("Error saving ORS distribution: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "Internal server error occurred"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = "ors/distribution/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllOrsDistribution(@RequestHeader(value = "jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + List result = campaignService.getOrsCampaign(token); + + + if (result != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", result); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error save ors distribution :", e.getMessage()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @PostMapping("/polio/campaign/saveAll") + public ResponseEntity> savePolioCampaign( + @RequestPart("formDataJson") String fields, + @RequestHeader("jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + logger.info("Received polio campaign data"); + + // Validate input + if (fields == null || fields.trim().isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Form data is required"); + return ResponseEntity.badRequest().body(response); + } + + // Parse JSON to DTO + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + PolioCampaignDTO requestDTO = objectMapper.readValue(fields, PolioCampaignDTO.class); + + // Validate fields + if (requestDTO.getFields() == null) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Campaign fields are required"); + return ResponseEntity.badRequest().body(response); + } + + logger.info("Parsed DTO - Start Date: {}, End Date: {}, Families: {}, Individuals: {}, Photos: {}", + requestDTO.getFields().getStartDate(), + requestDTO.getFields().getEndDate(), + requestDTO.getFields().getNumberOfChildren(), + + requestDTO.getFields().getCampaignPhotos() + ); + + // Create DTO + PolioCampaignDTO campaignDTO = new PolioCampaignDTO(); + campaignDTO.setFields(requestDTO.getFields()); + + List polioCampaignDTOList = Collections.singletonList(campaignDTO); + + // Save to database + List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "polio campaign saved successfully"); + response.put("data", result); + return ResponseEntity.status(HttpStatus.OK).body(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save Polio campaign"); + return ResponseEntity.badRequest().body(response); + } + + } catch (JsonProcessingException e) { + logger.error("JSON parsing error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Invalid JSON format"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (IEMRException e) { + logger.error("Business logic error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (Exception e) { + logger.error("Error saving filariasis campaign: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "Internal server error occurred"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = "polio/campaign/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllPolioCampaign(@RequestHeader(value = "jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + List result = campaignService.getPolioCampaign(token); + + + if (result != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", result); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error save ors distribution :", e.getMessage()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @PostMapping("/filariasis/campaign/saveAll") + public ResponseEntity> saveFilariasisCampaign( + @RequestPart("formDataJson") String fields, + @RequestHeader("jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + logger.info("Received polio campaign data"); + + // Validate input + if (fields == null || fields.trim().isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Form data is required"); + return ResponseEntity.badRequest().body(response); + } + + // Parse JSON to DTO + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + FilariasisCampaignDTO requestDTO = objectMapper.readValue(fields, FilariasisCampaignDTO.class); + + // Validate fields + if (requestDTO.getFields() == null) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Campaign fields are required"); + return ResponseEntity.badRequest().body(response); + } + + logger.info("Parsed DTO - Start Date: {}, End Date: {}, Families: {}, Individuals: {}, Photos: {}", + requestDTO.getFields().getStartDate(), + requestDTO.getFields().getEndDate(), + requestDTO.getFields().getNumberOfIndividuals(), + requestDTO.getFields().getNumberOfIndividuals(), + + requestDTO.getFields().getMdaPhotos() + ); + + // Create DTO + FilariasisCampaignDTO campaignDTO = new FilariasisCampaignDTO(); + campaignDTO.setFields(requestDTO.getFields()); + + List filariasisCampaignDTOS = Collections.singletonList(campaignDTO); + + + // Save to database + List result = campaignService.saveFilariasisCampaign(filariasisCampaignDTOS, token); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "filariasis campaign saved successfully"); + response.put("data", result); + return ResponseEntity.status(HttpStatus.OK).body(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save filariasis campaign"); + return ResponseEntity.badRequest().body(response); + } + + } catch (JsonProcessingException e) { + logger.error("JSON parsing error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Invalid JSON format"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (IEMRException e) { + logger.error("Business logic error: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", e.getMessage()); + return ResponseEntity.badRequest().body(response); + + } catch (Exception e) { + logger.error("Error saving filariasis campaign: {}", e.getMessage(), e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "Internal server error occurred"); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = "filariasis/campaign/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllFilariasisCampaign(@RequestHeader(value = "jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + List result = campaignService.getAllFilariasisCampaign(token); + + + if (result != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", result); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error save ors distribution :", e.getMessage()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } +} diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 33d02dcf..36da3ba7 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -1,7 +1,12 @@ package com.iemr.flw.controller; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.iemr.HbncVisit; +import com.iemr.flw.domain.iemr.IfaDistribution; +import com.iemr.flw.domain.iemr.SamVisitResponseDTO; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.service.ChildCareService; @@ -9,16 +14,22 @@ import io.swagger.v3.oas.annotations.Operation; +import jakarta.mail.Multipart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.sql.Timestamp; +import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; @RestController -@RequestMapping(value = "/child-care", headers = "Authorization", consumes = "application/json", produces = "application/json") +@RequestMapping(value = "/child-care", produces = "application/json") public class ChildCareController { private final Logger logger = LoggerFactory.getLogger(DeathReportsController.class); @@ -27,11 +38,18 @@ public class ChildCareController { private ChildCareService childCareService; @Operation(summary = "save HBYC details") - @RequestMapping(value = { "/hbyc/saveAll" }, method = { RequestMethod.POST }) - public String saveHbycRecords(@RequestBody List hbycDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) + public String saveHbycRecords(@RequestBody List hbycDTOs, + @RequestHeader(value = "JwtToken") String token) { + ObjectMapper mapper = new ObjectMapper(); + mapper.enable(SerializationFeature.INDENT_OUTPUT); // Pretty print + + // Request log + OutputResponse response = new OutputResponse(); + try { + logger.info("Saving All HBYC Details"); if (hbycDTOs != null) { String s = childCareService.registerHBYC(hbycDTOs); @@ -49,14 +67,13 @@ public String saveHbycRecords(@RequestBody List hbycDTOs, } @Operation(summary = "get List of HBYC details") - @RequestMapping(value = { "/hbyc/getAll" }, method = { RequestMethod.POST }) - public String getHbycRecords(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestMapping(value = {"/hbycVisit/getAll"}, method = {RequestMethod.POST}) + public String getHbycRecords(@RequestBody GetBenRequestHandler requestDTO) { OutputResponse response = new OutputResponse(); try { logger.info("fetching All HBYC Details for user: " + requestDTO.getAshaId()); if (requestDTO != null) { - List result = childCareService.getHbycRecords(requestDTO); + List result = childCareService.getHbycRecords(requestDTO); Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); String s = gson.toJson(result); if (s != null) @@ -73,57 +90,76 @@ public String getHbycRecords(@RequestBody GetBenRequestHandler requestDTO, return response.toString(); } - @Operation(summary = "save hbnc visit details") - @RequestMapping(value = { "/hbncVisit/saveAll" }, method = { RequestMethod.POST }) + @PostMapping("/hbncVisit/saveAll") public String saveHBNCVisit(@RequestBody List hbncRequestDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); + try { - if (hbncRequestDTOs.size() != 0) { - logger.info("Saving HBNC visits with timestamp : " + new Timestamp(System.currentTimeMillis())); - String s = childCareService.saveHBNCDetails(hbncRequestDTOs); - if (s != null) - response.setResponse(s); + if (!hbncRequestDTOs.isEmpty()) { + logger.info("Saving HBNC details at: " + new Timestamp(System.currentTimeMillis())); + + String result = childCareService.saveHBNCDetails(hbncRequestDTOs); // <-- actual save + + if (result != null) + response.setResponse(result); else - response.setError(5000, "Saving hbnc data to db failed"); - } else - response.setError(5000, "Invalid/NULL request obj"); + response.setError(500, "Failed to save HBNC visit data."); + } else { + response.setError(400, "Empty request list."); + } } catch (Exception e) { - logger.error("Error in save HBNC visit details : " + e); - response.setError(5000, "Error in save HBNC visit details : " + e); + logger.error("Error saving HBNC visit: ", e); + response.setError(500, "Server error: " + e.getMessage()); } return response.toString(); } + @Operation(summary = "get hbnc visit details") - @RequestMapping(value = { "/hbncVisit/getAll" }, method = { RequestMethod.POST }) - public String getHBNCVisitDetails(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String Authorization) { - OutputResponse response = new OutputResponse(); + @RequestMapping(value = {"/hbncVisit/getAll"}, method = {RequestMethod.POST}) + public ResponseEntity>> getHBNCVisitDetails( + @RequestBody GetBenRequestHandler requestDTO) { + + StandardResponse> response = new StandardResponse<>(); + try { if (requestDTO != null) { - logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " - + requestDTO); - List result = childCareService.getHBNCDetails(requestDTO); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - String s = gson.toJson(result); - if (s != null) - response.setResponse(s); - else - response.setError(5000, "No record found"); - } else - response.setError(5000, "Invalid/NULL request obj"); + logger.info("Request: " + requestDTO); + + List data = childCareService.getHBNCDetails(requestDTO); + + response.setStatusCode(200); + response.setStatus("Success"); + response.setErrorMessage("Success"); + response.setData(data); + + return ResponseEntity.ok(response); + + } else { + response.setStatusCode(400); + response.setStatus("Failed"); + response.setErrorMessage("Invalid request object"); + response.setData(null); + return ResponseEntity.badRequest().body(response); + } } catch (Exception e) { - logger.error("Error in Hbnc visit get data : " + e); - response.setError(5000, "Error in Hbnc visit get data : " + e); + logger.error("Exception in fetching HBNC visits", e); + + response.setStatusCode(500); + response.setStatus("Failed"); + response.setErrorMessage("Internal Server Error: " + e.getMessage()); + response.setData(null); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } - return response.toString(); } + + @Operation(summary = "save child vaccination details") - @RequestMapping(value = { "/vaccination/saveAll" }, method = { RequestMethod.POST }) + @RequestMapping(value = {"/vaccination/saveAll"}, method = {RequestMethod.POST}) public String saveChildVaccinationDetails(@RequestBody List childVaccinationDTOS, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { if (childVaccinationDTOS.size() != 0) { @@ -144,9 +180,9 @@ public String saveChildVaccinationDetails(@RequestBody List } @Operation(summary = "get child vaccination details") - @RequestMapping(value = { "/vaccination/getAll" }, method = { RequestMethod.POST }) + @RequestMapping(value = {"/vaccination/getAll"}, method = {RequestMethod.POST}) public String getChildVaccinationDetails(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { if (requestDTO != null) { @@ -170,9 +206,9 @@ public String getChildVaccinationDetails(@RequestBody GetBenRequestHandler reque } @Operation(summary = "get child vaccination details") - @RequestMapping(value = { "/vaccine/getAll" }, method = { RequestMethod.GET }) + @RequestMapping(value = {"/vaccine/getAll"}, method = {RequestMethod.GET}) public String getChildVaccinationDetails(@RequestParam(value = "category") String category, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { logger.info("request object for getting all vaccines with timestamp : " @@ -191,4 +227,180 @@ public String getChildVaccinationDetails(@RequestParam(value = "category") Strin } return response.toString(); } + @RequestMapping(value = {"/sam/saveAll"}, method = RequestMethod.POST) + public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List samRequest) { + Map response = new LinkedHashMap<>(); + logger.info("SAM Request: {}", samRequest); + + try { + if (samRequest == null || samRequest.isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Request body cannot be empty"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + + String responseObject = childCareService.saveSamDetails(samRequest); + + if (responseObject != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save SAM details"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + } catch (Exception e) { + logger.error("Error saving SAM details:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = {"/sam/getAll"}, method = RequestMethod.POST) + public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenRequestHandler request) { + Map response = new LinkedHashMap<>(); + try { + List responseObject = childCareService.getSamVisitsByBeneficiary(request); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "No SAM records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error fetching SAM records:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = {"/ors/saveAll"}, method = RequestMethod.POST) + public ResponseEntity saveOrsDistribution(@RequestBody List orsDistributionDTOS) { + Map response = new LinkedHashMap<>(); + logger.info("ORS Request: {}", orsDistributionDTOS); + + try { + if (orsDistributionDTOS == null || orsDistributionDTOS.isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Request body cannot be empty"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + String responseObject = childCareService.saveOrsDistributionDetails(orsDistributionDTOS); + + if (responseObject != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save ORS details"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + } catch (Exception e) { + logger.error("Error saving ORS:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = {"/ors/getAll"}, method = RequestMethod.POST) + public ResponseEntity getAllOrDistribution(@RequestBody GetBenRequestHandler request) { + Map response = new LinkedHashMap<>(); + + try { + List responseObject = childCareService.getOrdDistrubtion(request); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("message", "No ORS records found"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + logger.error("Error fetching ORS records:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = {"/ifa/saveAll"}, method = RequestMethod.POST) + public ResponseEntity saveIfDistribution(@RequestBody List ifaDistributionDTOS) { + Map response = new LinkedHashMap<>(); + logger.info("IFA Request: {}", ifaDistributionDTOS); + + try { + if (ifaDistributionDTOS == null || ifaDistributionDTOS.isEmpty()) { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Request body cannot be empty"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + List responseObject = childCareService.saveAllIfa(ifaDistributionDTOS); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "IFA saved successfully"); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Failed to save IFA details"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + } catch (Exception e) { + logger.error("Error saving IFA:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + + @RequestMapping(value = {"/ifa/getAll"}, method = RequestMethod.POST) + public ResponseEntity getIfaDistribution(@RequestBody GetBenRequestHandler request) { + Map response = new LinkedHashMap<>(); + + try { + List responseObject = childCareService.getByBeneficiaryId(request); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "No IFA records found"); + return ResponseEntity.status(HttpStatus.OK).body(response); + } + + } catch (Exception e) { + logger.error("Error fetching IFA records:", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + } diff --git a/src/main/java/com/iemr/flw/controller/CoupleController.java b/src/main/java/com/iemr/flw/controller/CoupleController.java index 883f850d..4a14da4e 100644 --- a/src/main/java/com/iemr/flw/controller/CoupleController.java +++ b/src/main/java/com/iemr/flw/controller/CoupleController.java @@ -6,11 +6,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -21,6 +18,7 @@ import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; +import org.springframework.web.multipart.MultipartFile; @RestController @RequestMapping(value = "/couple", headers = "Authorization") @@ -31,10 +29,40 @@ public class CoupleController { @Autowired private CoupleService coupleService; + private String kitPhoto1; + + private String kitPhoto2; + + @Operation(summary = "save eligible couple registration details") + @RequestMapping(value = { "/register/saveAll" }, method = { RequestMethod.POST },consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public String saveEligibleCouple(@RequestPart("data") List eligibleCoupleDTOs, + @RequestPart(value = "kitPhoto1", required = false) MultipartFile kitPhoto1, + @RequestPart(value = "kitPhoto2", required = false) MultipartFile kitPhoto2, + @RequestHeader(value = "Authorization") String Authorization) { + OutputResponse response = new OutputResponse(); + try { + logger.info("Saving All Eligible Couple Details"); + if (eligibleCoupleDTOs != null) { + String s = coupleService.registerEligibleCouple(eligibleCoupleDTOs,kitPhoto1,kitPhoto2); + if (s != null) + response.setResponse(s); + else + response.setError(5000, "No record found"); + } else + response.setError(5000, "Invalid/NULL request obj"); + } catch (Exception e) { + logger.error("Error in saving eligible couple registration details, " + e); + response.setError(5000, "Error in saving eligible couple registration details" + e); + } + return response.toString(); + } + + + @Operation(summary = "save eligible couple registration details") @RequestMapping(value = { "/register/saveAll" }, method = { RequestMethod.POST }) public String saveEligibleCouple(@RequestBody List eligibleCoupleDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { logger.info("Saving All Eligible Couple Details"); @@ -112,6 +140,7 @@ public String getEligibleCoupleTracking(@RequestBody GetBenRequestHandler reques .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format .create(); String s = gson.toJson(result); + logger.info("tracking data:"+s); if (s != null) response.setResponse(s); else diff --git a/src/main/java/com/iemr/flw/controller/CrashLogController.java b/src/main/java/com/iemr/flw/controller/CrashLogController.java new file mode 100644 index 00000000..335d7dbb --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/CrashLogController.java @@ -0,0 +1,63 @@ +package com.iemr.flw.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.dto.crashlogs.CrashLogRequest; +import com.iemr.flw.service.CrashLogService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.response.OutputResponse; + +@RestController +@RequestMapping(value = "/crash-logs", headers = "Authorization") +public class CrashLogController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private CrashLogService crashLogService; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private ObjectMapper objectMapper; + + @PostMapping(value = "/upload", consumes = "multipart/form-data") + public String uploadCrashLog( + @RequestHeader(value = "JwtToken") String jwtToken, // Changed from Authorization + @RequestParam("file") MultipartFile file, + @RequestParam("metadata") String metadataJson) { + + OutputResponse response = new OutputResponse(); + + try { + // No need to remove "Bearer " prefix - JwtToken header contains raw JWT + Integer userId = jwtUtil.extractUserId(jwtToken); + + // Parse metadata JSON + CrashLogRequest request = objectMapper.readValue(metadataJson, CrashLogRequest.class); + + // Save crash log file + String filePath = crashLogService.saveCrashLog(request, userId, file); + + // Build success response + response.setResponse("Crash log saved successfully. File path: " + filePath); + logger.info("Crash log uploaded successfully for userId: " + userId); + + } catch (Exception e) { + logger.error("Error uploading crash log: " + e.getMessage(), e); + response.setError(e); + } + + return response.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java new file mode 100644 index 00000000..816fb244 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -0,0 +1,372 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.service.DiseaseControlService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/disease",headers = "Authorization") +public class DiseaseControlController { + private final Logger logger = LoggerFactory.getLogger(DiseaseControlController.class); + + @Autowired + private DiseaseControlService diseaseControlService; + + + @RequestMapping(value = "malaria/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") + public ResponseEntity> saveMalaria(@RequestBody MalariaDTO malariaDTO) { + Map response = new HashMap<>(); + + try { + + logger.info("Malaria DTO: {}", new ObjectMapper().writeValueAsString(malariaDTO)); + if(malariaDTO!=null){ + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.saveMalaria(malariaDTO)); + }else { + response.put("message", "Invalid request"); + response.put("statusCode", 5000); + } + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "kalaAzar/saveAll", method = RequestMethod.POST,consumes = "application/json", produces = "application/json",headers = "Authorization") + public ResponseEntity> saveKalaAzar(@RequestBody KalaAzarDTO kalaAzarDTO) { + Map response = new HashMap<>(); + + try { + logger.info("KalaAzar DTO: {}", new ObjectMapper().writeValueAsString(kalaAzarDTO)); + if(kalaAzarDTO!=null){ + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.saveKalaAzar(kalaAzarDTO)); + }else { + response.put("message", "Invalid request"); + response.put("statusCode", 5000); + } + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "aesJe/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") + public ResponseEntity> saveAESJE(@RequestBody AesJeDTO aesJeDTO) { + Map response = new HashMap<>(); + + try { + if(aesJeDTO!=null){ + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.saveAES(aesJeDTO)); + }else { + response.put("message", "Invalid request"); + response.put("statusCode", 5000); + } + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "filaria/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") + public ResponseEntity> saveFilaria(@RequestBody FilariaDTO filariaDTO) { + Map response = new HashMap<>(); + + try { + if(filariaDTO!=null){ + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.saveFilaria(filariaDTO)); + }else { + response.put("message", "Invalid request"); + response.put("statusCode", 5000); + } + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "leprosy/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") + public ResponseEntity> saveLeprosy(@RequestBody LeprosyDTO leprosyDTO) { + Map response = new HashMap<>(); + try { + if(leprosyDTO!=null){ + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.saveLeprosy(leprosyDTO)); + }else { + response.put("message", "Invalid request"); + response.put("statusCode", 5000); + } + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + @RequestMapping(value = "leprosy/followUp/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json", headers = "Authorization") + public ResponseEntity> saveLeprosyFollowUP(@RequestBody List followUps) { + Map response = new HashMap<>(); + try { + if (followUps != null && !followUps.isEmpty()) { + for (LeprosyFollowUpDTO dto : followUps) { + diseaseControlService.saveLeprosyFollowUp(dto); + } + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("message", "All follow-ups saved successfully"); + } else { + response.put("message", "Invalid request - no follow-up data"); + response.put("statusCode", 5000); + } + } catch (Exception e) { + response.put("status", "Error: " + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + } + + + @RequestMapping(value = "leprosy/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllLeprosy( + @RequestBody Map request, + @RequestHeader(value = "Authorization") String authorization) { + + Map response = new HashMap<>(); + try { + String userName = request.get("userName"); + if (userName != null) { + List result = diseaseControlService.getAllLeprosyData(userName); + + if (result != null && !result.isEmpty()) { + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", result); // ← Put list directly, no gson.toJson() + } else { + response.put("message", "No record found"); + response.put("statusCode", 5000); + } + } else { + response.put("message", "Invalid request - userName required"); + response.put("statusCode", 5000); + } + } catch (Exception e) { + response.put("status", "Error: " + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); // ← Spring serializes the whole map + } + + @RequestMapping(value = "leprosy/followUp/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllLeprosyFollowUp( + @RequestBody Map request, + @RequestHeader(value = "Authorization") String authorization) { + + Map response = new HashMap<>(); + try { + String userName = request.get("userName"); + if (userName != null) { + List result = diseaseControlService.getAllLeprosyFollowUpData(userName); + + if (result != null && !result.isEmpty()) { + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", result); // ← Put list directly, no gson.toJson() + } else { + response.put("message", "No record found"); + response.put("statusCode", 5000); + } + } else { + response.put("message", "Invalid request - userName required"); + response.put("statusCode", 5000); + } + } catch (Exception e) { + response.put("status", "Error: " + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); // ← Spring serializes the whole map + } + + @RequestMapping(value = "getAllDisease", method = RequestMethod.POST, produces = "application/json", headers = "Authorization") + public ResponseEntity> getAllData( + @RequestBody GetDiseaseRequestHandler getDiseaseRequestHandler) { + Map response = new HashMap<>(); + try { + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", diseaseControlService.getAllScreeningData(getDiseaseRequestHandler)); + + } catch (Exception e) { + response.put("status", "Error" + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + } + + @RequestMapping(value = "mobilizationMosquitoNet/saveAll",method = RequestMethod.POST) + public ResponseEntity> saveMobilizationMosquitoNet(@RequestBody List mosquitoNetDTOS){ + + Map response = new LinkedHashMap<>(); + logger.info("Eye Checkup Get Request: {}", mosquitoNetDTOS); + + try { + List responseObject = diseaseControlService.saveMosquitoMobilizationNet(mosquitoNetDTOS); + + if (responseObject != null && !responseObject.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + } + + } catch (Exception e) { + logger.error("Error mobilizationMosquitoNet :", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } + + + @RequestMapping(value = "mobilizationMosquitoNet/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllMobilizationMosquitoNet(@RequestBody GetBenRequestHandler getBenRequestHandler) { + + Map response = new LinkedHashMap<>(); + + try { + List responseObject = diseaseControlService.getAllMosquitoMobilizationNet(getBenRequestHandler.getAshaId()); + + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", responseObject); + return ResponseEntity.ok(response); + + } catch (Exception e) { + logger.error("Error getAllMobilizationMosquitoNet :", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + @RequestMapping(value = "cdtfVisit/saveAll", method = RequestMethod.POST) + public ResponseEntity> saveVisit( + @RequestBody List requestList,@RequestHeader(value = "JwtToken") String token) { + + Map response = new LinkedHashMap<>(); + logger.info("Chronic Disease Visit Save Request: {}", requestList); + + try { + List savedList = + diseaseControlService.saveChronicDiseaseVisit(requestList,token); + + if (savedList != null && !savedList.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "Data saved successfully"); + response.put("data", savedList); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "No data saved"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + } catch (Exception e) { + logger.error("Error saving Chronic Disease Visit :", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + @RequestMapping(value = "cdtfVisit/getAll", method = RequestMethod.POST) + public ResponseEntity> getVisitDetails( + @RequestBody GetBenRequestHandler getBenRequestHandler) { + + Map response = new LinkedHashMap<>(); + + try { + List result = + diseaseControlService.getCdtfVisits(getBenRequestHandler); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("data", result); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + } + + } catch (Exception e) { + logger.error("Error fetching Chronic Disease Visit :", e); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/controller/GeneralOPDController.java b/src/main/java/com/iemr/flw/controller/GeneralOPDController.java new file mode 100644 index 00000000..c683a9be --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/GeneralOPDController.java @@ -0,0 +1,88 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* @@ -0,0 +1,212 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.GeneralOpdData; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.GeneralOpdDto; +import com.iemr.flw.service.BeneficiaryService; +import com.iemr.flw.service.GeneralOpdService; +import com.iemr.flw.utils.CookieUtil; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.response.OutputResponse; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +@RestController +@RequestMapping(value = "/generalOpd") +public class GeneralOPDController { + private final org.slf4j.Logger logger = LoggerFactory.getLogger(GeneralOPDController.class); + + @Autowired + private JwtUtil jwtUtil; + @Autowired + private GeneralOpdService generalOpdService; + + @RequestMapping(value = "getBeneficiaries", method = RequestMethod.POST) + @Operation(summary = "get beneficiary data for given user ") + public ResponseEntity> getBeneficiaryDataByAsha(@RequestBody GetBenRequestHandler requestDTO) { + Map response = new LinkedHashMap<>(); + try { + + Page pageResult = generalOpdService.getOutreachData(requestDTO.getVillageID(),requestDTO.getUserName()); + + // Response map + Map data = new HashMap<>(); + data.put("userId", requestDTO.getUserId()); + data.put("entries", pageResult.getContent()); + + response.put("data", data); + response.put("statusCode", 200); + response.put("errorMessage", "Success"); + response.put("status", "Success"); + + } catch (Exception e) { + logger.error("Error in get data : " + e); + response.put("statusCode", 5000); + response.put("message", "Error in get data : " + e); + } + return ResponseEntity.ok(response); + } + + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/controller/IRSRoundController.java b/src/main/java/com/iemr/flw/controller/IRSRoundController.java new file mode 100644 index 00000000..f138a0ef --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/IRSRoundController.java @@ -0,0 +1,89 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.IRSRound; +import com.iemr.flw.dto.iemr.IRSRoundDTO; +import com.iemr.flw.dto.iemr.IRSRoundListDTO; +import com.iemr.flw.service.IRSRoundService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.response.OutputResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.lang.reflect.Method; +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/irsRound", headers = "Authorization") + +public class IRSRoundController { + @Autowired + private IRSRoundService irsRoundService; + + @Autowired + private JwtUtil jwtUtil; + + @PostMapping(value = "/add") + public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto,@RequestHeader("jwtToken") String token) { + Map response = new LinkedHashMap<>(); + try { + if (dto.getRounds().size() != 0) { + if(token==null){ + response.put("statusCode", 401); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response) ; + } + List s = irsRoundService.addRounds(dto.getRounds(),jwtUtil.extractUserId(token),jwtUtil.extractUsername(token)); + if (s.size() != 0) { + Map data = new HashMap<>(); + data.put("entries", s); + response.put("data", data); + response.put("statusCode", 200); + response.put("message", "Success"); + return ResponseEntity.ok(response); + } else { + response.put("statusCode", 500); + response.put("errorMessage", "Invalid/NULL request obj"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } else + response.put("statusCode", 400); + response.put("errorMessage", "Invalid/NULL request obj"); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } catch (Exception e) { + response.put("statusCode", 500); + response.put("errorMessage", "Error in saving IRS round details: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } + + @GetMapping(value = "/list/{householdId}") + public ResponseEntity> getRounds(@PathVariable Long householdId) { + + Map response = new LinkedHashMap<>(); + + try { + Map data = new HashMap<>(); + data.put("entries", irsRoundService.getRounds(householdId)); + response.put("data", data); + response.put("statusCode", 200); + response.put("message", "Success"); + return ResponseEntity.ok(response); + + } catch (Exception e) { + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + + } + + } + + +} diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index bccccb46..c76d26ae 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -3,11 +3,14 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.IncentiveActivityDTO; import com.iemr.flw.dto.iemr.IncentiveRequestDTO; +import com.iemr.flw.dto.iemr.PendingActivityDTO; import com.iemr.flw.service.IncentiveService; +import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -17,18 +20,18 @@ import java.util.List; @RestController -@RequestMapping(value = "/incentive", headers = "Authorization", consumes = "application/json", produces = "application/json") +@RequestMapping(value = "/incentive", consumes = "application/json", produces = "application/json") public class IncentiveController { private final Logger logger = LoggerFactory.getLogger(IncentiveController.class); + @Autowired IncentiveService incentiveService; @Operation(summary = "save incentive master") - @RequestMapping(value = { "/masterData/saveAll" }, method = { RequestMethod.POST }) - public String saveIncentiveMasterData(@RequestBody List activityDTOS, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestMapping(value = {"/masterData/saveAll"}, method = {RequestMethod.POST}) + public String saveIncentiveMasterData(@RequestBody List activityDTOS, @RequestHeader(value = "Authorization") String authorization, HttpServletRequest request) { OutputResponse response = new OutputResponse(); try { logger.info("Saving All incentives"); @@ -48,16 +51,19 @@ public String saveIncentiveMasterData(@RequestBody List ac } @Operation(summary = "get incentive master") - @RequestMapping(value = { "/masterData/getAll" }, method = { RequestMethod.POST }) + @RequestMapping(value = {"/masterData/getAll"}, method = {RequestMethod.POST}) public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentiveRequestDTO, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { + logger.info("get All incentives"); // add logic for different state or district if (incentiveRequestDTO != null) { String s = incentiveService.getIncentiveMaster(incentiveRequestDTO); + logger.info("All incentives" + s); + if (s != null) response.setResponse(s); else @@ -71,10 +77,11 @@ public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentive return response.toString(); } + @Operation(summary = "get high risk assessment data of all beneficiaries registered with given user id") - @RequestMapping(value = { "/fetchUserData" }, method = { RequestMethod.POST }) + @RequestMapping(value = {"/fetchUserData"}, method = {RequestMethod.POST}) public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); try { @@ -82,6 +89,7 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); String s = incentiveService.getAllIncentivesByUserId(requestDTO); + logger.info("User Incentive:" + s); if (s != null) response.setResponse(s); else @@ -95,4 +103,29 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request return response.toString(); } + @RequestMapping(value = {"/update"}, method = RequestMethod.POST) + public String updateIncentive(@RequestBody PendingActivityDTO requestDTO) { + OutputResponse response = new OutputResponse(); + try { + + if (requestDTO != null) { + logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + + requestDTO); + String s = incentiveService.updateIncentive(requestDTO); + logger.info("User Incentive:" + s); + if (s != null) + response.setResponse(s); + else + response.setError(5000, "No record found"); + } else + response.setError(5000, "Invalid/NULL request obj"); + } catch (Exception e) { + logger.error("Error in high risk assessment data : " + e); + response.setError(5000, "Error in high risk assessment data : " + e); + } + return response.toString(); + + + } + } diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java new file mode 100644 index 00000000..49c2236b --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -0,0 +1,158 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.MaaMeeting; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.MaaMeetingListResponseDTO; +import com.iemr.flw.dto.iemr.MaaMeetingRequestDTO; +import com.iemr.flw.dto.iemr.MaaMeetingResponseDTO; +import com.iemr.flw.service.MaaMeetingService; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("maa-meetings") +public class MaaMeetingController { + + + private final MaaMeetingService service; + + public MaaMeetingController(MaaMeetingService service) { + this.service = service; + } + + @PostMapping(value = "/saveAll", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity saveMeeting( + + @RequestPart(value = "villageName", required = false) String villageName, + @RequestPart(value = "noOfPragnentWoment", required = false) String noOfPragnentWomen, + @RequestPart(value = "noOfLactingMother", required = false) String noOfLactingMother, + @RequestPart(value = "mitaninActivityCheckList", required = false) String mitaninActivityCheckList, + @RequestPart(value = "meetingDate") String meetingDate, + @RequestPart(value = "place", required = false) String place, + @RequestPart(value = "participants") String participants, + @RequestPart(value = "ashaId", required = false) String ashaId, + @RequestPart(value = "createdBy", required = false) String createdBy, + @RequestPart(value = "meetingImages", required = false) List meetingImages + ) { + try { + MaaMeetingRequestDTO dto = new MaaMeetingRequestDTO(); + + if (meetingDate != null && !meetingDate.isEmpty()) { + dto.setMeetingDate(LocalDate.parse(meetingDate)); + } + + dto.setPlace(place); + dto.setVillageName(villageName); + dto.setMitaninActivityCheckList(mitaninActivityCheckList); + dto.setCreatedBY(createdBy); + + if (participants != null && !participants.isEmpty()) { + dto.setParticipants(Integer.parseInt(participants)); + } + + if (ashaId != null && !ashaId.isEmpty()) { + dto.setAshaId(Integer.parseInt(ashaId)); + } + + if (noOfLactingMother != null && !noOfLactingMother.isEmpty()) { + dto.setNoOfLactingMother(Integer.parseInt(noOfLactingMother)); + } + + if (noOfPragnentWomen != null && !noOfPragnentWomen.isEmpty()) { + dto.setNoOfPragnentWomen(Integer.parseInt(noOfPragnentWomen)); + } + + if (meetingImages != null && !meetingImages.isEmpty()) { + dto.setMeetingImages(meetingImages.toArray(new MultipartFile[0])); + } + + service.saveMeeting(dto); + + return ResponseEntity.ok("Saved Successfully"); + + } catch (Exception e) { + e.printStackTrace(); + return ResponseEntity.badRequest().body(e.getMessage()); + } + } + + @PostMapping(value = "/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity updateMeeting( + @RequestPart("meetingDate") String meetingDate, + @RequestPart("place") String place, + @RequestPart("participants") String participants, + @RequestPart("ashaId") String ashaId, + @RequestPart("createdBy") String createdBy, + @RequestPart(value = "meetingImages", required = false) List meetingImages) { + try { + MaaMeetingRequestDTO dto = new MaaMeetingRequestDTO(); + if (meetingDate != null) { + dto.setMeetingDate(LocalDate.parse(meetingDate)); + + } + if (place != null) { + dto.setPlace(place); + + } + if (participants != null) { + dto.setParticipants(Integer.parseInt(participants)); + + } + if (ashaId != null) { + dto.setAshaId(Integer.parseInt(ashaId)); + + } + if (createdBy != null) { + dto.setCreatedBY(createdBy); + + } + if (meetingImages != null) { + dto.setMeetingImages(meetingImages != null ? meetingImages.toArray(new MultipartFile[0]) : null); + + } + if (dto != null) { + service.updateMeeting(dto); + + } + return ResponseEntity.ok("Saved Successfully"); + } catch (Exception e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + } + + + @PostMapping("/getAll") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Successfully fetched meetings", + content = @Content(mediaType = "application/json", + schema = @Schema(implementation = MaaMeetingListResponseDTO.class))), + @ApiResponse(responseCode = "500", description = "Internal Server Error") + }) + public ResponseEntity getMeetings(@RequestBody GetBenRequestHandler getBenRequestHandler) { + MaaMeetingListResponseDTO response = new MaaMeetingListResponseDTO(); + + try { + response.setData(service.getAllMeetings(getBenRequestHandler)); + response.setStatusCode(200); + response.setStatus("Success"); + return ResponseEntity.ok(response); + } catch (Exception e) { + response.setStatusCode(500); + response.setStatus("Something went wrong"); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } +} diff --git a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java new file mode 100644 index 00000000..c2b421d6 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java @@ -0,0 +1,98 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.controller; + +import com.iemr.flw.dto.iemr.GetDiseaseRequestHandler; +import com.iemr.flw.dto.iemr.MalariaFollowListUpDTO; +import com.iemr.flw.dto.iemr.MalariaFollowUpDTO; +import com.iemr.flw.service.MalariaFollowUpService; +import com.iemr.flw.utils.JwtUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/follow-up", headers = "Authorization") +public class MalariaFollowUpController { + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private MalariaFollowUpService followUpService; + + @RequestMapping(value = "save", method = RequestMethod.POST) + public ResponseEntity> save(@RequestBody MalariaFollowUpDTO dto,@RequestHeader(value = "JwtToken") String token) { + Map response = new HashMap<>(); + + try { + if(token!=null){ + + Boolean result = followUpService.saveFollowUp(dto,token); + if (result) { + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("message", "Follow-up saved successfully"); + } else { + response.put("status", "Failed"); + response.put("statusCode", 5000); + } + } + + } catch (Exception e) { + response.put("status", "Error: " + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + } + + @RequestMapping(value = "get", method = RequestMethod.POST) + public ResponseEntity> getFollowUpsByUserId(@RequestBody GetDiseaseRequestHandler getDiseaseRequestHandler,@RequestHeader(value = "JwtToken") String token) { + Map response = new HashMap<>(); + + try { + if(token!=null){ + List data = followUpService.getByUserId(jwtUtil.extractUserId(token)); + response.put("status", "Success"); + response.put("statusCode", 200); + response.put("data", data); + if (data.isEmpty()) { + response.put("message", "No records found"); + } + } + + } catch (Exception e) { + response.put("status", "Error: " + e.getMessage()); + response.put("statusCode", 5000); + } + return ResponseEntity.ok(response); + + + } +} diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 5c9621f6..e65eacda 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -8,13 +8,18 @@ import com.iemr.flw.service.DeliveryOutcomeService; import com.iemr.flw.service.InfantService; import com.iemr.flw.service.MaternalHealthService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; +import jakarta.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.sql.Timestamp; @@ -38,6 +43,9 @@ public class MaternalHealthController { @Autowired private ChildService childService; + @Autowired + private JwtUtil jwtUtil; + @Operation(summary = "save pregnant woman registration details") @RequestMapping(value = { "/pregnantWoman/saveAll" }, method = { RequestMethod.POST }) public String savePregnantWomanRegistrations(@RequestBody List pregnantWomanDTOs, @@ -84,6 +92,7 @@ public String getPregnantWomanList(@RequestBody GetBenRequestHandler requestDTO, response.setError(5000, "Error in pregnant woman get data : " + e); } return response.toString(); + } @Operation(summary = "save anc visit details") @@ -102,7 +111,8 @@ public String saveANCVisit(@RequestBody List ancVisitDTOs, } else response.setError(5000, "Invalid/NULL request obj"); } catch (Exception e) { - logger.error("Error in save ANC visit details : " + e); + logger.error("Error in save ANC visit details : ",e); + response.setError(5000, "Error in save ANC visit details : " + e); } return response.toString(); @@ -133,10 +143,73 @@ public String getANCVisitDetails(@RequestBody GetBenRequestHandler requestDTO, return response.toString(); } + @Operation(summary = "save anc visit question") + @RequestMapping(value = { "/ancVisit/counselling/saveAll" }, method = { RequestMethod.POST }) + public String saveANCVisitQuestion(@RequestBody List ancVisitQuestionsDTOS, + @RequestHeader(value = "JwtToken") String Authorization) { + OutputResponse response = new OutputResponse(); + try { + if (ancVisitQuestionsDTOS.size() != 0) { + + logger.info("Saving ANC visits with timestamp : " + new Timestamp(System.currentTimeMillis())); + String s = maternalHealthService.saveANCVisitQuestions(ancVisitQuestionsDTOS,Authorization); + if (s != null) + response.setResponse(s); + else + response.setError(500, "Saving anc data to db failed"); + } else + response.setError(500, "Invalid/NULL request obj"); + } catch (Exception e) { + logger.error("Error in save ANC visit details : ",e); + + response.setError(500, "Error in save ANC visit details : " + e); + } + return response.toString(); + } + + @Operation(summary = "get anc visit questions") + @RequestMapping(value = { "/ancVisit/counselling/getAll" }, method = { RequestMethod.POST }) + public ResponseEntity>> getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, + @RequestHeader(value = "JwtToken") String Authorization) { + StandardResponse> response = new StandardResponse<>(); + + try { + if (requestDTO != null) { + logger.info("Request: " + requestDTO); + + List result = maternalHealthService.getANCCounselling(requestDTO); + + response.setStatusCode(200); + response.setStatus("Success"); + response.setErrorMessage("Success"); + response.setData(result); + + return ResponseEntity.ok(response); + + } else { + response.setStatusCode(400); + response.setStatus("Failed"); + response.setErrorMessage("Invalid request object"); + response.setData(null); + return ResponseEntity.badRequest().body(response); + } + } catch (Exception e) { + logger.error("Exception in fetching HBNC visits", e); + + response.setStatusCode(500); + response.setStatus("Failed"); + response.setErrorMessage("Internal Server Error: " + e.getMessage()); + response.setData(null); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } + @Operation(summary = "save Delivery Outcome details") @RequestMapping(value = { "/deliveryOutcome/saveAll" }, method = { RequestMethod.POST }) public String saveDeliveryOutcome(@RequestBody List deliveryOutcomeDTOS, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "Authorization") String Authorization, HttpServletRequest request) throws IEMRException { + + OutputResponse response = new OutputResponse(); try { if (deliveryOutcomeDTOS.size() != 0) { @@ -153,6 +226,7 @@ public String saveDeliveryOutcome(@RequestBody List delivery response.setError(5000, "Error in save delivery outcome details : " + e); } return response.toString(); + } @Operation(summary = "get Delivery Outcome details") diff --git a/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java new file mode 100644 index 00000000..c501b405 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java @@ -0,0 +1,85 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.MicroBirthPlan; +import com.iemr.flw.dto.iemr.GetMicroPlanHandler; +import com.iemr.flw.dto.iemr.MicroBirthPlanDTO; +import com.iemr.flw.service.MicroBirthPlanService; +import com.iemr.flw.utils.JwtUtil; +import io.jsonwebtoken.Jwe; +import io.swagger.v3.oas.annotations.Operation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/micro-birthPlan", headers = "Authorization", produces = "application/json") +public class MicroBirthPlanController { + private final Logger logger = LoggerFactory.getLogger(MicroBirthPlanController.class); + + @Autowired + private MicroBirthPlanService service; + + @Autowired + JwtUtil jwtUtil; + + + @RequestMapping(value = "saveAll", method = RequestMethod.POST) + public ResponseEntity> createMicroBirthPlan(@RequestBody MicroBirthPlanDTO birthPlan) { + logger.info("Micro birth plan request " + birthPlan.toString()); + Map response = new HashMap<>(); + + Map data = new HashMap<>(); + try { + data.put("userId", birthPlan.getUserId()); + data.put("entries", service.createMicroBirthPlan(birthPlan)); + response.put("data", data); + response.put("statusCode", 200); + response.put("status", "Success"); + } catch (Exception e) { + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + + + } + + + return ResponseEntity.ok(response); + } + + + @RequestMapping(value = "getAll", method = RequestMethod.GET) + public ResponseEntity> getAllMicroBirthPlans(@RequestParam("userId") Integer userId) { + + Map response = new HashMap<>(); + + + Map data = new HashMap<>(); + try { + if (userId != null) { + data.put("userId", userId); + data.put("entries", service.getAllMicroBirthPlans(userId)); + response.put("data", data); + response.put("statusCode", 200); + response.put("status", "Success"); + } + + } catch (Exception e) { + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + + + } + + return ResponseEntity.ok(response); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/controller/SammelanController.java b/src/main/java/com/iemr/flw/controller/SammelanController.java new file mode 100644 index 00000000..e5c85227 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/SammelanController.java @@ -0,0 +1,110 @@ +package com.iemr.flw.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.service.SammelanService; +import com.iemr.flw.utils.DateUtil; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Limit; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +@RestController +@RequestMapping(value = "/sammelans") +public class SammelanController { + private final Logger logger = LoggerFactory.getLogger(DeathReportsController.class); + + @Autowired + private SammelanService service; + + + + @RequestMapping(value = "saveAll",method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity create( + + @RequestPart("date") String date, + @RequestPart("place") String place, + @RequestPart("participants") String participants, + @RequestPart("ashaId") String ashaId, + @RequestPart(value = "sammelanImages", required = false) List sammelanImages) throws JsonProcessingException { + Map response = new LinkedHashMap<>(); + + SammelanRequestDTO sammelanRequestDTO = new SammelanRequestDTO(); + sammelanRequestDTO.setPlace(place); + sammelanRequestDTO.setParticipants(Integer.valueOf(participants)); + sammelanRequestDTO.setDate(Long.parseLong(date)); + sammelanRequestDTO.setAshaId(Integer.valueOf(ashaId)); + sammelanRequestDTO.setSammelanImages(sammelanImages != null ? sammelanImages.toArray(new MultipartFile[0]) : null); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(sammelanRequestDTO); + logger.info("📥 Incoming HBYC Request: \n" + json+"date"+date); + SammelanResponseDTO resp = service.submitSammelan(sammelanRequestDTO); + + try { + if (resp != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "Data saved successfully"); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", HttpStatus.BAD_REQUEST.getReasonPhrase()); + } + + } catch (Exception e) { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + } + return ResponseEntity.ok(response); + + + } + + + @PostMapping("/getAll") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Successfully fetched meetings", + content = @Content(mediaType = "application/json", + schema = @Schema(implementation = SammelanListResponseDTO.class))), + @ApiResponse(responseCode = "500", description = "Internal Server Error") + }) + public ResponseEntity getMeetings(@RequestBody GetBenRequestHandler getBenRequestHandler) { + SammelanListResponseDTO response = new SammelanListResponseDTO(); + + try { + response.setData(service.getSammelanHistory(getBenRequestHandler.getAshaId())); + response.setStatusCode(HttpStatus.OK.value()); + response.setStatus("Success"); + return ResponseEntity.ok(response); + } catch (Exception e) { + response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+"\n"+e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + } +} + diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index 6beb9008..e95c3ab4 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -1,14 +1,18 @@ package com.iemr.flw.controller; +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.TBConfirmedRequestDTO; import com.iemr.flw.dto.iemr.TBScreeningRequestDTO; import com.iemr.flw.dto.iemr.TBSuspectedRequestDTO; +import com.iemr.flw.service.TBConfirmedCaseService; import com.iemr.flw.service.TBScreeningService; import com.iemr.flw.service.TBSuspectedService; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; +import org.checkerframework.checker.units.qual.A; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -28,6 +32,9 @@ public class TBController { @Autowired private TBSuspectedService tbSuspectedService; + @Autowired + private TBConfirmedCaseService tbConfirmedCaseService; + @Operation(summary = "get tb screening data of all beneficiaries registered with given user id") @RequestMapping(value = { "/screening/getAll" }, method = { RequestMethod.POST }) public String getAllScreeningByUserId(@RequestBody GetBenRequestHandler requestDTO, @@ -42,9 +49,9 @@ public String getAllScreeningByUserId(@RequestBody GetBenRequestHandler requestD if (s != null) response.setResponse(s); else - response.setError(5000, "No record found"); + response.setError(500, "No record found"); } else - response.setError(5000, "Invalid/NULL request obj"); + response.setError(500, "Invalid/NULL request obj"); } catch (Exception e) { logger.error("Error in tb screening get data : " + e); response.setError(5000, "Error in tb screening get data : " + e); @@ -66,9 +73,9 @@ public String saveAllScreeningByUserId(@RequestBody TBScreeningRequestDTO reques if (s != null) response.setResponse(s); else - response.setError(5000, "No record found"); + response.setError(500, "No record found"); } else - response.setError(5000, "Invalid/NULL request obj"); + response.setError(500, "Invalid/NULL request obj"); } catch (Exception e) { logger.error("Error in save tb screening details : " + e); response.setError(5000, "Error in save tb suspected details : " + e); @@ -91,12 +98,12 @@ public String getAllSuspectedByUserId(@RequestBody GetBenRequestHandler requestD if (s != null) response.setResponse(s); else - response.setError(5000, "No record found"); + response.setError(500, "No record found"); } else - response.setError(5000, "Invalid/NULL request obj"); + response.setError(500, "Invalid/NULL request obj"); } catch (Exception e) { logger.error("Error in get data : " + e); - response.setError(5000, "Error in get data : " + e); + response.setError(500, "Error in get data : " + e); } return response.toString(); } @@ -115,13 +122,73 @@ public String saveAllSuspectedByUserId(@RequestBody TBSuspectedRequestDTO reques if (s != null) response.setResponse(s); else - response.setError(5000, "No record found"); + response.setError(500, "No record found"); } else - response.setError(5000, "Invalid/NULL request obj"); + response.setError(500, "Invalid/NULL request obj"); } catch (Exception e) { logger.error("Error in save tb suspected details : " + e); response.setError(5000, "Error in save tb suspected details : " + e); } return response.toString(); } + + @Operation(summary = "save tb confirmed case data of beneficiary") + @RequestMapping(value = { "/confirmed/save" }, method = { RequestMethod.POST }) + public String saveConfirmedCase( + @RequestBody TBConfirmedRequestDTO requestDTO, + @RequestHeader(value = "jwtToken") String token) { + + OutputResponse response = new OutputResponse(); + + try { + if (requestDTO != null) { + + logger.info("request object with timestamp : " + + new Timestamp(System.currentTimeMillis()) + " " + + requestDTO); + + String result = tbConfirmedCaseService.save(requestDTO.getTbConfirmedList(), token); + + if (result != null) + response.setResponse(result); + else + response.setError(500, "No record saved"); + + } else { + response.setError(500, "Invalid/NULL request obj"); + } + } catch (Exception e) { + logger.error("Error in save tb confirmed case details : ", e); + response.setError(500, "Error in save tb confirmed case details : " + e.getMessage()); + } + + return response.toString(); + } + + @Operation(summary = "get tb confirmed case by beneficiary id") + @RequestMapping(value = { "/confirmed/getAll" }, method = { RequestMethod.GET }) + public String getConfirmedByBenId( + @RequestHeader(value = "jwtToken") String token) { + + OutputResponse response = new OutputResponse(); + + try { + String result = + tbConfirmedCaseService.getByUserId(token); + + if (result != null) + response.setResponse(result); + else + response.setError(404, "No record found"); + + } catch (Exception e) { + logger.error("Error in get tb confirmed case details : ", e); + response.setError(500, "Error in get tb confirmed case details : " + e.getMessage()); + } + + return response.toString(); + } + + + } diff --git a/src/main/java/com/iemr/flw/controller/UserController.java b/src/main/java/com/iemr/flw/controller/UserController.java index 307b12a9..605bc0dd 100644 --- a/src/main/java/com/iemr/flw/controller/UserController.java +++ b/src/main/java/com/iemr/flw/controller/UserController.java @@ -9,6 +9,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -31,7 +32,7 @@ public ResponseEntity getUserDetail(@RequestParam(value = "userId") Integer u return new ResponseEntity<>( new ApiResponse(true, null, result), HttpStatus.ACCEPTED); } catch (Exception e) { - logger.error("Error in fetching user role, " + e); + logger.error("Error in fetching user role, " + e.getMessage()); return new ResponseEntity<>( new ApiResponse(false, "Error in fetching user role, " + e.getMessage(), null), HttpStatus.INTERNAL_SERVER_ERROR); diff --git a/src/main/java/com/iemr/flw/controller/UwinSessionController.java b/src/main/java/com/iemr/flw/controller/UwinSessionController.java new file mode 100644 index 00000000..6fd31b16 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/UwinSessionController.java @@ -0,0 +1,96 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.UwinSessionRequestDTO; +import com.iemr.flw.dto.iemr.UwinSessionResponseDTO; +import com.iemr.flw.service.UwinSessionService; +import com.iemr.flw.utils.JwtUtil; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/uwin/session") +public class UwinSessionController { + + + @Autowired + private UwinSessionService service; + + @Autowired + private JwtUtil jwtUtil; + + @RequestMapping(value = "saveAll", method = RequestMethod.POST, headers = "Authorization", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity saveSession( + @RequestPart("meetingDate") String meetingDate, + @RequestPart("place") String place, + @RequestPart("participants") String participants, + @RequestPart("ashaId") String ashaId, + @RequestPart("createdBy") String createdBy, + @RequestPart(value = "meetingImages", required = false) List images) throws Exception { + Map response = new LinkedHashMap<>(); + + UwinSessionRequestDTO dto = new UwinSessionRequestDTO(); + dto.setAshaId(Integer.valueOf(ashaId)); + dto.setDate(Timestamp.valueOf(meetingDate)); + dto.setPlace(place); + dto.setParticipants(Integer.valueOf(participants)); + dto.setCreatedBy(createdBy); + dto.setAttachments(images != null ? images.toArray(new MultipartFile[0]) : null); + UwinSessionResponseDTO uwinSessionResponse = service.saveSession(dto); + try { + if (uwinSessionResponse != null) { + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "Data saved successfully"); + } else { + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", HttpStatus.BAD_REQUEST.getReasonPhrase()); + } + + } catch (Exception e) { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + } + + return ResponseEntity.ok(response); + } + + @RequestMapping(value = "getAll", method = RequestMethod.POST,headers = "Authorization") + public ResponseEntity> getSessions(@RequestBody GetBenRequestHandler getBenRequestHandler, HttpServletRequest request) throws Exception { + Map response = new LinkedHashMap<>(); + + try { + Map data = new HashMap<>(); + + List uwinSessionResponse = service.getSessionsByAsha(getBenRequestHandler.getAshaId()); + if (uwinSessionResponse!= null) { + data.put("userId", getBenRequestHandler.getUserId()); + data.put("entries", service.getSessionsByAsha(getBenRequestHandler.getAshaId())); + response.put("data", data); + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", "Success"); + } else { + response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("message", "Data not found for this user"); + } + + } catch (Exception e) { + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("errorMessage", e.getMessage()); + + } + + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java new file mode 100644 index 00000000..884f794d --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java @@ -0,0 +1,174 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.controller; + +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.service.VillageLevelFormService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +@RestController +@RequestMapping(value = "/forms/villageLevel") +public class VillageLevelFormController { + + @Autowired + private VillageLevelFormService villageLevelFormService; + + @RequestMapping(value = "vhnd/saveAll",method = RequestMethod.POST) + public ResponseEntity> saveVhndForm(@RequestBody VhndDto dto) { + Map response = new HashMap<>(); + if (!dto.getEntries().isEmpty()) { + Boolean isSaved = villageLevelFormService.saveForm(dto); + boolean ok = isSaved; + response.put("status", ok ? "Success" : "Fail"); + response.put("statusCode", ok ? 200 : 500); + response.put("message", "Save Successfully"); + return new ResponseEntity<>(response, ok ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR); + + } else { + response.put("status", "Fail"); + response.put("statusCode", 400); + response.put("message", "Invalid Request Object"); + return ResponseEntity.ok(response); + + } + + + } + + @RequestMapping(value = "vhnc/saveAll", method = RequestMethod.POST) + public ResponseEntity> saveVhncForm(@RequestBody VhncDto dto) { + Map response = new HashMap<>(); + + if (!dto.getEntries().isEmpty()) { + Boolean isSaved = villageLevelFormService.saveVhncForm(dto); + boolean ok = isSaved; + response.put("status", ok ? "Success" : "Fail"); + response.put("statusCode", ok ? 200 : 500); + response.put("message", "Save Successfully"); + return new ResponseEntity<>(response, ok ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR); + } else { + response.put("status", "Fail"); + response.put("statusCode", 400); + response.put("message", "Invalid Request Object"); + return ResponseEntity.ok(response); + + + } + + + } + + @RequestMapping(value = "phc/saveAll", method = RequestMethod.POST) + public ResponseEntity> savePhcForm(@RequestBody PhcReviewMeetingDTO dto) { + Map response = new HashMap<>(); + + if (!dto.getEntries().isEmpty()) { + Boolean isSaved = villageLevelFormService.savePhcForm(dto); + boolean ok = isSaved; + response.put("status", ok ? "Success" : "Fail"); + response.put("statusCode", ok ? 200 : 500); + response.put("message", "Save Successfully"); + return new ResponseEntity<>(response, ok ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR); + } else { + response.put("status", "Fail"); + response.put("statusCode", 400); + response.put("message", "Invalid Request Object"); + return ResponseEntity.ok(response); + + } + + + } + + @RequestMapping(value = "ahd/saveAll", method = RequestMethod.POST) + public ResponseEntity> saveAhdForm(@RequestBody AhdMeetingDto dto) { + Map response = new HashMap<>(); + + if(!dto.getEntries().isEmpty()){ + Boolean isSaved = villageLevelFormService.saveAhdForm(dto); + boolean ok = isSaved; + response.put("status", ok ? "Success" : "Fail"); + response.put("statusCode", ok ? 200 : 500); + response.put("message", "Save Successfully"); + return new ResponseEntity<>(response, ok ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR); + }else { + response.put("status", "Fail"); + response.put("statusCode", 400); + response.put("message", "Invalid Request Object"); + return ResponseEntity.ok(response); + } + + } + + @RequestMapping(value = "deworming/saveAll", method = RequestMethod.POST) + public ResponseEntity> saveDewormingForm(@RequestBody DewormingDto dto) { + Map response = new HashMap<>(); + + if(!dto.getEntries().isEmpty()){ + Boolean isSaved = villageLevelFormService.saveDewormingForm(dto); + boolean ok = isSaved; + response.put("status", ok ? "Success" : "Fail"); + response.put("statusCode", ok ? 200 : 500); + response.put("message", "Save Successfully"); + return new ResponseEntity<>(response, ok ? HttpStatus.OK : HttpStatus.INTERNAL_SERVER_ERROR); + }else { + response.put("status", "Fail"); + response.put("statusCode", 400); + response.put("message", "Invalid Request Object"); + return ResponseEntity.ok(response); + } + + } + + + @RequestMapping(value = "getAll", method = RequestMethod.POST) + public ResponseEntity> getVillageLevelFormData(@RequestBody GetVillageLevelRequestHandler getVillageLevelRequestHandler) { + Map response = new LinkedHashMap<>(); + + try { + Map data = new HashMap<>(); + data.put("userId", getVillageLevelRequestHandler.getUserId()); + data.put("entries", villageLevelFormService.getAll(getVillageLevelRequestHandler)); + response.put("data", data); + response.put("statusCode", 200); + response.put("message", "Success"); + } catch (Exception e) { + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + + } + + return ResponseEntity.ok(response); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/controller/health/HealthController.java b/src/main/java/com/iemr/flw/controller/health/HealthController.java new file mode 100644 index 00000000..93308554 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/health/HealthController.java @@ -0,0 +1,83 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.flw.controller.health; + +import java.time.Instant; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.iemr.flw.service.health.HealthService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/health") +@Tag(name = "Health Check", description = "APIs for checking infrastructure health status") +public class HealthController { + + private static final Logger logger = LoggerFactory.getLogger(HealthController.class); + + private final HealthService healthService; + + public HealthController(HealthService healthService) { + this.healthService = healthService; + } + + @GetMapping + @Operation(summary = "Check infrastructure health", + description = "Returns the health status of MySQL, Redis, and other configured services") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Services are UP or DEGRADED (operational with warnings)"), + @ApiResponse(responseCode = "503", description = "One or more critical services are DOWN") + }) + public ResponseEntity> checkHealth() { + logger.debug("Health check endpoint called"); + + try { + Map healthStatus = healthService.checkHealth(); + String overallStatus = (String) healthStatus.get("status"); + + HttpStatus httpStatus = "DOWN".equals(overallStatus) ? HttpStatus.SERVICE_UNAVAILABLE : HttpStatus.OK; + + logger.debug("Health check completed with status: {}", overallStatus); + return new ResponseEntity<>(healthStatus, httpStatus); + + } catch (Exception e) { + logger.error("Unexpected error during health check", e); + + Map errorResponse = Map.of( + "status", "DOWN", + "timestamp", Instant.now().toString() + ); + + return new ResponseEntity<>(errorResponse, HttpStatus.SERVICE_UNAVAILABLE); + } + } +} diff --git a/src/main/java/com/iemr/flw/controller/version/VersionController.java b/src/main/java/com/iemr/flw/controller/version/VersionController.java new file mode 100644 index 00000000..f2f2bf66 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/version/VersionController.java @@ -0,0 +1,80 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.flw.controller.version; + +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Operation; + +@RestController +public class VersionController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + private static final String UNKNOWN_VALUE = "unknown"; + + @Operation(summary = "Get version information") + @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity> versionInformation() { + Map response = new LinkedHashMap<>(); + try { + logger.info("version Controller Start"); + Properties gitProperties = loadGitProperties(); + response.put("buildTimestamp", gitProperties.getProperty("git.build.time", UNKNOWN_VALUE)); + response.put("version", gitProperties.getProperty("git.build.version", UNKNOWN_VALUE)); + response.put("branch", gitProperties.getProperty("git.branch", UNKNOWN_VALUE)); + response.put("commitHash", gitProperties.getProperty("git.commit.id.abbrev", UNKNOWN_VALUE)); + } catch (Exception e) { + logger.error("Failed to load version information", e); + response.put("buildTimestamp", UNKNOWN_VALUE); + response.put("version", UNKNOWN_VALUE); + response.put("branch", UNKNOWN_VALUE); + response.put("commitHash", UNKNOWN_VALUE); + } + logger.info("version Controller End"); + return ResponseEntity.ok(response); + } + + private Properties loadGitProperties() throws IOException { + Properties properties = new Properties(); + try (InputStream input = getClass().getClassLoader() + .getResourceAsStream("git.properties")) { + if (input != null) { + properties.load(input); + } + } + return properties; + } +} diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java index 8d69c685..297694b7 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java @@ -9,7 +9,7 @@ import java.sql.Timestamp; @Entity -@Table(name = "i_beneficiarydetails_rmnch") +@Table(name = "i_beneficiarydetails_rmnch",schema = "db_identity") @Data public class RMNCHBeneficiaryDetailsRmnch { @Id @@ -339,6 +339,56 @@ public class RMNCHBeneficiaryDetailsRmnch { @Transient private String villageName; + + @Expose + private Boolean isDeath; + + @Expose + private String isDeathValue; + + @Expose + private String dateOfDeath; + + @Expose + private String timeOfDeath; + + @Expose + private String reasonOfDeath; + + @Expose + private Integer reasonOfDeathId; + + @Expose + private String placeOfDeath; + + @Expose + private Integer placeOfDeathId; + + @Expose + private String otherPlaceOfDeath; + + @Expose + private Boolean isSpouseAdded; + + + @Expose + private Boolean isChildrenAdded; + + @Expose + private Boolean isMarried; + + @Expose + private Boolean doYouHavechildren; + + @Expose + private Integer noOfchildren; + + @Expose + private Integer noofAlivechildren; + + @Expose + private Boolean isDeactivate; + @Expose @Transient private Integer servicePointID; diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHBornBirthDetails.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHBornBirthDetails.java index 27925716..6b5d4c3a 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHBornBirthDetails.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHBornBirthDetails.java @@ -314,4 +314,16 @@ public class RMNCHBornBirthDetails { @Column(name = "birthOPV") private Boolean birthOPV; + @Expose + @Column(name = "birthCertificateFileFrontView") + private String birthCertificateFileFrontView; + + @Expose + @Column(name = "birthCertificateFileBackView") + private String birthCertificateFileBackView; + + + + + } diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java index 9ab4f822..3a3ccec8 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java @@ -325,4 +325,8 @@ public class RMNCHHouseHoldDetails { @Column(name = "mohallaName") private String mohallaName; + @Expose + @Column(name = "isDeactivate") + private Boolean isDeactivate; + } diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java index 667c5b84..72e994f5 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java @@ -185,4 +185,5 @@ public class RMNCHMBeneficiarydetail { @Expose @Transient private Integer ProviderServiceMapID; + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/AHDForm.java b/src/main/java/com/iemr/flw/domain/iemr/AHDForm.java new file mode 100644 index 00000000..a9a20dfb --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AHDForm.java @@ -0,0 +1,47 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.sql.Timestamp; + +import static jakarta.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "ahd_form", schema = "db_iemr") +@Data +public class AHDForm { + + @Id + @GeneratedValue(strategy = IDENTITY) + private int id; + + @Column(name = "mobilized_for_ahd") + private String mobilizedForAHD; + + @Column(name = "ahd_place") + private String ahdPlace; + + @Column(name = "ahd_date") + private String ahdDate; + + @Column(name = "image1") + private String image1; + + @Column(name = "image2") + private String image2; + + @Column(name = "user_id") + private Long userId; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "form_type") + private String formType; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java b/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java index 9aeb8878..4128f082 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java @@ -112,4 +112,70 @@ public class ANCVisit { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "file_path") + private String filePath; + + @Column(name = "serial_no") + private String serialNo; + + @Column(name = "method_of_termination") + private String methodOfTermination; + + @Column(name = "method_of_termination_id") + private Integer methodOfTerminationId; + + @Column(name = "termination_done_by") + private String terminationDoneBy; + + @Column(name = "termination_done_by_id") + private Integer terminationDoneById; + + @Column(name = "is_paiucd_id") + private Integer isPaiucdId; + + @Column(name = "is_paiucd") + private String isPaiucd; + + @Column(name = "remarks") + private String remarks; + + @Column(name = "abortion_img1") + private String abortionImg1; + + @Column(name = "abortion_img2") + private String abortionImg2; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "place_of_death_id") + private Integer placeOfDeathId; + + @Column(name = "other_place_of_death") + private String otherPlaceOfDeath; + + @Column(name = "visit_date") + private Timestamp visitDate; + + @Column(name = "lmp_date") + private Timestamp lmpDate; + + @Column(name = "is_YesOrNo") + private Boolean isYesOrNo; + + @Column(name = "date_of_sterilisation") + private Timestamp dateSterilisation; + + @Column (name = "place_of_anc") + private String placeOfAnc; + + @Column(name = "place_of_ancId") + private Integer placeOfAncId; + + + + + + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/AdolescentHealth.java b/src/main/java/com/iemr/flw/domain/iemr/AdolescentHealth.java new file mode 100644 index 00000000..14008706 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AdolescentHealth.java @@ -0,0 +1,72 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Date; +import java.sql.Timestamp; + +@Entity +@Data +@Table(name = "adolescent_health") +public class AdolescentHealth { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "ben_id") + private BigInteger benId; + + @Column(name = "userID") + private Integer userId; + + @Column(name = "visit_date") + private Timestamp visitDate; + + @Column(name = "health_status",length = 50) + private String healthStatus; + + @Column(name = "ifa_tablet_distribution") + private Boolean ifaTabletDistribution; + + @Column(name = "quantity_of_ifa_tablets") + private Integer quantityOfIfaTablets; + + @Column(name = "menstrual_hygiene_awareness_given") + private Boolean menstrualHygieneAwarenessGiven; + + @Column(name = "sanitary_napkin_distributed") + private Boolean sanitaryNapkinDistributed; + + @Column(name = "no_of_packets_distributed") + private Integer noOfPacketsDistributed; + + @Column(name = "place",length = 100) + private String place; + + @Column(name = "referred_to_health_facility",length = 100) + private String referredToHealthFacility; + + @Column(name = "counseling_provided") + private Boolean counselingProvided; + + @Column(name = "counseling_type",length = 50) + private String counselingType; + + @Column(name = "follow_up_date") + private Date followUpDate; + + @Column(name = "referral_status",length = 50) + private String referralStatus; + + @Column(name = "created_date") + private Timestamp createdDate; + + @Column(name = "created_by") + private String createdBy; + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/AncCounsellingCare.java b/src/main/java/com/iemr/flw/domain/iemr/AncCounsellingCare.java new file mode 100644 index 00000000..46737f12 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AncCounsellingCare.java @@ -0,0 +1,128 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Table(name = "anc_counselling_care", schema = "db_iemr") +@Data +public class AncCounsellingCare { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "beneficiary_id", nullable = false) + private Long beneficiaryId; + + @Column(name = "visit_date") + private LocalDate visitDate; + + @Column(name = "home_visit_date", nullable = false) + private LocalDate homeVisitDate; + + @Column(name = "anc_visit_id", nullable = false) + private Long ancVisitId; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "updated_by") + private String updatedBy; + + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + /* ---------- BOOLEAN FLAGS ---------- */ + + @Column(name = "select_all") + private Boolean selectAll = false; + + @Column(name = "swelling") + private Boolean swelling = false; + + @Column(name = "high_bp") + private Boolean highBp = false; + + @Column(name = "convulsions") + private Boolean convulsions = false; + + @Column(name = "anemia") + private Boolean anemia = false; + + @Column(name = "reduced_fetal_movement") + private Boolean reducedFetalMovement = false; + + @Column(name = "age_risk") + private Boolean ageRisk = false; + + @Column(name = "child_gap") + private Boolean childGap = false; + + @Column(name = "short_height") + private Boolean shortHeight = false; + + @Column(name = "pre_preg_weight") + private Boolean prePregWeight = false; + + @Column(name = "bleeding") + private Boolean bleeding = false; + + @Column(name = "miscarriage_history") + private Boolean miscarriageHistory = false; + + @Column(name = "four_plus_delivery") + private Boolean fourPlusDelivery = false; + + @Column(name = "first_delivery") + private Boolean firstDelivery = false; + + @Column(name = "twin_pregnancy") + private Boolean twinPregnancy = false; + + @Column(name = "c_section_history") + private Boolean cSectionHistory = false; + + @Column(name = "pre_existing_disease") + private Boolean preExistingDisease = false; + + @Column(name = "fever_malaria") + private Boolean feverMalaria = false; + + @Column(name = "jaundice") + private Boolean jaundice = false; + + @Column(name = "sickle_cell") + private Boolean sickleCell = false; + + @Column(name = "prolonged_labor") + private Boolean prolongedLabor = false; + + @Column(name = "malpresentation") + private Boolean malpresentation = false; + + /* ---------- Lifecycle Hooks ---------- */ + + @PrePersist + protected void onCreate() { + this.createdAt = LocalDateTime.now(); + this.updatedAt = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedAt = LocalDateTime.now(); + } + + /* ---------- Getters & Setters ---------- */ + // Lombok use kar raha ho toh @Getter @Setter laga sakta hai +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java b/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java new file mode 100644 index 00000000..36fba04e --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java @@ -0,0 +1,111 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import jakarta.validation.constraints.*; +import lombok.*; + +import java.time.LocalDate; + + +@Entity +@Data +@Table(name = "asha_profile",schema = "db_iemr") +public class AshaWorker { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "village") + private String village; + + @Column(name = "employee_id") + private Integer employeeId; // Changed from Integer to String + + @Column(name = "dob") + private LocalDate dob; // Changed from String to LocalDate + + + @Column(name = "mobile_number") + private String mobileNumber; + + @Column(name = "alternate_mobile_number") + private String alternateMobileNumber; + + @Column(name = "father_or_spouse_name") + private String fatherOrSpouseName; + + @Column(name = "date_of_joining") + private LocalDate dateOfJoining; // Changed from String to LocalDate + + + @Column(name = "bank_account") + private String bankAccount; + + @Column(name = "ifsc") + private String ifsc; + + + @Column(name = "population_covered") + private Integer populationCovered; + + + @Column(name = "cho_name",nullable = false) + private String choName; + + + @Column(name = "cho_mobile") + private String choMobile; + + + @Column(name = "aww_name") + private String awwName; + + + @Column(name = "aww_mobile") + private String awwMobile; + + + @Column(name = "anm1_name") + private String anm1Name; + + + @Column(name = "anm1_mobile") + private String anm1Mobile; + + + @Column(name = "anm2_name") + private String anm2Name; + + + @Column(name = "anm2_mobile") + private String anm2Mobile; + + + @Column(name = "abha_number") + private String abhaNumber; + + @Column(name = "asha_household_registration") + private String ashaHouseholdRegistration; + + @Column(name = "asha_family_member") + private String ashaFamilyMember; + + @Column(name = "ProviderServiceMapID") + private Integer ProviderServiceMapID; + + @Column(name = "profileImage") + private String profileImage; + + @Column(name = "isFatherOrSpouse") + private Boolean isFatherOrSpouse; + @Column(name = "supervisorName") + private String supervisorName; + @Column(name = "supervisorMobile") + private String supervisorMobile; + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/BenReferDetails.java b/src/main/java/com/iemr/flw/domain/iemr/BenReferDetails.java new file mode 100644 index 00000000..2112f311 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/BenReferDetails.java @@ -0,0 +1,433 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.domain.iemr; + +import java.sql.Timestamp; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; + +import com.fasterxml.jackson.annotation.JsonFormat; +//import com.fasterxml.jackson.annotation.JsonFormat; +import com.google.gson.annotations.Expose; + +@Entity +@Table(name = "t_benreferdetails",schema = "db_iemr") +public class BenReferDetails { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Expose + @Column(name = "benReferID") + private Long benReferID; + + @Expose + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Expose + @Column(name = "BenVisitID") + private Long benVisitID; + + @Expose + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Expose + @Column(name = "VisitCode") + private Long visitCode; + + @Expose + @Column(name = "referredToInstituteID") + private Integer referredToInstituteID; + + @Expose + @Column(name = "referredToInstituteName") + private String referredToInstituteName; + + @Expose + @Column(name = "OtherReferredToInstituteName") + private String otherReferredToInstituteName; + + @Expose + @Column(name = "serviceID") + private Short serviceID; + + @Expose + @Column(name = "serviceName") + private String serviceName; + + @Expose + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Expose + @Column(name = "Processed", insertable = false, updatable = false) + private String processed; + + @Expose + @Column(name = "CreatedBy", updatable = false) + private String createdBy; + + @Expose + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Expose + @Column(name = "ModifiedBy", insertable = false) + private String modifiedBy; + + @Expose + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Expose + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Expose + @Column(name = "VehicalNo") + private String vehicalNo; + + @Expose + @Column(name = "vanID") + private Integer vanID; + + @Expose + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Expose + @Column(name = "SyncedBy") + private String syncedBy; + + @Expose + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Expose + @Column(name = "ReservedForChange") + private String reservedForChange; + + @Transient + private String[] refrredToAdditionalServiceList; + + @Expose + @Column(name = "revisitdate") +// @JsonFormat(pattern="yyyy-MM-dd") + private Timestamp revisitDate; + + @Expose + @Column(name = "referralreason") + private String referralReason; + + @Expose + @Column(name = "OtherReferralReason") + private String otherReferralReason; + + @Expose + @Transient + private String[] referralReasonList; + + public String getOtherReferredToInstituteName() { + return otherReferredToInstituteName; + } + + public void setOtherReferredToInstituteName(String otherReferredToInstituteName) { + this.otherReferredToInstituteName = otherReferredToInstituteName; + } + + public String getOtherReferralReason() { + return otherReferralReason; + } + + public void setOtherReferralReason(String otherReferralReason) { + this.otherReferralReason = otherReferralReason; + } + + public String[] getReferralReasonList() { + return referralReasonList; + } + + public void setReferralReasonList(String[] referralReasonList) { + this.referralReasonList = referralReasonList; + } + + public String getReferralReason() { + return referralReason; + } + + public void setReferralReason(String referralReason) { + this.referralReason = referralReason; + } + + public Long getBenReferID() { + return benReferID; + } + + public void setBenReferID(Long benReferID) { + this.benReferID = benReferID; + } + + public Long getBeneficiaryRegID() { + return beneficiaryRegID; + } + + public void setBeneficiaryRegID(Long beneficiaryRegID) { + this.beneficiaryRegID = beneficiaryRegID; + } + + public Long getBenVisitID() { + return benVisitID; + } + + public void setBenVisitID(Long benVisitID) { + this.benVisitID = benVisitID; + } + + public Integer getProviderServiceMapID() { + return providerServiceMapID; + } + + public void setProviderServiceMapID(Integer providerServiceMapID) { + this.providerServiceMapID = providerServiceMapID; + } + + public Long getVisitCode() { + return visitCode; + } + + public void setVisitCode(Long visitCode) { + this.visitCode = visitCode; + } + + public Integer getReferredToInstituteID() { + return referredToInstituteID; + } + + public void setReferredToInstituteID(Integer referredToInstituteID) { + this.referredToInstituteID = referredToInstituteID; + } + + public String getReferredToInstituteName() { + return referredToInstituteName; + } + + public void setReferredToInstituteName(String referredToInstituteName) { + this.referredToInstituteName = referredToInstituteName; + } + + public Short getServiceID() { + return serviceID; + } + + public void setServiceID(Short serviceID) { + this.serviceID = serviceID; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public Boolean getDeleted() { + return deleted; + } + + public void setDeleted(Boolean deleted) { + this.deleted = deleted; + } + + public String getProcessed() { + return processed; + } + + public void setProcessed(String processed) { + this.processed = processed; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Timestamp getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Timestamp createdDate) { + this.createdDate = createdDate; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public Timestamp getLastModDate() { + return lastModDate; + } + + public void setLastModDate(Timestamp lastModDate) { + this.lastModDate = lastModDate; + } + + public Long getVanSerialNo() { + return vanSerialNo; + } + + public void setVanSerialNo(Long vanSerialNo) { + this.vanSerialNo = vanSerialNo; + } + + public String getVehicalNo() { + return vehicalNo; + } + + public void setVehicalNo(String vehicalNo) { + this.vehicalNo = vehicalNo; + } + + public Integer getParkingPlaceID() { + return parkingPlaceID; + } + + public void setParkingPlaceID(Integer parkingPlaceID) { + this.parkingPlaceID = parkingPlaceID; + } + + public String getSyncedBy() { + return syncedBy; + } + + public void setSyncedBy(String syncedBy) { + this.syncedBy = syncedBy; + } + + public Timestamp getSyncedDate() { + return syncedDate; + } + + public void setSyncedDate(Timestamp syncedDate) { + this.syncedDate = syncedDate; + } + + public String getReservedForChange() { + return reservedForChange; + } + + public void setReservedForChange(String reservedForChange) { + this.reservedForChange = reservedForChange; + } + + public String[] getRefrredToAdditionalServiceList() { + return refrredToAdditionalServiceList; + } + + public void setRefrredToAdditionalServiceList(String[] refrredToAdditionalServiceList) { + this.refrredToAdditionalServiceList = refrredToAdditionalServiceList; + } + + public BenReferDetails() { + super(); + // TODO Auto-generated constructor stub + } + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + public Timestamp getRevisitDate() { + + return revisitDate; + } + + public void setRevisitDate(Timestamp revisitDate) { + + this.revisitDate = revisitDate; + } + +// public BenReferDetails(Long benReferID, Long beneficiaryRegID, Long benVisitID, Integer providerServiceMapID, +// Integer referredToInstituteID, String referredToInstituteName, Short serviceID, String serviceName, +// Long visitCode, Timestamp revisitDate, String referralReason, Timestamp createdDate, +// String otherReferredToInstituteName, String otherReferralReason) { +// super(); +// this.benReferID = benReferID; +// this.beneficiaryRegID = beneficiaryRegID; +// this.benVisitID = benVisitID; +// this.providerServiceMapID = providerServiceMapID; +// this.referredToInstituteID = referredToInstituteID; +// this.referredToInstituteName = referredToInstituteName; +// this.serviceID = serviceID; +// this.serviceName = serviceName; +// this.visitCode = visitCode; +// this.revisitDate = revisitDate; +// this.referralReason = referralReason; +// this.createdDate = createdDate; +// +// this.otherReferredToInstituteName = otherReferredToInstituteName; +// this.otherReferralReason = otherReferralReason; +// } + +// public static BenReferDetails getBenReferDetails(ArrayList resList) { +// // ArrayList resArray = new ArrayList(); +// BenReferDetails cOBJ = null; +// if (resList != null && resList.size() > 0) { +// +// Object[] obj1 = resList.get(0); +// +// cOBJ = new BenReferDetails((Long) obj1[0], (Long) obj1[1], (Long) obj1[2], (Integer) obj1[3], +// (Integer) obj1[4], (String) obj1[5], (Short) obj1[6], (String) obj1[7], (Long) obj1[8], +// (Timestamp) obj1[9], (String) obj1[10], (Timestamp) obj1[11], (String) obj1[12], (String) obj1[13]); +// ArrayList servicesList = new ArrayList(); +// for (Object[] obj : resList) { +// if (null != obj[6]) { +// ServiceMaster sm = new ServiceMaster((Short) obj[6], (String) obj[7]); +// servicesList.add(sm); +// } +// } +// +// cOBJ.setRefrredToAdditionalServiceList(servicesList); +// } +// return cOBJ; +// } + + public Integer getVanID() { + return vanID; + } + + public void setVanID(Integer vanID) { + this.vanID = vanID; + } + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/CDR.java b/src/main/java/com/iemr/flw/domain/iemr/CDR.java index 057d53d9..89744928 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/CDR.java +++ b/src/main/java/com/iemr/flw/domain/iemr/CDR.java @@ -72,6 +72,18 @@ public class CDR { @Column(name = "created_by") private String createdBy; + @Column(name = "cdr_image_1") + private String cdrImage; + + @Column(name = "cdr_image_2") + private String cdrImage2; + + @Column(name = "death_cert_image_1") + private String deathCertImage1; + + @Column(name = "death_cert_image_2") + private String deathCertImage2; + @Column(name = "created_date") private Timestamp createdDate; @@ -80,4 +92,5 @@ public class CDR { @Column(name = "updated_by") private String updatedBy; + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java new file mode 100644 index 00000000..e33e1543 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java @@ -0,0 +1,59 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Table(name = "campaign_ors",schema = "db_iemr") +@Data +public class CampaignOrs { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "start_date", nullable = false) + private LocalDate startDate; + + @Column(name = "end_date", nullable = false) + private LocalDate endDate; + + @Column(name = "user_id", nullable = false) + private Integer userId; + + @Column(name = "number_of_families", nullable = false) + private Integer numberOfFamilies = 0; + + @Column(name = "campaign_photos",columnDefinition = "LONGTEXT") + private String campaignPhotos; + + @Column(name = "created_by", length = 200) + private String createdBy; + + @Column(name = "updated_by", length = 200) + private String updatedBy; + + @Column(name = "created_date", updatable = false) + private LocalDateTime createdDate; + + @Column(name = "updated_date") + private LocalDateTime updatedDate; + + /* ---------- Auto timestamps ---------- */ + + @PrePersist + protected void onCreate() { + this.createdDate = LocalDateTime.now(); + this.updatedDate = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedDate = LocalDateTime.now(); + } + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/CbacDetailsImer.java b/src/main/java/com/iemr/flw/domain/iemr/CbacDetailsImer.java new file mode 100644 index 00000000..989ed1d1 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/CbacDetailsImer.java @@ -0,0 +1,330 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.domain.iemr; + +import java.sql.Timestamp; + +import jakarta.persistence.*; + +import com.google.gson.annotations.Expose; +import lombok.Data; + +@Entity +@Table(name = "t_cbacdetails") +@Data +public class CbacDetailsImer { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Expose + @Column(name = "Id", insertable = false) + private Long id; + @Expose + @Column(name = "BeneficiaryRegId") + private Long beneficiaryRegId; + + @Expose + @Column(name = "Visitcode") + private Long visitCode; + @Expose + @Column(name = "Cbac_Age") + private String cbacAge; + @Expose + @Column(name = "Cbac_Age_Score") + private Integer cbacAgeScore; + @Expose + @Column(name = "Cbac_ConusmeGutka") + private String cbacConsumeGutka; + @Expose + @Column(name = "Cbac_ConusmeGutka_Score") + private Integer cbacConsumeGutkaScore; + @Expose + @Column(name = "cbac_alcohol") + private String cbacAlcohol; + @Expose + @Column(name = "cbac_alcohol_Score") + private Integer cbacAlcoholScore; + @Expose + @Column(name = "Cbac_waist_Male") + private String cbacWaistMale; + @Expose + @Column(name = "Cbac_waist_Male_Score") + private Integer cbacWaistMaleScore; + @Expose + @Column(name = "Cbac_Waist_Female") + private String cbacWaistFemale; + @Expose + @Column(name = "Cbac_Waist_Female_Score") + private Integer cbacWaistFemaleScore; + @Expose + @Column(name = "Cbac_PhysicalActivity") + private String cbacPhysicalActivity; + @Expose + @Column(name = "Cbac_PhysicalActivity_Score") + private Integer cbacPhysicalActivityScore; + @Expose + @Column(name = "Cbac_FamilyHistory_bpdiabetes") + private String cbacFamilyHistoryBpdiabetes; + @Expose + @Column(name = "Cbac_FamilyHistory_bpdiabetes_Score") + private Integer cbacFamilyHistoryBpdiabetesScore; + @Expose + @Column(name = "Cbac_ShortnessBreath") + private String cbacShortnessBreath; + @Expose + @Column(name = "Cbac_Cough2weeks") + private String cbacCough2weeks; + @Expose + @Column(name = "Cbac_Bloodsputum") + private String cbacBloodsputum; + @Expose + @Column(name = "Cbac_fever2weeks") + private String cbacFever2weeks; + @Expose + @Column(name = "Cbac_WeightLoss") + private String cbacWeightLoss; + @Expose + @Column(name = "Cbac_NightSweats") + private String cbacNightSweats; + @Expose + @Column(name = "Cbac_AntiTBDrugs") + private String cbacAntiTBDrugs; + @Expose + @Column(name = "Cabc_TB") + private String cbacTb; + @Expose + @Column(name = "Cbac_TBHistory") + private String cbacTBHistory; + @Expose + @Column(name = "Cbac_Ulceration") + private String cbacUlceration; + @Expose + @Column(name = "Cbac_RecurrentTingling") + private String cbacRecurrentTingling; + @Expose + @Column(name = "Cbac_FitsHistory") + private String cbacFitsHistory; + @Expose + @Column(name = "Cbac_MouthopeningDifficulty") + private String cbacMouthopeningDifficulty; + @Expose + @Column(name = "Cbac_MouthUlcers") + private String cbacMouthUlcers; + @Expose + @Column(name = "Cbac_MouthUlcersGrowth") + private String cbacMouthUlcersGrowth; + @Expose + @Column(name = "Cbac_Mouthredpatch") + private String cbacMouthredpatch; + @Expose + @Column(name = "Cbac_Painchewing") + private String cbacPainchewing; + @Expose + @Column(name = "Cbac_Tonechange") + private String cbacTonechange; + @Expose + @Column(name = "Cbac_Hypopigmentedpatches") + private String cbacHypopigmentedpatches; + @Expose + @Column(name = "Cbac_Thickenedskin") + private String cbacThickenedskin; + @Expose + @Column(name = "Cbac_Nodulesonskin") + private String cbacNodulesonskin; + @Expose + @Column(name = "Cbac_RecurrentNumbness") + private String cbacRecurrentNumbness; + @Expose + @Column(name = "Cbac_BlurredVision") + private String cbacBlurredVision; + @Expose + @Column(name = "Cbac_Difficultyreading") + private String cbacDifficultyreading; + @Expose + @Column(name = "Cbac_Painineyes") + private String cbacPainineyes; + @Expose + @Column(name = "Cbac_RednessPain") + private String cbacRednessPain; + @Expose + @Column(name = "Cbac_DifficultyHearing") + private String cbacDifficultyHearing; + @Expose + @Column(name = "Cbac_Clawingfingers") + private String cbacClawingfingers; + @Expose + @Column(name = "Cbac_HandTingling") + private String cbacHandTingling; + @Expose + @Column(name = "Cbac_InabilityCloseeyelid") + private String cbacInabilityCloseeyelid; + @Expose + @Column(name = "Cbac_DifficultHoldingObjects") + private String cbacDifficultHoldingObjects; + @Expose + @Column(name = "Cbac_Feetweakness") + private String cbacFeetweakness; + @Expose + @Column(name = "Cbac_LumpBreast") + private String cbacLumpBreast; + @Expose + @Column(name = "Cbac_BloodnippleDischarge") + private String cbacBloodnippleDischarge; + @Expose + @Column(name = "Cbac_Breastsizechange") + private String cbacBreastsizechange; + @Expose + @Column(name = "Cbac_BleedingPeriods") + private String cbacBleedingPeriods; + @Expose + @Column(name = "Cbac_BleedingMenopause") + private String cbacBleedingMenopause; + @Expose + @Column(name = "Cbac_BleedingIntercourse") + private String cbacBleedingIntercourse; + @Expose + @Column(name = "Cbac_VaginalDischarge") + private String cbacVaginalDischarge; + @Expose + @Column(name = "Cbac_FeelingUnsteady") + private String cbacFeelingUnsteady; + @Expose + @Column(name = "Cbac_PhysicalDisabilitySuffering") + private String cbacPhysicalDisabilitySuffering; + @Expose + @Column(name = "Cbac_NeedhelpEverydayActivities") + private String cbacNeedhelpEverydayActivities; + @Expose + @Column(name = "Cbac_Forgetnearones") + private String cbacForgetnearones; + @Expose + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapId; + + @Expose + @Column(name = "Total_Score") + private Integer totalScore; + @Expose + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Expose + @Column(name = "Processed", insertable = false, updatable = true) + private Character processed; + + @Expose + @Column(name = "CreatedBy") + private String createdBy; + + @Expose + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Expose + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Expose + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Expose + @Column(name = "VanSerialNo") + private Integer vanSerialNo; + @Expose + @Column(name = "VanID") + private Integer vanId; + @Expose + @Column(name = "VehicalNo") + private String vehicalNo; + @Expose + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceId; + @Expose + @Column(name = "SyncedBy") + private String syncedBy; + @Expose + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Transient + @Expose + private Long beneficiaryId; + + @Expose + @Column(name = "Cbac_OccupationalExposure") + private String CbacOccupationalExposure; + + @Expose + @Column(name = "Cbac_BotheredProblem_last2weeks") + private String CbacBotheredProblemLast2weeks; + + @Expose + @Column(name = "Cbac_LittleInterest_Pleasure") + private String CbacLittleInterestPleasure; + + @Expose + @Column(name = "Cbac_Depressed_hopeless") + private String CbacDepressedhopeless; + + @Expose + @Column(name = "Cbac_DiscolorationSkin") + private String CbacDiscolorationSkin; + + @Expose + @Column(name = "Cbac_Cooking_Oil") + private String CbacCookingOil; + + @Expose + @Column(name = "Cbac_OccupationalExposure_score") + private String CbacOccupationalExposureScore; + + @Expose + @Column(name = "Cbac_BotheredProblem_last2weeks_score") + private String CbacBotheredProblemLast2weeksScore; + + @Expose + @Column(name = "Cbac_LittleInterest_Pleasure_score") + private String CbacLittleInterestPleasureScore; + + @Expose + @Column(name = "Cbac_Depressed_hopeless_score") + private String CbacDepressedhopelessScore; + + @Expose + @Column(name = "Cbac_Cooking_Oil_score") + private String CbacCookingOilScore; + + + @Expose + @Column(name = "Cbac_Feeling_Down_score") + private String CbacFeelingDownScore; + + @Expose + @Column(name = "is_refer") + private Boolean isRefer; + + + + + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java b/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java new file mode 100644 index 00000000..10689cff --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java @@ -0,0 +1,75 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Table(name = "cdtf_visit_details") +@Data +public class ChronicDiseaseVisitEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "beneficiary_id") + private Long benId; + + @Column(name = "household_id") + private Long hhId; + + @Column(name = "form_id") + private String formId; + + @Column(name = "version") + private Integer version; + + @Column(name = "visit_no") + private Integer visitNo; + + @Column(name = "follow_up_no") + private Integer followUpNo; + + @Column(name = "diagnosis_codes", columnDefinition = "TEXT") + private String diagnosisCodes; + + @Column(name = "treatment_start_date") + private LocalDate treatmentStartDate; + + @Column(name = "follow_up_date") + private LocalDate followUpDate; + + @Column(name = "form_data_json", columnDefinition = "JSON") + private String formDataJson; + + @Column(name = "user_id") + private Integer userID; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "created_date") + private LocalDateTime createdDate; + + @Column(name = "updated_by") + private Integer updatedBy; + + @Column(name = "updated_date") + private LocalDateTime updatedDate; + + // 🔹 Auto timestamps + @PrePersist + protected void onCreate() { + this.createdDate = LocalDateTime.now(); + this.updatedDate = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedDate = LocalDateTime.now(); + } + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java b/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java index 104544fb..d3a1b56c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java @@ -1,5 +1,6 @@ package com.iemr.flw.domain.iemr; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import jakarta.persistence.*; @@ -67,12 +68,13 @@ public class DeliveryOutcome { @Column(name = "created_by") private String createdBy; + @Column(name = "updated_by") + private String updatedBy; + @Column(name = "created_date") private Timestamp createdDate; @Column(name = "updated_date") private Timestamp updatedDate; - @Column(name = "updated_by") - private String updatedBy; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/DewormingForm.java b/src/main/java/com/iemr/flw/domain/iemr/DewormingForm.java new file mode 100644 index 00000000..631dbfd5 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/DewormingForm.java @@ -0,0 +1,50 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.sql.Timestamp; + +import static jakarta.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "deworming_form", schema = "db_iemr") +@Data +public class DewormingForm { + + @Id + @GeneratedValue(strategy = IDENTITY) + private int id; + + @Column(name = "deworming_done") + private String dewormingDone; + + @Column(name = "deworming_date") + private String dewormingDate; + + @Column(name = "deworming_location") + private String dewormingLocation; + + @Column(name = "age_group") + private Integer ageGroup; + + @Column(name = "image1") + private String image1; + + @Column(name = "image2") + private String image2; + + @Column(name = "user_id") + private Long userId; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "form_type") + private String formType; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleRegister.java b/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleRegister.java index abe8313a..4a6226b4 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleRegister.java +++ b/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleRegister.java @@ -1,13 +1,18 @@ package com.iemr.flw.domain.iemr; +import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; import jakarta.persistence.*; +import org.springframework.web.multipart.MultipartFile; + import java.sql.Timestamp; +import java.util.List; @Entity @Table(name = "t_eligible_couple_register", schema = "db_iemr") @Data +@JsonInclude(JsonInclude.Include.ALWAYS) // Null values included public class EligibleCoupleRegister { @Id @@ -157,4 +162,22 @@ public class EligibleCoupleRegister { @Column(name = "updated_by") private String updatedBy; + + + @Column(name = "lmp_date") + private String lmpDate; + + @Column(name = "is_kit_handed_over") + private Boolean isKitHandedOver; + + @Column(name = "is_kit_handed_over_date") + private String kitHandedOverDate; + + @Lob + @Column(name = "kit_photo1", columnDefinition = "LONGTEXT") + private String kitPhoto1; + + @Column(name = "kit_photo2", columnDefinition = "LONGTEXT") + private String kitPhoto2; } + diff --git a/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleTracking.java b/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleTracking.java index 2cde9438..99b8b511 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleTracking.java +++ b/src/main/java/com/iemr/flw/domain/iemr/EligibleCoupleTracking.java @@ -3,6 +3,7 @@ import lombok.Data; import jakarta.persistence.*; + import java.sql.Timestamp; @Entity @@ -49,4 +50,26 @@ public class EligibleCoupleTracking { @Column(name = "updated_by") private String updatedBy; + + + @Column(name = "lmp_date") + private String lmpDate; + + @Column(name = "date_of_antra_injection") + private Timestamp dateOfAntraInjection; + + @Column(name = "due_date_of_antra_injection") + private String dueDateOfAntraInjection; + + @Column(name = "mpa_file") + private String mpaFile; + + @Column(name = "antra_dose") + private String antraDose; + + @Column(name = "discharge_summary1") + private String dischargeSummary1; + + @Column(name = "discharge_summary2") + private String dischargeSummary2; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/EyeCheckupVisit.java b/src/main/java/com/iemr/flw/domain/iemr/EyeCheckupVisit.java new file mode 100644 index 00000000..c15e8410 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/EyeCheckupVisit.java @@ -0,0 +1,54 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; +@Data +@Entity +@Table(name = "t_eye_checkup",schema = "db_iemr") +public class EyeCheckupVisit { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Column(name = "household_id") + private Long householdId; + + @Column(name = "visit_date") + private LocalDate visitDate; + + @Column(name = "symptoms_observed") + private String symptomsObserved; + + @Column(name = "eye_affected") + private String eyeAffected; + + @Column(name = "referred_to") + private String referredTo; + + @Column(name = "follow_up_status") + private String followUpStatus; + + @Column(name = "date_of_surgery") + private String dateOfSurgery; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "discharge_summary_upload") + private String dischargeSummaryUpload; + + @Column(name = "created_date") + private LocalDateTime createdDate = LocalDateTime.now(); + + @Column(name = "updated_date") + private LocalDateTime updatedDate = LocalDateTime.now(); +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java new file mode 100644 index 00000000..7e0916bd --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java @@ -0,0 +1,66 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Table(name = "campaign_filariasis_mda",schema = "db_iemr") +@Data +public class FilariasisCampaign { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "start_date", nullable = false) + private LocalDate startDate; + + @Column(name = "end_date", nullable = false) + private LocalDate endDate; + + @Column(name = "user_id", nullable = false) + private Integer userId; + + @Column(name = "number_of_families", nullable = false) + private Integer numberOfFamilies = 0; + + @Column(name = "number_of_individuals", nullable = false) + private Integer numberOfIndividuals = 0; + + /** + * Store JSON array like ["img1.jpg","img2.jpg"] + * MySQL JSON column + */ + @Column(name = "campaign_photos", columnDefinition = "json") + private String campaignPhotos; + + @Column(name = "created_by", length = 200) + private String createdBy; + + @Column(name = "updated_by", length = 200) + private String updatedBy; + + @Column(name = "created_date", updatable = false) + private LocalDateTime createdDate; + + @Column(name = "updated_date") + private LocalDateTime updatedDate; + + /* ---------- Auto timestamps ---------- */ + + @PrePersist + protected void onCreate() { + this.createdDate = LocalDateTime.now(); + this.updatedDate = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedDate = LocalDateTime.now(); + } + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdData.java b/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdData.java new file mode 100644 index 00000000..f2d81f18 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdData.java @@ -0,0 +1,224 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* @@ -0,0 +1,212 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ + +package com.iemr.flw.domain.iemr; + +import java.sql.Timestamp; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; + +import com.google.gson.annotations.Expose; +import lombok.Data; + +@Data +@Entity +@Table(name = "i_ben_flow_outreach") +public class GeneralOpdData { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Expose + @Column(name = "ben_flow_id") + private Long benFlowID; + + @Expose + @Column(name = "beneficiary_reg_id") + private Long beneficiaryRegID; + + @Expose + @Column(name = "beneficiary_visit_id") + private Long benVisitID; + + @Expose + @Column(name = "beneficiary_visit_code") + private Long visitCode; + + @Expose + @Column(name = "visit_reason") + private String VisitReason; + + @Expose + @Column(name = "visit_category") + private String VisitCategory; + + @Expose + @Column(name = "visit_no") + private Short benVisitNo; + + @Expose + @Column(name = "nurse_flag") + private Short nurseFlag; + + @Expose + @Column(name = "doctor_flag") + private Short doctorFlag; + + @Expose + @Column(name = "pharmacist_flag") + private Short pharmacist_flag; + + @Expose + @Column(name = "lab_technician_flag") + private Short lab_technician_flag; + + @Expose + @Column(name = "radiologist_flag") + private Short radiologist_flag; + + @Expose + @Column(name = "oncologist_flag") + private Short oncologist_flag; + + @Expose + @Column(name = "specialist_flag") + private Short specialist_flag; + + @Expose + @Column(name = "TC_SpecialistLabFlag") + private Short tC_SpecialistLabFlag; + + @Expose + @Column(name = "created_by") + private String agentId; + + @Expose + @Column(name = "created_date", insertable = false, updatable = false) + private Timestamp visitDate; + + @Expose + @Column(name = "modified_by") + private String modified_by; + + @Expose + @Column(name = "modified_date", insertable = false) + private Timestamp modified_date; + + @Expose + @Column(name = "ben_name") + private String benName; + + @Expose + @Column(name = "deleted", insertable = false) + private Boolean deleted; + + @Transient + private String firstName; + @Transient + private String lastName; + + @Expose + @Column(name = "ben_age") + private String age; + + @Expose + @Column(name = "ben_age_val") + private Integer ben_age_val; + + @Expose + @Column(name = "ben_dob") + private Timestamp dOB; + + @Expose + @Column(name = "ben_gender_val") + private Short genderID; + @Expose + @Column(name = "ben_gender") + private String genderName; + @Expose + @Column(name = "ben_phone_no") + private String preferredPhoneNum; + @Expose + @Column(name = "father_name") + private String fatherName; +// @Expose +// @Column(name = "benQuickbloxID") +// private Long benQuickbloxID; + @Expose + @Column(name = "spouse_name") + private String spouseName; + + @Expose + @Column(name = "district") + private String districtName; + @Expose + @Column(name = "servicePoint") + private String servicePointName; + + @Expose + @Column(name = "registrationDate") + private Timestamp registrationDate; + + @Expose + @Column(name = "visitDate") + private Timestamp benVisitDate; + + @Expose + @Column(name = "consultationDate") + private Timestamp consultationDate; + + @Expose + @Column(name = "consultantID") + private Integer consultantID; + + @Expose + @Column(name = "consultantName") + private String consultantName; + + @Expose + @Column(name = "visitSession") + private Integer visitSession; + + @Expose + @Column(name = "servicePointID") + private Integer servicePointID; + + @Expose + @Column(name = "districtID") + private Integer districtID; + + @Expose + @Column(name = "villageID") + private Integer villageID; + + @Expose + @Column(name = "vanID") + private Integer vanID; + + @Expose + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Expose + @Column(name = "village") + private String village; + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdEntry.java b/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdEntry.java new file mode 100644 index 00000000..2e68c9fe --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/GeneralOpdEntry.java @@ -0,0 +1,45 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +@Entity +@Data +@Table(name = "general_opd_entry") // Updated table name +public class GeneralOpdEntry { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "asha_id") + private String ashaId; + + @Column(name = "name") + private String name; + + @Column(name = "age") + private String age; + + @Column(name = "gender") + private String gender; + + @Column(name = "registration_date") + private String registrationDate; + + @Column(name = "mobile_number") + private String mobileNumber; + + @Column(name = "beneficiary_id") + private String beneficiaryId; + + @Column(name = "visit_date") + private String visitDate; + + @Column(name = "referred_to") + private String referredTo; + + @Column(name = "follow_up_date") + private String followUpDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/HbncVisit.java b/src/main/java/com/iemr/flw/domain/iemr/HbncVisit.java index b543e764..1513c088 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/HbncVisit.java +++ b/src/main/java/com/iemr/flw/domain/iemr/HbncVisit.java @@ -1,8 +1,10 @@ package com.iemr.flw.domain.iemr; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.google.gson.annotations.SerializedName; import lombok.Data; - import jakarta.persistence.*; + import java.sql.Timestamp; @Entity @@ -12,134 +14,97 @@ public class HbncVisit { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") private Long id; - @Column(name = "ben_id") - private Long benId; - - @Column(name = "visit_no") - private Integer visitNo; - - @Column(name = "visit_date") - private Timestamp dateOfVisit; - - @Column(name = "baby_alive") - private Boolean babyAlive; + @Column(name = "asha_id") + private Integer ashaId; - @Column(name = "num_times_full_meal") - private Integer numTimesFullMeal24hr; + @Column(name = "ben_id") + private Long beneficiaryId; - @Column(name = "num_pad_changed") - private Integer numPadChanged24hr; + @Column(name = "household_id") + private Long houseHoldId; - @Column(name = "baby_kept_warm") - private Boolean babyKeptWarmWinter; + @Column(name = "hbnc_visit_day") + private String visit_day; - @Column(name = "baby_fed_properly") - private Boolean babyFedProperly; + @Column(name = "hbnc_due_date") + private String due_date; - @Column(name = "baby_cry_continuously") - private Boolean babyCryContinuously; + @Column(name = "visit_date") + private String visit_date; - @Column(name = "mother_temp") - private Integer motherTemperature; + @Column(name = "baby_alive") + private Boolean is_baby_alive ; - @Column(name = "foul_discharge") - private Boolean foulDischargeFever; + @Column(name = "date_of_death") + private String date_of_death; - @Column(name = "mother_speaks_abnormally") - private Boolean motherSpeakAbnormallyFits; + @Column(name = "reason_for_death") + private String reasonForDeath; - @Column(name = "mother_less_no_milk") - private Boolean motherLessNoMilk; + @Column(name = "place_of_death") + private String place_of_death; - @Column(name = "mother_breast_problem") - private Boolean motherBreastProblem; - - @Column(name = "baby_eyes_swollen") - private Boolean babyEyesSwollen; + @Column(name = "other_place_of_death") + private String other_place_of_death; @Column(name = "baby_weight") - private Float babyWeight; - - @Column(name = "baby_temp") - private Integer babyTemperature; + private Double baby_weight; - @Column(name = "baby_yellow") - private Boolean babyYellow; + @Column(name = "urine_passed") + private Boolean urine_passed; - @Column(name = "baby_immunization_status") - private String babyImmunizationStatus; + @Column(name = "stool_passed") + private Boolean stool_passed; - @Column(name = "baby_referred") - private Boolean babyReferred; + @Column(name = "diarrhoea") + private Boolean diarrhoea; - @Column(name = "baby_referral_date") - private Timestamp dateOfBabyReferral; + @Column(name = "vomiting") + private Boolean vomiting; - @Column(name = "baby_referral_place") - private String placeOfBabyReferral; + @Column(name = "convulsions") + private Boolean convulsions; - @Column(name = "baby_referral_place_other") - private String otherPlaceOfBabyReferral; + @Column(name = "activity") + private String activity; - @Column(name = "mother_referred") - private Boolean motherReferred; + @Column(name = "sucking") + private String sucking; - @Column(name = "mother_referral_date") - private Timestamp dateOfMotherReferral; + @Column(name = "breathing") + private String breathing; - @Column(name = "mother_referral_place") - private String placeOfMotherReferral; + @Column(name = "chest_indrawing") + private String chest_indrawing; - @Column(name = "mother_referral_place_other") - private String otherPlaceOfMotherReferral; + @Column(name = "temperature") + private String temperature; - @Column(name = "all_limbs_limp") - private Boolean allLimbsLimp; + @Column(name = "jaundice") + private Boolean jaundice; - @Column(name = "feeding_less_stopped") - private Boolean feedingLessStopped; + @Column(name = "umbilical_stump_condition") + private String umbilical_stump; - @Column(name = "crt_weak_stopped") - private Boolean cryWeakStopped; + @Column(name = "baby_discharged_from_sncu") + private Boolean discharged_from_sncu; - @Column(name = "bloated_stomach") - private Boolean bloatedStomach; - - @Column(name = "cold_on_touch") - private Boolean coldOnTouch; - - @Column(name = "chest_drawing") - private Boolean chestDrawing; - - @Column(name = "breath_fast") - private Boolean breathFast; - - @Column(name = "pus_navel") - private String pusNavel; - - @Column(name = "supervisor") - private String supervisor; - - @Column(name = "supervisor_name") - private String supervisorName; - - @Column(name = "supervisor_comment") - private String supervisorComment; - - @Column(name = "supervisor_sign_date") - private Timestamp supervisorSignDate; + @Column(name = "discharge_summary_image") + private String discharge_summary_upload; @Column(name = "created_by") private String createdBy; + @Column(name = "updated_by") + private String updatedBy; + @Column(name = "created_date") private Timestamp createdDate; - @Column(name = "updated_date") - private Timestamp updatedDate; + @Column(name = "baby_eyes_swollen") + private Boolean babyEyesSwollen; - @Column(name = "updated_by") - private String updatedBy; -} +}; diff --git a/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java b/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java new file mode 100644 index 00000000..205716cc --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java @@ -0,0 +1,134 @@ +package com.iemr.flw.domain.iemr; + +import com.google.gson.annotations.SerializedName; +import jakarta.persistence.*; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import lombok.Data; +import org.hibernate.annotations.Type; + +@Entity +@Data +@Table(name = "t_hbyc_child_visits",schema = "db_iemr") +public class HbycChildVisit { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Column(name = "household_id") + private Long household_id; + + @Column(name = "visit_day") + private String visit_day; // 3 Months, 6 Months, etc. + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "hbyc_due_date") + private String hbyc_due_date; + + @Column(name = "hbyc_visit_date") + private String visit_date; + + @Column(name = "is_baby_alive") + private Boolean is_baby_alive = true; + + @Column(name = "date_of_death") + private String date_of_death; + + @Column(name = "reason_for_death") + private String reason_for_death; + + @Column(name = "place_of_death") + private String place_of_death; + + @Column(name = "other_place_of_death") + private String other_place_of_death; + + @Column(name = "baby_weight") + private Integer baby_weight; // 0.5 - 7.0 + + @Column(name = "is_child_sick") + private Boolean is_child_sick; + + @Column(name = "is_exclusive_breastfeeding") + private Boolean exclusive_breastfeeding; + + @Column(name = "is_mother_counseled_exbf") + private Boolean mother_counseled_ebf; + + @Column(name = "has_child_started_complementary_feeding") + private Boolean has_child_started_complementary_feeding; + + @Column(name = "is_mother_counseled_cf") + private Boolean mother_counseled_cf; + + @Column(name = "is_weight_recorded_by_aww") + private Boolean weight_recorded; + + @Column(name = "is_developmental_delay") + private Boolean developmental_delay; + + @Column(name = "is_measles_vaccine_given") + private Boolean measles_vaccine; + + @Column(name = "is_vitamin_a_given") + private Boolean vitamin_a; + + @Column(name = "is_ors_available") + private Boolean ors_available; + + @Column(name = "is_ifa_syrup_available") + private Boolean Ifa_available; + + @Column(name = "is_ors_given") + private Boolean ors_given; + + @Column(name = "is_ifa_syrup_given") + private Boolean ifa_given; + + @Column(name = "is_handwashing_counseling_given") + private Boolean handwash_counseling; + + @Column(name = "is_parenting_counseling_given") + private Boolean parenting_counseling; + + @Column(name = "is_family_planning_counseling_given") + private Boolean family_planning_counseling; + + @Column(name = "diarrhoea_episode") + private Boolean diarrhoea_episode; + + @Column(name = "pneumonia_symptoms") + private Boolean pneumonia_symptoms; + + @Column(name = "temperature") + private BigDecimal temperature; + + @Column(name = "mcp_card_images", columnDefinition = "json") + private List mcp_card_images; + + @Column(name = "created_at") + private LocalDateTime created_at = LocalDateTime.now(); + + @Column(name = "updated_at") + private LocalDateTime updated_at = LocalDateTime.now(); + + @Column(name = "created_by") + private String created_by; + + @Column(name = "is_breathing_difficulty") + private Boolean breathing_difficulty; + + @Column(name = "is_complementary_feeding") + private Boolean complementary_feeding; + + // Getters and Setters +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/IFAFormSubmissionData.java b/src/main/java/com/iemr/flw/domain/iemr/IFAFormSubmissionData.java new file mode 100644 index 00000000..42826902 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/IFAFormSubmissionData.java @@ -0,0 +1,65 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "t_ifa_distribution_data",schema = "db_iemr") + + public class IFAFormSubmissionData { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id", nullable = false) + private Integer userId; + + @Column(name = "beneficiary_id", nullable = false) + private Long beneficiaryId; + + @Column(name = "household_id") + private Long houseHoldId; + + @Column(name = "user_name", nullable = false) + private String userName; + + @Column(name = "visit_date") + private String visitDate; + + @Column(name = "form_id") + private String formId; + + @Column(name = "ifa_provided") + private String ifaProvided; + + @Column(name = "ifa_quantity") + private String ifaQuantity; + + @Column(name = "created_at", updatable = false) + private LocalDateTime createdAt; + + @Column(name = "updated_at") + private LocalDateTime updatedAt; + + @PrePersist + public void onCreate() { + this.createdAt = LocalDateTime.now(); + this.updatedAt = LocalDateTime.now(); + } + + @PreUpdate + public void onUpdate() { + this.updatedAt = LocalDateTime.now(); + } + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java b/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java new file mode 100644 index 00000000..6f3143e0 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java @@ -0,0 +1,37 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigInteger; +import java.sql.Date; +import java.time.LocalDate; + +@Entity +@Data +@Table(name = "irs_round", schema = "db_iemr") +@AllArgsConstructor +@NoArgsConstructor +public class IRSRound { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "irs_date") + private LocalDate date; + + @Column(name = "round") + private int rounds; + + @Column(name = "householdId") + private Long householdId; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "user_id") + private Integer userId; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/IfaDistribution.java b/src/main/java/com/iemr/flw/domain/iemr/IfaDistribution.java new file mode 100644 index 00000000..c6b61354 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/IfaDistribution.java @@ -0,0 +1,42 @@ +package com.iemr.flw.domain.iemr; + +import com.google.gson.annotations.SerializedName; +import jakarta.persistence.*; +import lombok.Data; +import org.checkerframework.checker.units.qual.C; + +import java.time.LocalDate; + +@Entity +@Table(name = "t_ifa_distribution") +@Data +public class IfaDistribution { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "house_hold_id") + private Long houseHoldId; + + @Column(name = "form_id") + private String formId; + + @Column(name = "visit_date") + private String visitDate; // kept as String because "N/A" possible + + @Column(name = "ifa_provision_date") + private LocalDate ifaProvisionDate; + + @Column(name = "mcp_card_upload", columnDefinition = "TEXT") + private String mcpCardUpload; + + @Column(name = "ifa_bottle_count") + private String ifaBottleCount; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java index 8972c331..b5c039f5 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java @@ -4,9 +4,10 @@ import jakarta.persistence.*; import java.sql.Timestamp; +import java.util.Date; @Entity -@Table(name = "incentive_activity", schema = "db_iemr") +@Table(name = "m_incentive_activity", schema = "db_iemr") @Data public class IncentiveActivity { @@ -35,6 +36,7 @@ public class IncentiveActivity { @Column(name = "group_name") private String group; + @Column(name = "fmr_code") private String fmrCode; @@ -55,4 +57,6 @@ public class IncentiveActivity { @Column(name = "is_deleted") private Boolean isDeleted; + + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityLangMapping.java b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityLangMapping.java new file mode 100644 index 00000000..0c81338c --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityLangMapping.java @@ -0,0 +1,47 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.sql.Timestamp; + +@Entity +@Data +@Table(name = "m_incentive_activity_lang_mapping",schema = "db_iemr") +public class IncentiveActivityLangMapping { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "activity_name") + private String name; + + @Column(name = "activity_description") + private String description; + + @Column(name = "payment_parameter") + private String paymentParam; + + @Column(name = "rate_per_activity") + private Integer rate; + + @Column(name = "group_name") + private String group; + + + @Column(name = "created_date") + private Timestamp createdDate; + + + @Column(name = "updated_date") + private Timestamp updatedDate; + + @Column(name = "assame_activity_description") + private String assameActivityDescription; + + @Column(name = "hindi_activity_description") + private String hindiActivityDescription; + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java index 5b921bb4..f4adf8df 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -46,4 +46,10 @@ public class IncentiveActivityRecord { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "is_eligible") + private Boolean isEligible; + + @Column(name = "is_default_activity") + private Boolean isDefaultActivity; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java b/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java new file mode 100644 index 00000000..870a48f5 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java @@ -0,0 +1,39 @@ +package com.iemr.flw.domain.iemr; + +import java.util.Date; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "incentive_pending_activity", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class IncentivePendingActivity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "activity_id", nullable = false) + private Long activityId; + + @Column(name = "record_id", nullable = false) + private Long recordId; + + @Column(name = "module_name", nullable = false, length = 100) + private String moduleName; + + @Column(name = "user_id", nullable = false) + private Integer userId; + + @Column(name = "created_date") + private Date createdDate; + + @Column(name = "updated_date") + private Date updatedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/InfantRegister.java b/src/main/java/com/iemr/flw/domain/iemr/InfantRegister.java index 7d6ae835..7a22516f 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/InfantRegister.java +++ b/src/main/java/com/iemr/flw/domain/iemr/InfantRegister.java @@ -85,4 +85,19 @@ public class InfantRegister { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "delivery_discharge_summary1") + private String deliveryDischargeSummary1; + + @Column(name = "delivery_discharge_summary2") + private String deliveryDischargeSummary2; + + @Column(name = "delivery_discharge_summary3") + private String deliveryDischargeSummary3; + + @Column(name = "delivery_discharge_summary4") + private String deliveryDischargeSummary4; + + @Column(name = "is_sncu") + private String isSNCU; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/LeprosyFollowUp.java b/src/main/java/com/iemr/flw/domain/iemr/LeprosyFollowUp.java new file mode 100644 index 00000000..5e0d78f0 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/LeprosyFollowUp.java @@ -0,0 +1,90 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.sql.Timestamp; +import java.util.Date; + +@Entity +@Table(name = "leprosy_follow_up", schema = "db_iemr") +@Data +public class LeprosyFollowUp { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "visit_number") + private Integer visitNumber; + + @Temporal(TemporalType.DATE) + @Column(name = "follow_up_date") + private Date followUpDate; + + @Column(name = "treatment_status", length = 100) + private String treatmentStatus; + + @Column(name = "mdt_blister_pack_received", length = 100) + private String mdtBlisterPackReceived; + + @Temporal(TemporalType.DATE) + @Column(name = "treatment_complete_date") + private Date treatmentCompleteDate; + + @Column(name = "remarks", columnDefinition = "TEXT") + private String remarks; + + @Temporal(TemporalType.DATE) + @Column(name = "home_visit_date") + private Date homeVisitDate; + + @Column(name = "leprosy_symptoms", length = 255) + private String leprosySymptoms; + + @Column(name = "type_of_leprosy", length = 100) + private String typeOfLeprosy; + + @Column(name = "leprosy_symptoms_position") + private Integer leprosySymptomsPosition; + + @Column(name = "visit_label", length = 100) + private String visitLabel; + + @Column(name = "leprosy_status", length = 100) + private String leprosyStatus; + + @Column(name = "referred_to", length = 255) + private String referredTo; + + @Column(name = "refer_to_name", length = 255) + private String referToName; + + @Temporal(TemporalType.DATE) + @Column(name = "treatment_end_date") + private Date treatmentEndDate; + + @Column(name = "mdt_blister_pack_recived", length = 100) + private String mdtBlisterPackRecived; + + @Temporal(TemporalType.DATE) + @Column(name = "treatment_start_date") + private Date treatmentStartDate; + + // Audit fields + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "created_date") + private Timestamp createdDate; + + @Column(name = "modified_by", length = 100) + private String modifiedBy; + + @Column(name = "last_mod_date") + private Timestamp lastModDate; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/MDSR.java b/src/main/java/com/iemr/flw/domain/iemr/MDSR.java index f25b1956..301fdd91 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MDSR.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MDSR.java @@ -54,4 +54,13 @@ public class MDSR { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "mdsr1_file") + private String mdsr1File; + + @Column(name = "mdsr2_file") + private String mdsr2File; + + @Column(name = "mdsr_death_cert_file") + private String mdsrDeathCertFile; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/M_User.java b/src/main/java/com/iemr/flw/domain/iemr/M_User.java index c57fc9fe..0187a613 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/M_User.java +++ b/src/main/java/com/iemr/flw/domain/iemr/M_User.java @@ -3,6 +3,7 @@ import java.sql.Timestamp; import java.time.LocalDate; +import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.Expose; import jakarta.persistence.Column; @@ -13,136 +14,144 @@ import jakarta.persistence.Table; import lombok.Data; +import com.google.gson.annotations.Expose; +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Date; +import java.sql.Timestamp; +import java.time.LocalDate; + @Entity -@Table(name = "m_User",schema = "db_iemr") +@Table(name = "m_User", schema = "db_iemr") @Data public class M_User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Expose - @Column(name="UserID") + @Column(name = "UserID") private Integer userID; @Expose - @Column(name="TitleID") + @Column(name = "TitleID") private Integer titleID; @Expose - @Column(name="FirstName") + @Column(name = "FirstName") private String firstName; @Expose - @Column(name="MiddleName") + @Column(name = "MiddleName") private String middleName; @Expose - @Column(name="LastName") + @Column(name = "LastName") private String lastName; @Expose - @Column(name="GenderID") + @Column(name = "GenderID") private Short genderID; @Expose - @Column(name="MaritalStatusID") + @Column(name = "MaritalStatusID") private Integer maritalStatusID; @Expose - @Column(name="DesignationID") + @Column(name = "DesignationID") private Integer designationID; @Expose - @Column(name="AadhaarNo") + @Column(name = "AadhaarNo") private String aadhaarNo; @Expose - @Column(name="PAN") + @JsonProperty("pan") + @Column(name = "PAN") private String pAN; @Expose - @Column(name="DOB") - private LocalDate dOB; + @JsonProperty("dob") + @Column(name = "DOB") + private Timestamp dOB; @Expose - @Column(name="DOJ") - private LocalDate dOJ; + @JsonProperty("doj") + @Column(name = "DOJ") + private Timestamp dOJ; @Expose - @Column(name="QualificationID") + @Column(name = "QualificationID") private Integer qualificationID; @Expose - @Column(name="HealthProfessionalID") + @Column(name = "HealthProfessionalID") private String healthProfessionalID; @Expose - @Column(name="UserName") + @Column(name = "UserName") private String userName; @Expose - @Column(name="Password") + @Column(name = "Password") private String password; @Expose - @Column(name="IsExternal") + @Column(name = "IsExternal") private Boolean isExternal; @Expose - @Column(name="AgentID") + @Column(name = "AgentID") private String agentID; @Expose - @Column(name="AgentPassword") + @Column(name = "AgentPassword") private String agentPassword; @Expose - @Column(name="EmailID") + @Column(name = "EmailID") private String emailID; @Expose - @Column(name="StatusID") + @Column(name = "StatusID") private Integer statusID; @Expose - @Column(name="EmergencyContactPerson") + @Column(name = "EmergencyContactPerson") private String emergencyContactPerson; @Expose - @Column(name="EmergencyContactNo") + @Column(name = "EmergencyContactNo") private String emergencyContactNo; @Expose - @Column(name="IsSupervisor") + @Column(name = "IsSupervisor") private Boolean isSupervisor; @Expose - @Column(name="Deleted",insertable = false, updatable = true) + @Column(name = "Deleted", insertable = false, updatable = true) private Boolean deleted; @Expose - @Column(name="CreatedBy") + @Column(name = "CreatedBy") private String createdBy; @Expose - @Column(name="EmployeeID") + @Column(name = "EmployeeID") private String employeeID; @Expose - @Column(name="CreatedDate",insertable = false, updatable = false) + @Column(name = "CreatedDate", insertable = false, updatable = false) private Timestamp createdDate; @Expose - @Column(name="ModifiedBy") + @Column(name = "ModifiedBy") private String modifiedBy; @Expose - @Column(name="LastModDate",insertable = false, updatable = false) + @Column(name = "LastModDate", insertable = false, updatable = false) private Timestamp lastModDate; @Expose - @Column(name="Remarks") + @Column(name = "Remarks") private String remarks; @Expose - @Column(name="ContactNo") + @Column(name = "ContactNo") private String contactNo; - @Expose - @Column(name="IsProviderAdmin") + @Column(name = "IsProviderAdmin") private Boolean isProviderAdmin; @Expose - @Column(name="ServiceProviderID") + @Column(name = "ServiceProviderID") private Integer serviceProviderID; - - @Expose @Column(name = "failed_attempt", insertable = false) private Integer failedAttempt; + public M_User() { // TODO Auto-generated constructor stub } public M_User(Integer userID, String userName) { // TODO Auto-generated constructor stub - this.userID=userID; - this.userName=userName; + this.userID = userID; + this.userName = userName; } } diff --git a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java new file mode 100644 index 00000000..0e843714 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java @@ -0,0 +1,57 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Entity +@Data +@Table(name = "maa_meeting", schema = "db_iemr") +public class MaaMeeting { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "meeting_date") + private LocalDate meetingDate; + + @Column(name = "place") + private String place; + + @Column(name = "participants") + private Integer participants; + + @Column(name = "quarter") + private Integer quarter; + + @Column(name = "year") + private Integer year; + + @Column(name = "asha_id") + private Integer ashaId; + + // Store multiple images as JSON of base64 strings + @Lob + @Column(name = "meeting_images", columnDefinition = "LONGTEXT") + private String meetingImagesJson; + + @Column(name = "village_name") + private String villageName; + + @Column(name = "no_of_pragnent_women") + private Integer noOfPragnentWomen; + + @Column(name = "no_of_lacting_mother") + private Integer noOfLactingMother; + + @Column(name = "mitanin_activity_checkList") + private String mitaninActivityCheckList; + + @Column(name = "created_by") + private String createdBy; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java b/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java new file mode 100644 index 00000000..cd7384e1 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java @@ -0,0 +1,50 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.util.Date; + +@Entity +@Table(name = "malaria_follow_up", schema = "db_iemr") +@Data +public class MalariaFollowUp { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "ben_id", nullable = false) + private Long benId; + + @Column(name = "house_hold_details_id", nullable = false) + private Long houseHoldDetailsId; + + @Column(name = "user_Id") + private Integer userId; + + @Column(name = "disease_Id", nullable = false) + private Long diseaseId; + + @Column(name = "date_of_diagnosis", nullable = false) + @Temporal(TemporalType.DATE) + private Date dateOfDiagnosis; + + @Column(name = "treatment_start_date", nullable = false) + @Temporal(TemporalType.DATE) + private Date treatmentStartDate; + + @Column(name = "treatment_given", nullable = false) + private String treatmentGiven; + + @Column(name = "days", nullable = false) + private String day; + + @Column(name = "treatment_completion_date") + @Temporal(TemporalType.DATE) + private Date treatmentCompletionDate; + + @Column(name = "referral_date") + @Temporal(TemporalType.DATE) + private Date referralDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/MdaDistributionData.java b/src/main/java/com/iemr/flw/domain/iemr/MdaDistributionData.java new file mode 100644 index 00000000..34c7a63e --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/MdaDistributionData.java @@ -0,0 +1,60 @@ +package com.iemr.flw.domain.iemr; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import jakarta.persistence.*; +import org.springframework.data.annotation.CreatedDate; + +import java.sql.Date; +import java.sql.Timestamp; + +@Data +@Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "t_mda_distribution_data", schema = "db_iemr") +public class MdaDistributionData { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Long id; + + @Column(name = "BeneficiaryId") + private Long beneficiaryId; + + @Column(name = "HouseHoldId", nullable = false) + private Long houseHoldId; + + @Column(name = "FormId") + private String formId; + + + @Column(name = "VisitDate") + private Timestamp visitDate; + + @Column(name = "UserName") + private String userName; + + @Column(name = "MdaDistributionDate") + private Timestamp mdaDistributionDate; + + @Column(name = "IsMedicineDistributed") + private String isMedicineDistributed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate") + @CreatedDate + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate") + private Timestamp lastModDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/MicroBirthPlan.java b/src/main/java/com/iemr/flw/domain/iemr/MicroBirthPlan.java new file mode 100644 index 00000000..9b145899 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/MicroBirthPlan.java @@ -0,0 +1,69 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.math.BigInteger; + +@Entity +@Table(name = "t_micro_birth_plan", schema = "db_iemr") +@Data +public class MicroBirthPlan { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "contact_no_1", length = 10) + private String contactNumber1; // Auto-filled, must be 10 digits, starts with 6-9 + + @Column(name = "contact_no_2", length = 10) + private String contactNumber2; // Optional, 10 digits, starts with 6-9 + + @Column(name = "sc_hwc_tg_hosp", length = 100) + private String scHosp; // Alphanumeric, all caps + + @Column(name = "block", length = 100) + private String block; // Alphanumeric, all caps + + + @Column(name = "nearest_sc_hwc", length = 100) + private String nearestSc; // Alphanumeric, all caps + + @Column(name = "nearest_phc", length = 100) + private String nearestPhc; // Alphanumeric, all caps + + @Column(name = "nearest_fru", length = 100) + private String nearestFru; // Alphanumeric, all caps + + @Column(name = "nearest_usg", length = 100) + private String usg; // Alphanumeric, all caps + + @Column(name = "blood_group") + private String bloodGroup; // Spinner: A+, B+, etc. + + @Column(name = "blood_donors", length = 50) + private String bloodDonors2; // Alphabets only, all caps + + @Column(name = "birth_companion", length = 50) + private String birthCompanion; // Alphabets only, all caps + + @Column(name = "child_caretaker", length = 50) + private String careTaker; // Alphabets only, all caps + + @Column(name = "community_support", length = 100) + private String communityMember; // Alphabets only, all caps + + @Column(name = "community_support_contact", length = 100) + private String communityMemberContact; // Alphabets only, all caps + + @Column(name = "transportation_mode", length = 100) + private String modeOfTransportation; // Mode of transport + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java b/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java new file mode 100644 index 00000000..9444d1af --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java @@ -0,0 +1,33 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; + +@Entity +@Data +@Table(name = "i_mobilization_mosquito_net",schema = "db_iemr") +public class MosquitoNetEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @Column(name = "beneficiary_id") + private Long beneficiaryId; + @Column(name = "household_id") + private Long houseHoldId; + @Column(name = "visit_date") + private LocalDate visitDate; + + @Column(name = "user_name") + private String userName; + + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "is_net_distributed") + private String isNetDistributed; + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/OrsDistribution.java b/src/main/java/com/iemr/flw/domain/iemr/OrsDistribution.java new file mode 100644 index 00000000..e5603dee --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/OrsDistribution.java @@ -0,0 +1,42 @@ +package com.iemr.flw.domain.iemr; + +import io.swagger.v3.oas.annotations.tags.Tags; +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; + +@Table(name = "t_ors_distribution",schema = "db_iemr") +@Entity +@Data +public class OrsDistribution { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "household_id") + private Long householdId; + + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "visit_date") + private LocalDate visitDate; + + @Column(name = "child_count") + private String childCount; + + @Column(name = "num_ors_packets") + private String numOrsPackets; + + + @Column(name = "created_at", updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") + private java.sql.Timestamp createdAt; + + @Column(name = "updated_at", insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP") + private java.sql.Timestamp updatedAt; + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/OtpBeneficiary.java b/src/main/java/com/iemr/flw/domain/iemr/OtpBeneficiary.java new file mode 100644 index 00000000..15a87bd0 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/OtpBeneficiary.java @@ -0,0 +1,33 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "m_otp_beneficiary", schema = "db_iemr") +@Data +public class OtpBeneficiary { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "beneficiaryId", nullable = false) + private Long beneficiaryId; + + @Column(name = "phoneNumber", nullable = false, length = 45) + private String phoneNumber; + + @Column(name = "isOtpVerify") + private Boolean isOtpVerify = false; + + @Column(name = "otp", nullable = false) + private Integer otp; + + @Column(name = "isExpired") + private Boolean isExpired = false; + + @Column(name = "createdAt", updatable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP") + private Timestamp createdAt; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java new file mode 100644 index 00000000..4dea0ce7 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java @@ -0,0 +1,60 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.sql.Timestamp; + +import static jakarta.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "phc_review_meeting", schema = "db_iemr") +@Data +public class PHCReviewForm { + + @Id + @GeneratedValue(strategy = IDENTITY) + private int id; + + @Column(name = "phc_review_date") + private String phcReviewDate; + + @Column(name = "place") + private String place; + + @Column(name = "no_of_beneficiaries_attended") + private Integer noOfBeneficiariesAttended; + + @Column(name = "image1") + private String image1; + + @Column(name = "image2") + private String image2; + + @Column(name = "user_id") + private Long userId; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "village_name ") + private String villageName; + + @Column(name = "mitanin_history") + private String mitaninHistory; + + @Column(name = "mitanin_activity_checkList") + private String mitaninActivityCheckList; + + @Column(name = "place_Id") + private Integer placeId; + + @Column(name = "form_type") + private String formType; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/PMSMA.java b/src/main/java/com/iemr/flw/domain/iemr/PMSMA.java index ed660f6b..f1320fee 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PMSMA.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PMSMA.java @@ -132,4 +132,13 @@ public class PMSMA { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "visitDate") + private Timestamp visitDate; + + @Column(name = "visitNo") + private Integer visitNumber; + + @Column(name = "anyOtherHighRiskCondition") + private String anyOtherHighRiskCondition; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/PNCVisit.java b/src/main/java/com/iemr/flw/domain/iemr/PNCVisit.java index 2ff6c24c..04eb6f4a 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PNCVisit.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PNCVisit.java @@ -79,4 +79,19 @@ public class PNCVisit { @Column(name = "updated_by") private String updatedBy; + + @Column(name = "steilisation_date") + private Timestamp sterilisationDate; + + @Column(name = "delivery_discharge_summary_image1") + private String deliveryDischargeSummary1; + + @Column(name = "delivery_discharge_summary_image2") + private String deliveryDischargeSummary2; + + @Column(name = "delivery_discharge_summary_image3") + private String deliveryDischargeSummary3; + + @Column(name = "delivery_discharge_summary_image4") + private String deliveryDischargeSummary4; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java new file mode 100644 index 00000000..ddf7b8b6 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java @@ -0,0 +1,60 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Table(name = "campaign_pulse_polio",schema = "db_iemr") +@Data +public class PulsePolioCampaign { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "start_date", nullable = false) + private LocalDate startDate; + + @Column(name = "end_date", nullable = false) + private LocalDate endDate; + + @Column(name = "user_id", nullable = false) + private Integer userId; + + @Column(name = "number_of_children", nullable = false) + private Integer numberOfChildren = 0; + + + @Column(name = "campaign_photos",columnDefinition = "LONGTEXT") + private String campaignPhotos; + + @Column(name = "created_by", length = 200) + private String createdBy; + + @Column(name = "updated_by", length = 200) + private String updatedBy; + + @Column(name = "created_date", updatable = false) + private LocalDateTime createdDate; + + @Column(name = "updated_date") + private LocalDateTime updatedDate; + + /* ---------- Auto timestamps ---------- */ + + @PrePersist + protected void onCreate() { + this.createdDate = LocalDateTime.now(); + this.updatedDate = LocalDateTime.now(); + } + + @PreUpdate + protected void onUpdate() { + this.updatedDate = LocalDateTime.now(); + } + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SMSTemplate.java b/src/main/java/com/iemr/flw/domain/iemr/SMSTemplate.java new file mode 100644 index 00000000..10ec7b82 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SMSTemplate.java @@ -0,0 +1,81 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.domain.iemr; + +import java.sql.Timestamp; +import java.util.List; + + +import com.google.gson.GsonBuilder; +import com.google.gson.LongSerializationPolicy; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToMany; +import jakarta.persistence.OneToOne; +import jakarta.persistence.Table; +import lombok.Data; + +@Entity +@Table(name = "m_smstemplate") +@Data +public class SMSTemplate +{ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "SMSTemplateID") + Integer smsTemplateID; + @Column(name = "SMSTemplateName") + String smsTemplateName; + @Column(name = "SMSTemplate") + String smsTemplate; + @Column(name = "dltTemplateId") + String dltTemplateId; + @Column(name = "SMSSenderName") + String smsSenderID; + @Column(name = "SMSTypeID") + Integer smsTypeID; + @Column(name = "ProviderServiceMapID") + Integer providerServiceMapID; + @Column(name = "Deleted", insertable = false, updatable = true) + Boolean deleted; + @Column(name = "CreatedBy", insertable = true, updatable = false) + String createdBy; + @Column(name = "CreatedDate", insertable = false, updatable = false) + Timestamp createdDate; + @Column(name = "ModifiedBy", insertable = false, updatable = true) + String modifiedBy; + @Column(name = "LastModDate", insertable = false, updatable = false) + Timestamp lastModDate; + + @Override + public String toString() { + + return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setLongSerializationPolicy(LongSerializationPolicy.STRING).serializeNulls() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create().toJson(this); + } + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SamVisit.java b/src/main/java/com/iemr/flw/domain/iemr/SamVisit.java new file mode 100644 index 00000000..56822609 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SamVisit.java @@ -0,0 +1,73 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.time.LocalDate; +import java.time.LocalDateTime; + +@Entity +@Data +@Table(name = "t_sam_visit", schema = "db_iemr") +public class SamVisit { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "beneficiary_id") + private Long beneficiaryId; + + @Column(name = "household_id") + private Long householdId; + + @Column(name = "visit_date") + private LocalDate visitDate; + + @Column(name = "visit_label") + private String visitLabel; + + @Column(name = "muac") + private String muac; + + @Column(name = "weight_for_height_status") + private String weightForHeightStatus; + + @Column(name = "is_child_referred_nrc") + private String isChildReferredNrc; + + @Column(name = "is_child_admitted_nrc") + private String isChildAdmittedNrc; + + @Column(name = "nrc_admission_date") + private String nrcAdmissionDate; + + @Column(name = "is_child_discharged_nrc") + private String isChildDischargedNrc; + + @Column(name = "nrc_discharge_date") + private String nrcDischargeDate; + + @Column(name = "follow_up_visit_date") + private String followUpVisitDate; + + @Column(name = "sam_status") + private String samStatus; + + @Column(name = "discharge_summary") + private String dischargeSummary; + + @Column(name = "view_discharge_docs") + private String viewDischargeDocs; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "created_date") + private LocalDateTime createdDate = LocalDateTime.now(); + + @Column(name = "updated_date") + private LocalDateTime updatedDate = LocalDateTime.now(); +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SamVisitResponseDTO.java b/src/main/java/com/iemr/flw/domain/iemr/SamVisitResponseDTO.java new file mode 100644 index 00000000..17eb15c2 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SamVisitResponseDTO.java @@ -0,0 +1,56 @@ +package com.iemr.flw.domain.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +@Data +public class SamVisitResponseDTO { + + @JsonProperty("beneficiary_id") + private Long beneficiaryId; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("visit_date") + private LocalDate visitDate; + + @JsonProperty("visit_label") + private String visitLabel; + + @JsonProperty("muac") + private Double muac; + + @JsonProperty("weight_for_height_status") + private String weightForHeightStatus; + + @JsonProperty("is_child_referred_nrc") + private String isChildReferredNrc; + + @JsonProperty("is_child_admitted_nrc") + private String isChildAdmittedNrc; + + @JsonProperty("nrc_admission_date") + private String nrcAdmissionDate; + + @JsonProperty("is_child_discharged_nrc") + private String isChildDischargedNrc; + + @JsonProperty("nrc_discharge_date") + private String nrcDischargeDate; + + @JsonProperty("follow_up_visit_date") + private List followUpVisitDate; + + @JsonProperty("sam_status") + private String samStatus; + + @JsonProperty("discharge_summary") + private String dischargeSummary; + + @JsonProperty("view_discharge_docs") + private List viewDischargeDocs; // Base64 array or JSON array +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SammelanAttachment.java b/src/main/java/com/iemr/flw/domain/iemr/SammelanAttachment.java new file mode 100644 index 00000000..e94dd2bc --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SammelanAttachment.java @@ -0,0 +1,28 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "sammelan_attachment") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SammelanAttachment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "sammelan_id", nullable = false) + private SammelanRecord sammelanRecord; + + + private String fileName; + private String fileType; + @Lob + private byte[] fileData; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/SammelanRecord.java b/src/main/java/com/iemr/flw/domain/iemr/SammelanRecord.java new file mode 100644 index 00000000..1ccc5bbd --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SammelanRecord.java @@ -0,0 +1,54 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "sammelan_record", + uniqueConstraints = @UniqueConstraint(name = "uk_asha_month", columnNames = {"asha_id", "meeting_date"})) +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SammelanRecord { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + + @Column(name = "asha_id", nullable = false) + private Integer ashaId; + + + @Column(name = "meeting_date", nullable = false) + private Timestamp meetingDate; + + + @Column(nullable = false) + private String place; + + + @Column(nullable = false, name = "participants") + private int participants; + + + @Column(columnDefinition = "TEXT", name = "remarks") + private String remarks; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "created_date") + private Timestamp createdDate = new Timestamp(System.currentTimeMillis()); + + @Lob + @Column(columnDefinition = "LONGTEXT",name = "attachments") + private String attachments; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningAesje.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningAesje.java new file mode 100644 index 00000000..372908f9 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningAesje.java @@ -0,0 +1,105 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.util.Date; + +@Entity +@Table(name = "screening_aesje", schema = "db_iemr") +@Data +public class ScreeningAesje { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "house_hold_details_Id",nullable = false) + private Long houseHoldDetailsId; + + @Temporal(TemporalType.DATE) + @Column(name = "visit_date") + private Date visitDate; + + @Column(name = "beneficiary_status") + private String beneficiaryStatus = "Not Applicable"; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_death") + private Date dateOfDeath; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "other_place_of_death") + private String otherPlaceOfDeath; + + @Column(name = "reason_for_death") + private String reasonForDeath; + + @Column(name = "other_reason_for_death") + private String otherReasonForDeath; + + @Column(name = "aes_je_case_status") + private String aesJeCaseStatus; + + @Column(name = "aes_je_case_count") + private Integer aesJeCaseCount = 0; + + @Column(name = "follow_up_point") + private Integer followUpPoint; + + @Column(name = "referred_to") + private String referredTo; + + @Column(name = "other_referred_facility") + private String otherReferredFacility; + + @Column(name = "created_date") + private Date createdDate = new Date(); + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "disease_type_id") + private Integer diseaseTypeId; + + @Column(name = "refer_to_name") + private String referToName; + + @Column(name = "beneficiary_status_id") + private Integer beneficiaryStatusId; + + // Getters and Setters +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningFilariasis.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningFilariasis.java new file mode 100644 index 00000000..e75cb046 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningFilariasis.java @@ -0,0 +1,86 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.util.Date; + +@Entity +@Table(name = "screening_filaria", schema = "db_iemr") +@Data +public class ScreeningFilariasis { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "house_hold_details_Id",nullable = false) + private Long houseHoldDetailsId; + + @Column(name = "suffering_from_filariasis") + private Boolean sufferingFromFilariasis; + + @Column(name = "affected_body_part", length = 50) + private String affectedBodyPart; + + @Temporal(TemporalType.DATE) + @Column(name = "mda_home_visit_date") + private Date mdaHomeVisitDate; + + @Column(name = "dose_status", length = 5) + private String doseStatus; + + @Column(name = "filariasis_case_count") + private Integer filariasisCaseCount; + + @Column(name = "other_dose_status_details", columnDefinition = "TEXT") + private String otherDoseStatusDetails; + + @Column(name = "medicine_side_effect", length = 5) + private String medicineSideEffect; + + @Column(name = "other_side_effect_details", columnDefinition = "TEXT") + private String otherSideEffectDetails; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "created_date") + private Date createdDate; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "disease_type_id") + private Integer diseaseTypeId; + + @Column(name = "user_id") + private Integer userId; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java new file mode 100644 index 00000000..d6bcd7b6 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java @@ -0,0 +1,111 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.util.Date; + +@Entity +@Table(name = "screening_kala_azar", schema = "db_iemr") +@Data +public class ScreeningKalaAzar { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "house_hold_details_Id",nullable = false) + private Long houseHoldDetailsId; + + @Column(name = "user_id") + private Integer userId; + + @Temporal(TemporalType.DATE) + @Column(name = "visit_date") + private Date visitDate; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_death") + private Date dateOfDeath; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "other_place_of_death") + private String otherPlaceOfDeath; + + @Column(name = "reason_for_death") + private String reasonForDeath; + + @Column(name = "other_reason_for_death") + private String otherReasonForDeath; + + @Column(name = "kala_azar_case_status") + private String kalaAzarCaseStatus; + + @Column(name = "kala_azar_case_count") + private Integer kalaAzarCaseCount; + + @Column(name = "rapid_diagnostic_test") + private String rapidDiagnosticTest; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_rdt") + private Date dateOfRdt; + + @Column(name = "follow_up_point") + private Integer followUpPoint; + + @Column(name = "referred_to") + private String referredTo; + + @Column(name = "other_referred_facility") + private String otherReferredFacility; + + @Temporal(TemporalType.DATE) + @Column(name = "created_date") + private Date createdDate; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "disease_type_id") + private Integer diseaseTypeId; + + @Column(name = "refer_to_name") + private String referToName; + + @Column(name = "beneficiary_statusId") + private Integer beneficiaryStatusId; + + @Column(name = "beneficiary_status") + private String beneficiaryStatus; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java new file mode 100644 index 00000000..6a485eef --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java @@ -0,0 +1,228 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; +import java.util.Date; + +@Entity +@Table(name = "screening_leprosy", schema = "db_iemr") +@Data +public class ScreeningLeprosy { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "house_hold_details_Id",nullable = false) + private Long houseHoldDetailsId; + + @Temporal(TemporalType.DATE) + @Column(name = "home_visit_date") + private Date homeVisitDate; + + @Column(name = "leprosy_status", length = 225) + private String leprosyStatus; + + @Column(name = "referred_to", length = 225) + private String referredTo; + + @Column(name = "other_referred_to", columnDefinition = "TEXT") + private String otherReferredTo; + + @Temporal(TemporalType.DATE) + @Column(name = "leprosy_status_date") + private Date leprosyStatusDate; + + @Column(name = "type_of_leprosy", length = 225) + private String typeOfLeprosy; + + @Temporal(TemporalType.DATE) + @Column(name = "follow_up_date") + private Date followUpDate; + + @Column(name = "remark", length = 225) + private String remark; + + @Column(name = "disease_type_id") + private Integer diseaseTypeId; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "refer_to_name") + private String referToName; + + @Column(name = "beneficiary_statusId") + private Integer beneficiaryStatusId; + + @Column(name = "beneficiary_status") + private String beneficiaryStatus; + + @Column(name = "date_of_death") + private Date dateOfDeath; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "other_place_of_death", columnDefinition = "TEXT") + private String otherPlaceOfDeath; + + @Column(name = "reason_for_death") + private String reasonForDeath; + + @Column(name = "other_reason_for_death", columnDefinition = "TEXT") + private String otherReasonForDeath; + + @Column(name = "leprosy_symptoms") + private String leprosySymptoms; + + @Column(name = "leprosy_symptoms_position") + private Integer leprosySymptomsPosition; + + @Column(name = "leprosy_status_position") + private Integer lerosyStatusPosition; + + @Column(name = "current_visit_number") + private Integer currentVisitNumber; + + @Column(name = "visit_label") + private String visitLabel; + + @Column(name = "visit_number") + private Integer visitNumber; + + @Column(name = "is_confirmed") + private Boolean isConfirmed; + + @Column(name = "leprosy_state", length = 255) + private String leprosyState; + + @Temporal(TemporalType.DATE) + @Column(name = "treatment_start_date") + private Date treatmentStartDate; + + @Column(name = "total_followup_months_required") + private Integer totalFollowUpMonthsRequired; + + @Temporal(TemporalType.DATE) + @Column(name = "treatment_end_date") + private Date treatmentEndDate; + + @Column(name = "mdt_blister_pack_recived", length = 100) + private String mdtBlisterPackRecived; + + @Column(name = "treatment_status", length = 100) + private String treatmentStatus; + + @Column(name = "recurrent_ulceration_id") + private Integer recurrentUlcerationId; + + @Column(name = "recurrent_tingling_id") + private Integer recurrentTinglingId; + + @Column(name = "hypopigmented_patch_id") + private Integer hypopigmentedPatchId; + + @Column(name = "thickened_skin_id") + private Integer thickenedSkinId; + + @Column(name = "skin_nodules_id") + private Integer skinNodulesId; + + @Column(name = "skin_patch_discoloration_id") + private Integer skinPatchDiscolorationId; + + @Column(name = "recurrent_numbness_id") + private Integer recurrentNumbnessId; + + @Column(name = "clawing_fingers_id") + private Integer clawingFingersId; + + @Column(name = "tingling_numbness_extremities_id") + private Integer tinglingNumbnessExtremitiesId; + + @Column(name = "inability_close_eyelid_id") + private Integer inabilityCloseEyelidId; + + @Column(name = "difficulty_holding_objects_id") + private Integer difficultyHoldingObjectsId; + + @Column(name = "weakness_feet_id") + private Integer weaknessFeetId; + + @Column(name = "recurrent_ulceration") + private String recurrentUlceration; + + @Column(name = "recurrent_tingling") + private String recurrentTingling; + + @Column(name = "hypopigmented_patch") + private String hypopigmentedPatch; + + @Column(name = "thickened_skin") + private String thickenedSkin; + + @Column(name = "skin_nodules") + private String skinNodules; + + @Column(name = "skin_patch_discoloration") + private String skinPatchDiscoloration; + + @Column(name = "recurrent_numbness") + private String recurrentNumbness; + + @Column(name = "clawing_fingers") + private String clawingFingers; + + @Column(name = "tingling_numbness_extremities") + private String tinglingNumbnessExtremities; + + @Column(name = "inability_close_eyelid") + private String inabilityCloseEyelid; + + @Column(name = "difficulty_holding_objects") + private String difficultyHoldingObjects; + + @Column(name = "weakness_feet") + private String weaknessFeet; + + @Column(name = "CreatedBy", length = 100) + private String createdBy; + + @Column(name = "CreatedDate") + private Timestamp createdDate; + + @Column(name = "ModifiedBy", length = 100) + private String modifiedBy; + + @Column(name = "LastModDate") + private Timestamp lastModDate; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningMalaria.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningMalaria.java new file mode 100644 index 00000000..a310acb5 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningMalaria.java @@ -0,0 +1,143 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.util.Date; + +@Entity +@Table(name = "screening_malaria", schema = "db_iemr") +@Data +public class ScreeningMalaria { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "ben_id") + private Long benId; + + @Column(name = "house_hold_details_Id",nullable = false) + private Long houseHoldDetailsId; + + @Temporal(TemporalType.DATE) + @Column(name = "screening_date") + private Date screeningDate; + + @Column(name = "beneficiary_status") + private String beneficiaryStatus; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_death") + private Date dateOfDeath; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "other_place_of_death") + private String otherPlaceOfDeath; + + @Column(name = "reason_for_death") + private String reasonForDeath; + + @Column(name = "other_reason_for_death") + private String otherReasonForDeath; + + @Column(name = "symptoms") + private String symptoms; + + @Column(name = "case_status") + private String caseStatus; + + @Column(name = "rapid_diagnostic_test") + private String rapidDiagnosticTest; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_rdt") + private Date dateOfRdt; + + @Column(name = "slide_test_pf") + private String slideTestPf; + + @Column(name = "slide_test_pv") + private String slideTestPv; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_slide_test") + private Date dateOfSlideTest; + + @Column(name = "slide_no") + private String slideNo; + + @Column(name = "referred_to") + private Integer referredTo; + + @Column(name = "other_referred_facility") + private String otherReferredFacility; + + @Column(name = "remarks") + private String remarks; + + @Temporal(TemporalType.DATE) + @Column(name = "date_of_visit_by_supervisor") + private Date dateOfVisitBySupervisor; + + @Column(name = "disease_type_id") + private Integer diseaseTypeId; + + @Column(name = "user_id") + private Integer userId; + + @Temporal(TemporalType.DATE) + @Column(name = "created_date") + private Date createdDate; + + @Column(name = "created_by") + private String createdBy; + + + @Column(name = "refer_to_name") + private String referToName; + + @Column(name = "case_status_id") + private Integer caseStatusId; + + @Column(name = "malaria_test_type") + private String malariaTestType; + + @Column(name = "malaria_slide_test_Type") + private String malariaSlideTestType; + + @Column(name = "visit_Id") + private Long visitId; + + @Column(name = "visit_date") + private Date visitDate; + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java new file mode 100644 index 00000000..adacdb1b --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -0,0 +1,73 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.sql.Timestamp; +import java.time.LocalDate; + +@Entity +@Data +@Table(name = "tb_confirmed_cases",schema = "db_iemr") +public class TBConfirmedCase { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id; + + @Column(name = "ben_id", nullable = false) + private Long benId; + + @Column(name = "user_id",nullable = false) + private Integer userId; + + + @Column(name = "regimen_type") + private String regimenType; + + @Column(name = "treatment_start_date") + private LocalDate treatmentStartDate; + + @Column(name = "expected_treatment_completion_date") + private LocalDate expectedTreatmentCompletionDate; + + @Column(name = "follow_up_date") + private LocalDate followUpDate; + + @Column(name = "monthly_follow_up_done") + private String monthlyFollowUpDone; + + @Column(name = "adherence_to_medicines") + private String adherenceToMedicines; + + @Column(name = "any_discomfort") + private Boolean anyDiscomfort; + + @Column(name = "treatment_completed") + private Boolean treatmentCompleted; + + @Column(name = "actual_treatment_completion_date") + private LocalDate actualTreatmentCompletionDate; + + @Column(name = "treatment_outcome") + private String treatmentOutcome; + + @Column(name = "date_of_death") + private LocalDate dateOfDeath; + + @Column(name = "place_of_death") + private String placeOfDeath; + + @Column(name = "reason_for_death") + private String reasonForDeath = "Tuberculosis"; + + @Column(name = "reason_for_not_completing") + private String reasonForNotCompleting; + + @Column(name = "created_at") + private LocalDate createdAt = LocalDate.now(); + + @Column(name = "updated_at") + private LocalDate updatedAt; + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java new file mode 100644 index 00000000..180c3bbe --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java @@ -0,0 +1,29 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class TBConfirmedCaseDTO { + + private Long benId; + private Integer userId; + private Integer suspectedTbId; + private String regimenType; + private LocalDate treatmentStartDate; + private LocalDate expectedTreatmentCompletionDate; + private LocalDate followUpDate; + private String monthlyFollowUpDone; + private String adherenceToMedicines; + private Boolean anyDiscomfort; + private Boolean treatmentCompleted; + private LocalDate actualTreatmentCompletionDate; + private String treatmentOutcome; + private LocalDate dateOfDeath; + private String placeOfDeath; + private String reasonForDeath ; + private String reasonForNotCompleting; + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java index 9bf7ea8d..6789f9bf 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java @@ -46,4 +46,37 @@ public class TBScreening { @Column(name = "family_check") private Boolean familySufferingFromTB; + + @Column(name = "rise_of_fever") + private Boolean riseOfFever; + + @Column(name = "loss_of_appetite") + private Boolean lossOfAppetite; + + @Column(name = "age") + private Boolean age; + + @Column(name = "diabetic") + private Boolean diabetic; + + @Column(name = "tobacco_user") + private Boolean tobaccoUser; + + @Column(name = "bmi") + private Boolean bmi; + + @Column(name = "contact_with_tb_patient") + private Boolean contactWithTBPatient; + + @Column(name = "history_of_tb_in_last_five_yrs") + private Boolean historyOfTBInLastFiveYrs; + + @Column(name = "sympotomatic") + private String sympotomatic; + + @Column(name = "asymptomatic") + private String asymptomatic; + + @Column(name = "recommandate_test") + private String recommandateTest; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java index 7cb945a8..2de2baf8 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -40,4 +40,40 @@ public class TBSuspected { @Column(name = "followups") private String followUps; + + // Visit Information + @Column(name = "visit_label") + private String visitLabel; + + @Column(name = "type_of_tb_case") + private String typeOfTBCase; + + @Column(name = "reason_for_suspicion", length = 500) + private String reasonForSuspicion; + + + // Chest X-Ray + @Column(name = "is_chest_xray_done") + private Boolean isChestXRayDone; + + @Column(name = "chest_xray_result", length = 100) + private String chestXRayResult; + + // Referral & Confirmation + @Column(name = "referral_facility", length = 200) + private String referralFacility; + + @Column(name = "is_tb_confirmed") + private Boolean isTBConfirmed; + + @Column(name = "is_drtb_confirmed") + private Boolean isDRTBConfirmed; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapId; + + @Column(name = "is_confirmed") + private Boolean isConfirmed; + + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java b/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java new file mode 100644 index 00000000..9ab6d5cb --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java @@ -0,0 +1,43 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Entity +@Data +@Table(name = "uwin_session_record",schema = "db_iemr") +public class UwinSession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "asha_id", nullable = false) + private Integer ashaId; + + @Column(name = "date", nullable = false) + private Timestamp date; + + @Column(name = "session_date", nullable = false) + private Timestamp sessionDate; + + @Column(name = "place", nullable = false) + private String place; + + @Column(name = "participants", nullable = false) + private Integer participants; + + @Lob + @Column(name = "attachments_json", columnDefinition = "LONGTEXT") + private String attachmentsJson; + + @Column(name = "created_by") + private String createdBy; + + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java b/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java new file mode 100644 index 00000000..758cc449 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java @@ -0,0 +1,81 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.sql.Timestamp; + +@Entity +@Table(name = "VHND_form",schema = "db_iemr") +@Data +public class VHNDForm { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private int id; + + @Column(name = "user_id") + private Integer userId; + + @Column(name = "vhnd_date") + private String vhndDate; + + @Column(name = "place") + private String place; + + @Column(name = "no_of_beneficiaries_attended") + private Integer noOfBeneficiariesAttended; + + @Column(name = "image1") + private String image1; + + @Column(name = "image2") + private String image2; + + @Column(name = "form_type") + private String formType; + + @Column(name = "vhnd_place_id") + private Integer vhndPlaceId; + + @Column(name = "pregnant_women_anc") + private String pregnantWomenAnc; + + @Column(name = "lactating_mothers_pnc") + private String lactatingMothersPnc; + + @Column(name = "children_immunization") + private String childrenImmunization; + + @Column(name = "select_all_education") + private Boolean selectAllEducation; + + @Column(name = "knowledge_balanced_diet") + private String knowledgeBalancedDiet; + + @Column(name = "care_during_pregnancy") + private String careDuringPregnancy; + + @Column(name = "importance_breastfeeding") + private String importanceBreastfeeding; + + @Column(name = "complementary_feeding") + private String complementaryFeeding; + + @Column(name = "hygiene_sanitation") + private String hygieneSanitation; + + @Column(name = "family_planning_healthcare") + private String familyPlanningHealthcare; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java b/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java new file mode 100644 index 00000000..858554da --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java @@ -0,0 +1,69 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import jakarta.xml.bind.annotation.XmlAccessorOrder; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.sql.Timestamp; + +import static jakarta.persistence.GenerationType.*; + +@Entity +@Table(name = "vhnc_form",schema = "db_iemr") +@Data +public class VhncForm { + @Id + @GeneratedValue(strategy = IDENTITY) + private int id; + + @Column(name = "vhnc_date") + private String vhncDate; + + @Column(name = "place") + private String place; + + @Column(name = "no_of_beneficiaries_attended") + private Integer noOfBeneficiariesAttended; + + @Column(name = "image1") + private String image1; + + @Column(name = "image2") + private String image2; + + @Column(name = "user_id") + private Long userId; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "form_type") + private String formType; + + @Column(name = "village_name") + private String villageName; + + @Column(name = "anm") + private Integer anm; + + @Column(name = "aww") + private Integer aww; + + @Column(name = "no_of_pragnent_women") + private Integer noOfPragnentWoment; + + @Column(name = "no_of_lacting_mother") + private Integer noOfLactingMother; + + @Column(name = "no_of_committee") + private Integer noOfCommittee; + + @Column(name = "followup_previous") + private Boolean followupPrevius; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/crashlogs/CrashLogRequest.java b/src/main/java/com/iemr/flw/dto/crashlogs/CrashLogRequest.java new file mode 100644 index 00000000..2e0bf107 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/crashlogs/CrashLogRequest.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.crashlogs; + +import lombok.Data; + +@Data +public class CrashLogRequest { + private String appVersion; + private String deviceId; + private String timestamp; +} diff --git a/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java b/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java index 09570aa6..00e452c5 100644 --- a/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java +++ b/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java @@ -1,71 +1,71 @@ -package com.iemr.flw.dto.identity; + package com.iemr.flw.dto.identity; -import java.sql.Timestamp; + import java.sql.Timestamp; -public class GetBenRequestHandler { - private Integer villageID; - private Timestamp fromDate; - private Timestamp toDate; - private Integer pageNo; - private Integer userId; - private String userName; + public class GetBenRequestHandler { + private Integer villageID; + private Timestamp fromDate; + private Timestamp toDate; + private Integer pageNo; + private Integer userId; + private String userName; - private Integer ashaId; + private Integer ashaId; - public Integer getAshaId() { - return ashaId; - } + public Integer getAshaId() { + return ashaId; + } - public void setAshaId(Integer ashaId) { - this.ashaId = ashaId; - } + public void setAshaId(Integer ashaId) { + this.ashaId = ashaId; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } - public void setUserName(String userName) { - this.userName = userName; - } + public void setUserName(String userName) { + this.userName = userName; + } - public Integer getUserId() { - return userId; - } + public Integer getUserId() { + return userId; + } - public void setUserId(Integer userId) { - this.userId = userId; - } + public void setUserId(Integer userId) { + this.userId = userId; + } - public Integer getPageNo() { - return pageNo; - } + public Integer getPageNo() { + return pageNo; + } - public void setPageNo(Integer pageNo) { - this.pageNo = pageNo; - } + public void setPageNo(Integer pageNo) { + this.pageNo = pageNo; + } - public Integer getVillageID() { - return villageID; - } + public Integer getVillageID() { + return villageID; + } - public void setVillageID(Integer villageID) { - this.villageID = villageID; - } + public void setVillageID(Integer villageID) { + this.villageID = villageID; + } - public Timestamp getFromDate() { - return fromDate; - } + public Timestamp getFromDate() { + return fromDate; + } - public void setFromDate(Timestamp fromDate) { - this.fromDate = fromDate; - } + public void setFromDate(Timestamp fromDate) { + this.fromDate = fromDate; + } - public Timestamp getToDate() { - return toDate; - } + public Timestamp getToDate() { + return toDate; + } - public void setToDate(Timestamp toDate) { - this.toDate = toDate; - } + public void setToDate(Timestamp toDate) { + this.toDate = toDate; + } -} + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java index 83f1acef..b4cf0033 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java @@ -1,7 +1,10 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; import lombok.Data; +import java.io.File; +import java.sql.Date; import java.sql.Timestamp; @Data @@ -42,5 +45,26 @@ public class ANCVisitDTO { private Timestamp updatedDate; private String updatedBy; private Integer providerServiceMapID; + private String filePath; + private String serialNo; + private String methodOfTermination; + private Integer methodOfTerminationId; + private String terminationDoneBy; + private Integer terminationDoneById; + private Integer isPaiucdId; + private String isPaiucd; + private String remarks; + private String abortionImg1; + private String abortionImg2; + private String placeOfDeath; + private Integer placeOfDeathId; + private String otherPlaceOfDeath; + private Timestamp lmpDate; + private Timestamp visitDate; + private Timestamp dateSterilisation; + private Boolean isYesOrNo; + private String placeOfAnc; + private Integer placeOfAncId; + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/AdolescentHealthDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AdolescentHealthDTO.java new file mode 100644 index 00000000..b59bb8ea --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AdolescentHealthDTO.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.util.List; +@Data +public class AdolescentHealthDTO { + @NotNull(message = "User ID cannot be null") + Integer userId; + @NotNull(message = "Adolescent health records cannot be null") + @Size(min = 1, message = "At least one adolescent health record is required") + List adolescentHealths; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/AesJeDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AesJeDTO.java new file mode 100644 index 00000000..ee444826 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AesJeDTO.java @@ -0,0 +1,35 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class AesJeDTO { + Integer userId; + List aesJeLists; +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/AhDMeetingFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AhDMeetingFormDTO.java new file mode 100644 index 00000000..0ecc31be --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AhDMeetingFormDTO.java @@ -0,0 +1,13 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AhDMeetingFormDTO { + private int id = 0; + private String mobilizedForAHD; + private String ahdPlace; + private String ahdDate; + private String image1; + private String image2; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/AhdMeetingDto.java b/src/main/java/com/iemr/flw/dto/iemr/AhdMeetingDto.java new file mode 100644 index 00000000..fc5e7a26 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AhdMeetingDto.java @@ -0,0 +1,11 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; + +@Data +public class AhdMeetingDto { + private Integer userId; + private List entries; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java new file mode 100644 index 00000000..76aff81d --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java @@ -0,0 +1,15 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AncCounsellingCareDTO { + private String formId; + private Long beneficiaryId; + private String visitDate; + private AncCounsellingCareListDTO fields; + +} + + + diff --git a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java new file mode 100644 index 00000000..981e34e2 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java @@ -0,0 +1,79 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +@Data +public class AncCounsellingCareListDTO { + + @SerializedName("home_visit_date") + private String homeVisitDate; + + @SerializedName("select_all") + private String selectAll; + + @SerializedName("swelling") + private String swelling; + + @SerializedName("high_bp") + private String highBp; + + @SerializedName("convulsions") + private String convulsions; + + @SerializedName("anemia") + private String anemia; + + @SerializedName("reduced_fetal_movement") + private String reducedFetalMovement; + + @SerializedName("age_risk") + private String ageRisk; + + @SerializedName("child_gap") + private String childGap; + + @SerializedName("short_height") + private String shortHeight; + + @SerializedName("pre_preg_weight") + private String prePregWeight; + + @SerializedName("bleeding") + private String bleeding; + + @SerializedName("miscarriage_history") + private String miscarriageHistory; + + @SerializedName("four_plus_delivery") + private String fourPlusDelivery; + + @SerializedName("first_delivery") + private String firstDelivery; + + @SerializedName("twin_pregnancy") + private String twinPregnancy; + + @SerializedName("c_section_history") + private String cSectionHistory; + + @SerializedName("pre_existing_disease") + private String preExistingDisease; + + @SerializedName("fever_malaria") + private String feverMalaria; + + @SerializedName("jaundice") + private String jaundice; + + @SerializedName("sickle_cell") + private String sickleCell; + + @SerializedName("prolonged_labor") + private String prolongedLabor; + + @SerializedName("malpresentation") + private String malpresentation; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareResponseDTO.java new file mode 100644 index 00000000..2e019558 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareResponseDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.Map; + +@Data +public class AncCounsellingCareResponseDTO { + private String formId; + private Long beneficiaryId; + private String visitDate; + private Map fields; // for dynamic form fields + +} + + + diff --git a/src/main/java/com/iemr/flw/dto/iemr/AttachmentDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AttachmentDTO.java new file mode 100644 index 00000000..1ab382ca --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AttachmentDTO.java @@ -0,0 +1,41 @@ +package com.iemr.flw.dto.iemr; + +public class AttachmentDTO { + + private String fileName; // e.g. "meeting_photo1.jpg" + private String fileType; // e.g. "image/jpeg", "image/png", "application/pdf" + private Long fileSize; // size in bytes + + public AttachmentDTO() { + } + + public AttachmentDTO(String fileName, String fileType, Long fileSize) { + this.fileName = fileName; + this.fileType = fileType; + this.fileSize = fileSize; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getFileType() { + return fileType; + } + + public void setFileType(String fileType) { + this.fileType = fileType; + } + + public Long getFileSize() { + return fileSize; + } + + public void setFileSize(Long fileSize) { + this.fileSize = fileSize; + } +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java b/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java index a7ea9ebc..ed1dc34e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java @@ -1,9 +1,11 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; import lombok.Data; import java.sql.Time; import java.sql.Timestamp; +import java.util.List; @Data public class CdrDTO { @@ -47,6 +49,14 @@ public class CdrDTO { private Timestamp createdDate; + private String cdrImage2; + + private String deathCertImage1; + + private String deathCertImage2; + + private String cdrImage; + private Timestamp updatedDate; private String updatedBy; diff --git a/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java new file mode 100644 index 00000000..2a2790ad --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java @@ -0,0 +1,44 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; +import jakarta.persistence.Column; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class ChronicDiseaseVisitDTO { + + @JsonProperty("id") + private Long id; + + @JsonProperty("benId") + private Long benId; + + @JsonProperty("hhId") + private Long hhId; + + @JsonProperty("formId") + private String formId; + + @JsonProperty("version") + private Integer version; + + @JsonProperty("visitNo") + private Integer visitNo; + + @JsonProperty("followUpNo") + private Integer followUpNo; + + @Column(name = "followUpDate") + private LocalDate followUpDate; + + @JsonProperty("diagnosisCodes") + private String diagnosisCodes; + + @JsonProperty("treatmentStartDate") + private String treatmentStartDate; // yyyy-MM-dd + + @JsonProperty("formDataJson") + private String formDataJson; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java index 59ff225c..5e94697a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -1,5 +1,6 @@ package com.iemr.flw.dto.iemr; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.sql.Timestamp; @@ -8,6 +9,7 @@ public class DeliveryOutcomeDTO { private Long id; private Long benId; + private Timestamp dateOfDelivery; private String timeOfDelivery; private String placeOfDelivery; diff --git a/src/main/java/com/iemr/flw/dto/iemr/DewormingDto.java b/src/main/java/com/iemr/flw/dto/iemr/DewormingDto.java new file mode 100644 index 00000000..f95598c8 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DewormingDto.java @@ -0,0 +1,11 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; + +@Data +public class DewormingDto { + private Integer userId; + private List entries; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DewormingFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DewormingFormDTO.java new file mode 100644 index 00000000..bf77cd65 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DewormingFormDTO.java @@ -0,0 +1,14 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class DewormingFormDTO { + private int id = 0; + private String dewormingDone; + private String dewormingDate; + private String dewormingLocation; + private Integer ageGroup; + private String image1; + private String image2; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseAesjeDto.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseAesjeDto.java new file mode 100644 index 00000000..1a503e5a --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseAesjeDto.java @@ -0,0 +1,53 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.Date; +@Data +public class DiseaseAesjeDto { + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Date visitDate; + private String beneficiaryStatus; + private Date dateOfDeath; + private String placeOfDeath; + private String otherPlaceOfDeath; + private String reasonForDeath; + private String otherReasonForDeath; + private String aesJeCaseStatus; + private Integer aesJeCaseCount; + private Integer followUpPoint; + private String referredTo; + private String otherReferredFacility; + private Date createdDate; + private String createdBy; + private Integer userId; + private Integer diseaseTypeId; + private String referToName; + private Integer beneficiaryStatusId; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseFilariasisDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseFilariasisDTO.java new file mode 100644 index 00000000..a834fdba --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseFilariasisDTO.java @@ -0,0 +1,50 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.Date; +@Data +public class DiseaseFilariasisDTO { + + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Boolean sufferingFromFilariasis; + private String affectedBodyPart; + private Date mdaHomeVisitDate; + private String doseStatus; + private Integer filariasisCaseCount; + private String otherDoseStatusDetails; + private String medicineSideEffect; + private String otherSideEffectDetails; + private Date createdDate; + private String createdBy; + private Integer userId; + private Integer diseaseTypeId; + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseGetLeprosyDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseGetLeprosyDTO.java new file mode 100644 index 00000000..4f8a2ef7 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseGetLeprosyDTO.java @@ -0,0 +1,99 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.sql.Timestamp; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonFormat; + +@Data +public class DiseaseGetLeprosyDTO { + + private Long id; + private Long benId; + private Long houseHoldDetailsId; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date homeVisitDate; + + private String leprosyStatus; + private String referredTo; + private String otherReferredTo; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date leprosyStatusDate; + + private String typeOfLeprosy; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date followUpDate; + + private String beneficiaryStatus; + private String remark; + private Integer userId; + private Integer diseaseTypeId; + private String referToName; + private Integer beneficiaryStatusId; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date dateOfDeath; + + private String placeOfDeath; + private String otherPlaceOfDeath; + private String reasonForDeath; + private String otherReasonForDeath; + + private String leprosySymptoms; + private Integer leprosySymptomsPosition; + private Integer lerosyStatusPosition; + private Integer currentVisitNumber; + private String visitLabel; + private Integer visitNumber; + private Boolean isConfirmed; + private String leprosyState; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date treatmentStartDate; + + private Integer totalFollowUpMonthsRequired; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date treatmentEndDate; + + private String mdtBlisterPackRecived; + private String treatmentStatus; + private String createdBy; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Timestamp createdDate; + + private String modifiedBy; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Timestamp lastModDate; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseKalaAzarDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseKalaAzarDTO.java new file mode 100644 index 00000000..f70aa04d --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseKalaAzarDTO.java @@ -0,0 +1,57 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.Date; +@Data +public class DiseaseKalaAzarDTO { + + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Date visitDate; + private String beneficiaryStatus; + private Date dateOfDeath; + private String placeOfDeath; + private String otherPlaceOfDeath; + private String reasonForDeath; + private String otherReasonForDeath; + private String kalaAzarCaseStatus; + private Integer kalaAzarCaseCount; + private String rapidDiagnosticTest; + private Date dateOfRdt; + private Integer followUpPoint; + private String referredTo; + private String otherReferredFacility; + private Date createdDate; + private String createdBy; + private Integer userId; + private Integer diseaseTypeId; + private String referToName; + private Integer beneficiaryStatusId; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java new file mode 100644 index 00000000..47489c54 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java @@ -0,0 +1,99 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.sql.Timestamp; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonFormat; + +@Data +public class DiseaseLeprosyDTO { + + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Date homeVisitDate; + private String leprosyStatus; + private String referredTo; + private String otherReferredTo; + private Date leprosyStatusDate; + private String typeOfLeprosy; + private Date followUpDate; + private String beneficiaryStatus; + private String remark; + private Integer userId; + private Integer diseaseTypeId; + private String referToName; + private Integer beneficiaryStatusId; + private Date dateOfDeath; + private String placeOfDeath; + private String otherPlaceOfDeath; + private String reasonForDeath; + private String otherReasonForDeath; + private String leprosySymptoms; + private Integer leprosySymptomsPosition; + private Integer lerosyStatusPosition; + private Integer currentVisitNumber; + private String visitLabel; + private Integer visitNumber; + private Boolean isConfirmed; + private String leprosyState; + private Date treatmentStartDate; + private Integer totalFollowUpMonthsRequired; + private Date treatmentEndDate; + private String mdtBlisterPackRecived; + private String treatmentStatus; + private String createdBy; + private Timestamp createdDate; + private String modifiedBy; + private Timestamp lastModDate; + private Integer recurrentUlcerationId; + private Integer recurrentTinglingId; + private Integer hypopigmentedPatchId; + private Integer thickenedSkinId; + private Integer skinNodulesId; + private Integer skinPatchDiscolorationId; + private Integer recurrentNumbnessId; + private Integer clawingFingersId; + private Integer tinglingNumbnessExtremitiesId; + private Integer inabilityCloseEyelidId; + private Integer difficultyHoldingObjectsId; + private Integer weaknessFeetId; + private String recurrentUlceration; + private String recurrentTingling; + private String hypopigmentedPatch; + private String thickenedSkin; + private String skinNodules; + private String skinPatchDiscoloration; + private String recurrentNumbness; + private String clawingFingers; + private String tinglingNumbnessExtremities; + private String inabilityCloseEyelid; + private String difficultyHoldingObjects; + private String weaknessFeet; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseMalariaDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseMalariaDTO.java new file mode 100644 index 00000000..99b27f8b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseMalariaDTO.java @@ -0,0 +1,76 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import jakarta.persistence.Column; +import lombok.Data; + +import java.util.Date; +@Data +public class DiseaseMalariaDTO { + + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Date screeningDate; + private String beneficiaryStatus; + private Date dateOfDeath; + private String placeOfDeath; + private String otherPlaceOfDeath; + private String reasonForDeath; + private String otherReasonForDeath; + private String symptoms; + private String caseStatus; + private String rapidDiagnosticTest; + private Date dateOfRdt; + private String slideTestPf; + private String slideTestPv; + private Date dateOfSlideTest; + private String slideNo; + private Integer referredTo; + private String otherReferredFacility; + private String remarks; + private Date dateOfVisitBySupervisor; + private Integer diseaseTypeId; + private Integer userId; + private Date createdDate; + private String createdBy; + private boolean feverMoreThanTwoWeeks; + private boolean fluLikeIllness; + private boolean shakingChills; + private boolean headache; + private boolean muscleAches; + private boolean tiredness; + private boolean nausea; + private boolean vomiting; + private boolean diarrhea; + private String referToName; + private Integer caseStatusId; + private String malariaTestType; + private String malariaSlideTestType; + private Long visitId; + private Date visitDate; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java index e51bbb70..0ec1c876 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleDTO.java @@ -1,9 +1,13 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; +import jakarta.persistence.Lob; import lombok.Data; +import org.springframework.web.multipart.MultipartFile; import java.io.Serializable; import java.sql.Timestamp; +import java.util.List; @Data public class EligibleCoupleDTO implements Serializable { @@ -105,4 +109,17 @@ public class EligibleCoupleDTO implements Serializable { private Timestamp updatedDate; private String updatedBy; + + private String lmpDate; + + private Boolean isKitHandedOver; + + private String kitHandedOverDate; + + private String kitPhoto1; + + private String kitPhoto2; + + + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleTrackingDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleTrackingDTO.java index 4eddee57..415fd1b1 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleTrackingDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/EligibleCoupleTrackingDTO.java @@ -33,4 +33,18 @@ public class EligibleCoupleTrackingDTO implements Serializable { private Timestamp updatedDate; private String updatedBy; + + private String lmpDate; + + private Timestamp dateOfAntraInjection; + + private String dueDateOfAntraInjection; + + private String mpaFile; + + private String antraDose; + + private String dischargeSummary1; + private String dischargeSummary2; + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java new file mode 100644 index 00000000..3480aa0b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java @@ -0,0 +1,29 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +@Data +public class EyeCheckupListDTO { + @SerializedName("visit_date") + private String visit_date; + + @SerializedName("symptoms_observed") + private String symptoms_observed; + + @SerializedName("eye_affected") + private String eye_affected; + + @SerializedName("referred_to") + private String referred_to; + + @SerializedName("follow_up_status") + private String follow_up_status; + + @SerializedName("date_of_surgery") + private String date_of_surgery; + + @SerializedName("discharge_summary_upload") + private String discharge_summary_upload; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java new file mode 100644 index 00000000..f0c6d8bb --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java @@ -0,0 +1,14 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class EyeCheckupRequestDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private EyeCheckupListDTO fields; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariaDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariaDTO.java new file mode 100644 index 00000000..821b16e0 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariaDTO.java @@ -0,0 +1,35 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class FilariaDTO { + Integer userId; + List filariaLists; +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignDTO.java new file mode 100644 index 00000000..2e53ee29 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class FilariasisCampaignDTO { + private Long id; + private String visitDate; + private FilariasisCampaignListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListDTO.java new file mode 100644 index 00000000..81438df9 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListDTO.java @@ -0,0 +1,30 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class FilariasisCampaignListDTO { + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("start_date") + private LocalDate startDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("end_date") + private LocalDate endDate; + + @JsonProperty("no_of_families") + private String numberOfFamilies; + + @JsonProperty("no_of_individuals") + private String numberOfIndividuals; + + @JsonProperty("mda_photos") + private List mdaPhotos; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java new file mode 100644 index 00000000..700d4665 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java @@ -0,0 +1,31 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class FilariasisCampaignListResponseDTO { + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("start_date") + private LocalDate startDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("end_date") + private LocalDate endDate; + + @JsonProperty("no_of_families") + private Double numberOfFamilies; + + @JsonProperty("no_of_individuals") + private Double numberOfIndividuals; + + @JsonProperty("mda_photos") + private List mdaPhotos; + + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisResponseDTO.java new file mode 100644 index 00000000..7b6dc5aa --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisResponseDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class FilariasisResponseDTO { + private Long id; + private Long houseHoldId; + private FilariasisCampaignListResponseDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/GeneralOpdDto.java b/src/main/java/com/iemr/flw/dto/iemr/GeneralOpdDto.java new file mode 100644 index 00000000..69f0dfc5 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/GeneralOpdDto.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class GeneralOpdDto { + private String beneficiaryName; + private String age; + private String gender; + private String registrationDate; + private String mobileNumber; + private String beneficiaryId; + private String visitDate; + private String referredTo; + private String followUpDate; + private boolean callButtonEnabled; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/GetDiseaseRequestHandler.java b/src/main/java/com/iemr/flw/dto/iemr/GetDiseaseRequestHandler.java new file mode 100644 index 00000000..5029c19f --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/GetDiseaseRequestHandler.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.math.BigInteger; +import java.sql.Timestamp; +@Data +public class GetDiseaseRequestHandler { + private Integer villageID; + private Timestamp fromDate; + private Timestamp toDate; + private Integer pageNo; + private Integer userId; + private String userName; + private Integer ashaId; + private Integer diseaseTypeID; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/GetMicroPlanHandler.java b/src/main/java/com/iemr/flw/dto/iemr/GetMicroPlanHandler.java new file mode 100644 index 00000000..93d8ef0e --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/GetMicroPlanHandler.java @@ -0,0 +1,8 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class GetMicroPlanHandler { + private Integer userId; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/GetVillageLevelRequestHandler.java b/src/main/java/com/iemr/flw/dto/iemr/GetVillageLevelRequestHandler.java new file mode 100644 index 00000000..0e0e05ca --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/GetVillageLevelRequestHandler.java @@ -0,0 +1,21 @@ +package com.iemr.flw.dto.iemr; + +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +import java.sql.Timestamp; +@Data +public class GetVillageLevelRequestHandler { + @NotNull(message = "Form type is required") + private String formType; + private Integer villageID; + private Timestamp fromDate; + private Timestamp toDate; + private Integer pageNo; + private Integer userId; + private String userName; + private Integer ashaId; + + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbncDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbncDTO.java new file mode 100644 index 00000000..4cb7106b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/HbncDTO.java @@ -0,0 +1,34 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class HbncDTO { + private Long beneficiaryId; + private String hbncVisitDay; + private LocalDate hbncDueDate; + private LocalDate visitDate; + private Boolean babyAlive; + private LocalDate dateOfDeath; + private String reasonForDeath; + private String placeOfDeath; + private String otherPlaceOfDeath; + private Double babyWeight; + private Boolean urinePassed; + private Boolean stoolPassed; + private Boolean diarrhoea; + private Boolean vomiting; + private Boolean convulsions; + private String activity; + private String sucking; + private String breathing; + private String chestIndrawing; + private String temperature; + private Boolean jaundice; + private String umbilicalStumpCondition; + private Boolean babyDischargedFromSNCU; + private List dischargeSummaryImages; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbncRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbncRequestDTO.java index bc05e2fc..742144b8 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/HbncRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/HbncRequestDTO.java @@ -1,20 +1,17 @@ package com.iemr.flw.dto.iemr; +import com.google.gson.annotations.SerializedName; import lombok.Data; @Data public class HbncRequestDTO { private Long id; - private Long benId; - private Long hhId; - private Integer homeVisitDate; - - private HbncVisitCardDTO hbncVisitCardDTO; - - private HbncPart1DTO hbncPart1DTO; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private HbncVisitDTO fields; +} - private HbncPart2DTO hbncPart2DTO; - private HbncVisitDTO hbncVisitDTO; -} diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbncVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbncVisitDTO.java index 8e8aac8c..239e21c8 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/HbncVisitDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/HbncVisitDTO.java @@ -1,54 +1,101 @@ package com.iemr.flw.dto.iemr; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.google.gson.annotations.SerializedName; +import jakarta.persistence.Column; import lombok.Data; -import java.sql.Timestamp; - -@Data -public class HbncVisitDTO { - - private Long id; - private Long benId; - private Integer visitNo; - private Timestamp dateOfVisit; - private Boolean babyAlive; - private Integer numTimesFullMeal24hr; - private Integer numPadChanged24hr; - private Boolean babyKeptWarmWinter; - private Boolean babyFedProperly; - private Boolean babyCryContinuously; - private Integer motherTemperature; - private Boolean foulDischargeFever; - private Boolean motherSpeakAbnormallyFits; - private Boolean motherLessNoMilk; - private Boolean motherBreastProblem; - private Boolean babyEyesSwollen; - private Float babyWeight; - private Integer babyTemperature; - private Boolean babyYellow; - private String babyImmunizationStatus; - private Boolean babyReferred; - private Timestamp dateOfBabyReferral; - private String placeOfBabyReferral; - private String otherPlaceOfBabyReferral; - private Boolean motherReferred; - private Timestamp dateOfMotherReferral; - private String placeOfMotherReferral; - private String otherPlaceOfMotherReferral; - private Boolean allLimbsLimp; - private Boolean feedingLessStopped; - private Boolean cryWeakStopped; - private Boolean bloatedStomach; - private Boolean coldOnTouch; - private Boolean chestDrawing; - private Boolean breathFast; - private String pusNavel; - private String supervisor; - private String supervisorName; - private String supervisorComment; - private Timestamp supervisorSignDate; - private String createdBy; - private Timestamp createdDate; - private Timestamp updatedDate; - private String updatedBy; -} +import java.util.List; + + @Data + public class HbncVisitDTO { + @SerializedName("id") + private Integer id; + + @SerializedName("visit_day") + private String visit_day; + + @SerializedName("visit_date") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") // match your actual input + private String visit_date; + + @SerializedName("is_baby_alive") + private String is_baby_alive; + + + @SerializedName("baby_weight") + private Double baby_weight; + + @SerializedName("urine_passed") + private String urine_passed; + + @SerializedName("stool_passed") + private String stool_passed; + + @SerializedName("diarrhoea") + private String diarrhoea; + + @SerializedName("vomiting") + private String vomiting; + + @SerializedName("convulsions") + private String convulsions; + + @SerializedName("jaundice") + private String jaundice; + + @SerializedName("discharged_from_sncu") + private String discharged_from_sncu; + + @SerializedName("activity") + private String activity; + + @SerializedName("sucking") + private String sucking; + + @SerializedName("breathing") + private String breathing; + + @SerializedName("chest_indrawing") + private String chest_indrawing; + + @SerializedName("temperature") + private String temperature; + + @SerializedName("umbilical_stump") + private String umbilical_stump; + + @SerializedName("discharge_summary_upload") + private String discharge_summary_upload; + + @SerializedName("due_date") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + private String due_date; + + @Column(name = "date_of_death") + private String date_of_death; + + @Column(name = "reason_for_death") + private String reasonForDeath; + + @Column(name = "place_of_death") + private String place_of_death; + + @Column(name = "other_place_of_death") + private String other_place_of_death; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "updated_by") + private String updatedBy; + + @Column(name = "baby_eyes_swollen") + private Boolean babyEyesSwollen; + + + } + + + + diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbncVisitResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbncVisitResponseDTO.java new file mode 100644 index 00000000..48f66e4b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/HbncVisitResponseDTO.java @@ -0,0 +1,15 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import java.util.Date; +import java.util.Map; + +@Data +public class HbncVisitResponseDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private Map fields; // for dynamic form fields +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java index 0011bc93..172132e0 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java @@ -1,71 +1,122 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; import lombok.Data; +import java.math.BigDecimal; import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +import java.math.BigDecimal; +import java.sql.Timestamp; + +import java.util.List; @Data public class HbycDTO { - private Long id; + @SerializedName("visit_day") + private String visit_day; // 3 Months, 6 Months, etc. + + @SerializedName("due_date") + private String due_date; + + @SerializedName("visit_date") + private String visit_date; + + @SerializedName("is_baby_alive") + private String is_baby_alive; // Yes/No + + @SerializedName("date_of_death") + private String date_of_death; + + @SerializedName("reason_for_death") + private String reason_for_death; - private Long benId; + @SerializedName("place_of_death") + private String place_of_death; - private String subcenterName; + @SerializedName("other_place_of_death") + private String other_place_of_death; - private String primaryHealthCenterName; + @SerializedName("baby_weight") + private Integer baby_weight; - private Integer villagePopulation; + @SerializedName("is_child_sick") + private String is_child_sick; - private Integer infantPopulation; + @SerializedName("exclusive_breastfeeding") + private String exclusive_breastfeeding; - private Timestamp visitDate; + @SerializedName("mother_counseled_ebf") + private String mother_counseled_ebf; - private String hbycAgeCategory; + @SerializedName("complementary_feeding") + private String complementary_feeding; - private Boolean orsPacketDelivered; + @SerializedName("mother_counseled_cf") + private String mother_counseled_cf; - private Boolean ironFolicAcidGiven; + @SerializedName("weight_recorded") + private String weight_recorded; - private Boolean isVaccinatedByAge; + @SerializedName("developmental_delay") + private String developmental_delay; - private Boolean wasIll; + @SerializedName("measles_vaccine") + private String measles_vaccine; - private Boolean referred; + @SerializedName("vitamin_a") + private String vitamin_a; - private Boolean supplementsGiven; + @SerializedName("ors_available") + private String ors_available; - private Boolean byHeightLength; + @SerializedName("ifa_available") + private String ifa_available; - private Boolean childrenWeighingLessReferred; + @SerializedName("ors_given") + private String ors_given; - private Boolean weightAccordingToAge; + @SerializedName("ifa_given") + private String ifa_given; - private Boolean delayInDevelopment; + @SerializedName("handwash_counseling") + private String handwash_counseling; - private Boolean referredToHealthInstitite; + @SerializedName("parenting_counseling") + private String parenting_counseling; - private Boolean vitaminASupplementsGiven; + @SerializedName("family_planning_counseling") + private String family_planning_counseling; - private String deathAge; + @SerializedName("diarrhoea_episode") + private String diarrhoea_episode; - private String deathCause; + @SerializedName("breathing_difficulty") + private String breathing_difficulty; - private Boolean qmOrAnmInformed; + @SerializedName("temperature_check") + private BigDecimal temperature_check; - private String deathPlace; + @SerializedName("mcp_card_images") + private List mcp_card_images; - private Boolean superVisorOn; + @SerializedName("created_at") + private LocalDateTime created_at; - private Boolean orsShortage; + @SerializedName("updated_at") + private LocalDateTime updated_at; - private Boolean ifaDecreased; - private String createdBy; - private Timestamp createdDate; - private Timestamp updatedDate; - private String updatedBy; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbycRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbycRequestDTO.java new file mode 100644 index 00000000..82aa28d9 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/HbycRequestDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.HBYC; +import lombok.Data; + +import java.util.List; + +@Data +public class HbycRequestDTO { + + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private HbycDTO fields; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/HbycVisitResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/HbycVisitResponseDTO.java new file mode 100644 index 00000000..e569e223 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/HbycVisitResponseDTO.java @@ -0,0 +1,14 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.Map; + +@Data +public class HbycVisitResponseDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private Map fields; // for dynamic form fields +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/IFAFormFieldsDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IFAFormFieldsDTO.java new file mode 100644 index 00000000..023a9a1f --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IFAFormFieldsDTO.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class IFAFormFieldsDTO { + private String visit_date; + private String ifa_provided; + private Double ifa_quantity; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionRequest.java b/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionRequest.java new file mode 100644 index 00000000..cfd2a270 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionRequest.java @@ -0,0 +1,18 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +import java.util.Map; + +@Data +public class IFAFormSubmissionRequest { + private Long beneficiaryId; + private String formId; + private Long houseHoldId; + private String userName; + private String visitDate; + private IFAFormFieldsDTO fields; + +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionResponse.java b/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionResponse.java new file mode 100644 index 00000000..d1239523 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IFAFormSubmissionResponse.java @@ -0,0 +1,19 @@ +package com.iemr.flw.dto.iemr; + +import lombok.*; +import java.util.Map; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class IFAFormSubmissionResponse { + private Long beneficiaryId; + private String visitDate; + private Long houseHoldId; + private String createdBy; + private String formId; + private String createdAt; + private IFAFormFieldsDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/IRSRoundDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IRSRoundDTO.java new file mode 100644 index 00000000..f2d48716 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IRSRoundDTO.java @@ -0,0 +1,24 @@ +package com.iemr.flw.dto.iemr; + +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.math.BigInteger; +import java.sql.Date; +import java.time.LocalDate; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class IRSRoundDTO { + private Long id; + @NotNull(message = "Date cannot be null") + private LocalDate date; + @Min(value = 1, message = "Rounds must be at least 1") + private int rounds; + @NotNull(message = "Household ID cannot be null") + private Long householdId; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/IRSRoundListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IRSRoundListDTO.java new file mode 100644 index 00000000..e0780514 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IRSRoundListDTO.java @@ -0,0 +1,15 @@ +package com.iemr.flw.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public +class IRSRoundListDTO { + private List rounds; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/IfaDistributionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IfaDistributionDTO.java new file mode 100644 index 00000000..32143753 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/IfaDistributionDTO.java @@ -0,0 +1,35 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +@Data +public class IfaDistributionDTO { + + @SerializedName("beneficiaryId") + private Long beneficiaryId; + + @SerializedName("houseHoldId") + private Long houseHoldId; + + @SerializedName("formId") + private String formId; + + @SerializedName("visitDate") + private String visitDate; // can be "N/A" or date string + + @SerializedName("fields") + private FieldsDTO fields; + + @Data + public static class FieldsDTO { + @SerializedName("ifa_provision_date") + private String ifa_provision_date; + + @SerializedName("mcp_card_upload") + private String mcp_card_upload; + + @SerializedName("ifa_bottle_count") + private Double ifa_bottle_count; + } +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/IncentiveActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IncentiveActivityDTO.java index 8378de5a..0ebf4aac 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveActivityDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveActivityDTO.java @@ -24,6 +24,7 @@ public class IncentiveActivityDTO implements Serializable { private Integer district; private String group; + private String groupName; private String fmrCode; diff --git a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java index 58da9958..9a07f65c 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -1,5 +1,6 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; import lombok.Data; import java.sql.Timestamp; @@ -30,5 +31,9 @@ public class IncentiveRecordDTO { private Timestamp updatedDate; private String updatedBy; + + private Boolean isEligible; + + private Boolean isDefaultActivity; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRequestDTO.java index 6494855e..87daff48 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRequestDTO.java @@ -6,7 +6,7 @@ public class IncentiveRequestDTO { private Integer state; - + private String langCode; private Integer district; diff --git a/src/main/java/com/iemr/flw/dto/iemr/InfantRegisterDTO.java b/src/main/java/com/iemr/flw/dto/iemr/InfantRegisterDTO.java index 1e59b95d..0be067ff 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/InfantRegisterDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/InfantRegisterDTO.java @@ -32,4 +32,9 @@ public class InfantRegisterDTO { private String createdBy; private Timestamp updatedDate; private String updatedBy; + private String deliveryDischargeSummary1; + private String deliveryDischargeSummary2; + private String deliveryDischargeSummary3; + private String deliveryDischargeSummary4; + private String isSNCU; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/KalaAzarDTO.java b/src/main/java/com/iemr/flw/dto/iemr/KalaAzarDTO.java new file mode 100644 index 00000000..6048f636 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/KalaAzarDTO.java @@ -0,0 +1,35 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class KalaAzarDTO { + Integer userId; + List kalaAzarLists; +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/LeprosyDTO.java b/src/main/java/com/iemr/flw/dto/iemr/LeprosyDTO.java new file mode 100644 index 00000000..396048c4 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/LeprosyDTO.java @@ -0,0 +1,38 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class LeprosyDTO { + Integer userId; + List leprosyLists; + + + +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/LeprosyFollowUpDTO.java b/src/main/java/com/iemr/flw/dto/iemr/LeprosyFollowUpDTO.java new file mode 100644 index 00000000..aaf28a29 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/LeprosyFollowUpDTO.java @@ -0,0 +1,42 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import java.sql.Timestamp; +import java.util.Date; + +@Data +public class LeprosyFollowUpDTO { + + private Long id; + private Long benId; + private Integer visitNumber; + private Date followUpDate; + + private String treatmentStatus; + private String mdtBlisterPackReceived; + private Date treatmentCompleteDate; + + private String remarks; + private Date homeVisitDate; + + private String leprosySymptoms; + private String typeOfLeprosy; + private Integer leprosySymptomsPosition; + private String visitLabel; + private String leprosyStatus; + private String referredTo; + private String referToName; + private Date treatmentEndDate; + + private String mdtBlisterPackRecived; + + private Date treatmentStartDate; + + private String createdBy; + + private Timestamp createdDate; + + private String modifiedBy; + + private Timestamp lastModDate; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/LeprosyGetFollowUpDTO.java b/src/main/java/com/iemr/flw/dto/iemr/LeprosyGetFollowUpDTO.java new file mode 100644 index 00000000..0e2f59b0 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/LeprosyGetFollowUpDTO.java @@ -0,0 +1,55 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import java.sql.Timestamp; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonFormat; + +@Data +public class LeprosyGetFollowUpDTO { + + private Long id; + private Long benId; + private Integer visitNumber; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date followUpDate; + + private String treatmentStatus; + private String mdtBlisterPackReceived; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date treatmentCompleteDate; + + private String remarks; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date homeVisitDate; + + private String leprosySymptoms; + private String typeOfLeprosy; + private Integer leprosySymptomsPosition; + private String visitLabel; + private String leprosyStatus; + private String referredTo; + private String referToName; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date treatmentEndDate; + + private String mdtBlisterPackRecived; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Date treatmentStartDate; + + private String createdBy; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Timestamp createdDate; + + private String modifiedBy; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM d, yyyy h:mm:ss a", timezone = "Asia/Kolkata") + private Timestamp lastModDate; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingListResponseDTO.java new file mode 100644 index 00000000..ad2a0f37 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingListResponseDTO.java @@ -0,0 +1,12 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; + +@Data +public class MaaMeetingListResponseDTO { + private List data; + private Integer statusCode; + private String status; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java new file mode 100644 index 00000000..e4ca6af5 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -0,0 +1,24 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Data +public class MaaMeetingRequestDTO { + private Long id; + private LocalDate meetingDate; + private String place; + private Integer participants; + private MultipartFile[] meetingImages; // up to 5 images + private Integer ashaId; + private String villageName; + private Integer noOfPragnentWomen; + private Integer noOfLactingMother; + private String mitaninActivityCheckList; + private String createdBY; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java new file mode 100644 index 00000000..b56356c2 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java @@ -0,0 +1,47 @@ +package com.iemr.flw.dto.iemr; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.persistence.Column; +import lombok.Data; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Data +public class MaaMeetingResponseDTO { + @Schema(description = "Unique ID of the meeting", example = "1") + private Long id; + + @Schema(description = "Date of the meeting", example = "2025-09-06") + private LocalDate meetingDate; + + @Schema(description = "Place of the meeting", example = "HWC") + private String place; + + @Schema(description = "Number of participants attended", example = "25") + private Integer participants; + + @Schema(description = "Quarter of the year", example = "3") + private Integer quarter; + + @Schema(description = "Year of the meeting", example = "2025") + private Integer year; + + @Schema(description = "ID of ASHA", example = "963") + private Integer ashaId; + + @Schema(description = "Meeting images in base64 array", + example = "[\"iVBORw0KGgoAAAANSUhEUgAA...\", \"iVBORw0KGgoAAAANSUhEUgBB...\"]") + private List meetingImages; + + private String villageName; + private String noOfPragnentWomen; + private String noOfLactingMother; + private String mitaninActivityCheckList; + + @Column(name = "created_by") + private String createdBy; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MalariaDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MalariaDTO.java new file mode 100644 index 00000000..6570c7c5 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MalariaDTO.java @@ -0,0 +1,40 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + + +import lombok.Data; + +import java.util.List; +@Data +public class MalariaDTO { + Integer userId; + List malariaLists; + + + +} + + diff --git a/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java new file mode 100644 index 00000000..1a8b8e6e --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java @@ -0,0 +1,43 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import java.util.Date; + +@Data +public class MalariaFollowListUpDTO { + private Long id; + private Long benId; + private Long houseHoldDetailsId; + private Integer userId ; + private Long diseaseId; + private Date dateOfDiagnosis; + private Date treatmentStartDate; + private String treatmentGiven; + private String day; + private Date treatmentCompletionDate; + private Date referralDate; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowUpDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowUpDTO.java new file mode 100644 index 00000000..f47da8ed --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowUpDTO.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class MalariaFollowUpDTO { + private Integer userId; + private List malariaFollowListUp; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MalariaSymptomsDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MalariaSymptomsDTO.java new file mode 100644 index 00000000..b140a72b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MalariaSymptomsDTO.java @@ -0,0 +1,44 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@JsonIgnoreProperties(ignoreUnknown = true) +@Data +public class MalariaSymptomsDTO { + private boolean nausea; + private boolean diarrhea; + private boolean tiredness; + private boolean vomiting; + private boolean headache; + private boolean feverMoreThanTwoWeeks; + private boolean fluLikeIllness; + private boolean shakingChills; + private boolean muscleAches; + + // Getters & Setters +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/MdaFormFieldsDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MdaFormFieldsDTO.java new file mode 100644 index 00000000..9a8404e5 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MdaFormFieldsDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import java.sql.Timestamp; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class MdaFormFieldsDTO { + private String mda_distribution_date; + private String is_medicine_distributed; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionRequest.java b/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionRequest.java new file mode 100644 index 00000000..c4681ae8 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionRequest.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import java.sql.Timestamp; + +import lombok.Data; + +@Data +public class MdaFormSubmissionRequest { + private Long beneficiaryId; + private String formId; + private Long houseHoldId; + private String userName; + private String visitDate; + private MdaFormFieldsDTO fields; + private Timestamp createdDate; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionResponse.java b/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionResponse.java new file mode 100644 index 00000000..dee73d56 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MdaFormSubmissionResponse.java @@ -0,0 +1,22 @@ +package com.iemr.flw.dto.iemr; + +import java.sql.Timestamp; + +import lombok.*; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class MdaFormSubmissionResponse { + private Long beneficiaryId; + private String visitDate; + private Long houseHoldId; + private Integer ashaId; + private String createdBy; + private String formId; + private Timestamp createdAt; + private MdaFormFieldsDTO fields; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MdsrDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MdsrDTO.java index 5b07e40a..e59047ab 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MdsrDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MdsrDTO.java @@ -35,4 +35,10 @@ public class MdsrDTO { private Timestamp updatedDate; private String updatedBy; + + private String mdsr1File; + + private String mdsr2File; + + private String mdsrDeathCertFile; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/MicroBirthPlanDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MicroBirthPlanDTO.java new file mode 100644 index 00000000..882cee35 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MicroBirthPlanDTO.java @@ -0,0 +1,14 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.MicroBirthPlan; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; +@Data +public class MicroBirthPlanDTO implements Serializable { + Integer userId; + List entries; + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetDTO.java new file mode 100644 index 00000000..cbd604d9 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetDTO.java @@ -0,0 +1,13 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class MosquitoNetDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private MosquitoNetListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetListDTO.java new file mode 100644 index 00000000..ecab5e5e --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/MosquitoNetListDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class MosquitoNetListDTO { + private String visit_date; + private String is_net_distributed; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignDTO.java new file mode 100644 index 00000000..dbd83c26 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class OrsCampaignDTO { + private Long id; + private String visitDate; + private OrsCampaignListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java new file mode 100644 index 00000000..552c4fc8 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -0,0 +1,30 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Data +public class OrsCampaignListDTO { + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("start_date") + private LocalDate StartDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("end_date") + private LocalDate EndDate; + + @JsonProperty("number_of_families") + private String NumberOfFamilies; + + @JsonProperty("campaign_photos") + private List campaignPhotos; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java new file mode 100644 index 00000000..e72fb04c --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java @@ -0,0 +1,25 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class OrsCampaignListResponseDTO { + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("start_date") + private LocalDate StartDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("end_date") + private LocalDate EndDate; + + @JsonProperty("number_of_families") + private Double NumberOfFamilies; + + @JsonProperty("campaign_photos") + private List campaignPhotos; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java new file mode 100644 index 00000000..5c8b954d --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java @@ -0,0 +1,9 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class OrsCampaignResponseDTO { + private Long id; + private OrsCampaignListResponseDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionDTO.java new file mode 100644 index 00000000..7bdfd4fd --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionDTO.java @@ -0,0 +1,13 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class OrsDistributionDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private OrsDistributionListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java new file mode 100644 index 00000000..25ab11b5 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java @@ -0,0 +1,19 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +@Data +public class OrsDistributionListDTO { + + @SerializedName("visit_date") + private String visit_date; + + @SerializedName("num_under5_children") + private Double num_under5_children; + + @SerializedName("num_ors_packets") + private Double num_ors_packets; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseDTO.java new file mode 100644 index 00000000..051db762 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseDTO.java @@ -0,0 +1,13 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class OrsDistributionResponseDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private OrsDistributionResponseListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseListDTO.java new file mode 100644 index 00000000..3ce0db51 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionResponseListDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +@Data +public class OrsDistributionResponseListDTO { + + + @JsonProperty("num_under5_children") + private String num_under5_children; + + @JsonProperty("num_ors_packets") + private String num_ors_packets; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/PNCVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PNCVisitDTO.java index a1a4ad27..9bfc4fc7 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PNCVisitDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PNCVisitDTO.java @@ -29,4 +29,10 @@ public class PNCVisitDTO { private String createdBy; private Timestamp updatedDate; private String updatedBy; + private Timestamp sterilisationDate; + private String deliveryDischargeSummary1; + private String deliveryDischargeSummary2; + private String deliveryDischargeSummary3; + private String deliveryDischargeSummary4; + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java new file mode 100644 index 00000000..5fcdd537 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -0,0 +1,15 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Data +public class PendingActivityDTO { + private Long id; + private Integer userId; + private List images; + private String moduleName; + private String activityName; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingDTO.java new file mode 100644 index 00000000..7d265b81 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class PhcReviewMeetingDTO { + private Integer userId; + private List entries; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java new file mode 100644 index 00000000..b08386c6 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java @@ -0,0 +1,21 @@ +package com.iemr.flw.dto.iemr; + +import jakarta.persistence.Column; +import lombok.Data; + +@Data +public class PhcReviewMeetingFormDTO { + private int id; + private String phcReviewDate; + private String place; + private Integer noOfBeneficiariesAttended; + private String villageName; + private String mitaninHistory; + private String mitaninActivityCheckList; + private Integer placeId; + private String image1; + private String image2; + + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/PmsmaDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PmsmaDTO.java index 1f8003e9..5c0adfc9 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PmsmaDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PmsmaDTO.java @@ -47,4 +47,8 @@ public class PmsmaDTO { private Timestamp createdDate; private Timestamp updatedDate; private String updatedBy; + + private Timestamp visitDate; + private Integer visitNumber; + private String anyOtherHighRiskCondition; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignDTO.java new file mode 100644 index 00000000..7f6cfc87 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class PolioCampaignDTO { + private Long id; + private String visitDate; + private PolioCampaignListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java new file mode 100644 index 00000000..a42ef3c6 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -0,0 +1,28 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class PolioCampaignListDTO { + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("start_date") + private LocalDate startDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") + @JsonProperty("end_date") + private LocalDate endDate; + + @JsonProperty("children_vaccinated") + private String numberOfChildren; + + @JsonProperty("campaign_photos") + private List campaignPhotos; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java new file mode 100644 index 00000000..f27468f3 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java @@ -0,0 +1,25 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class PolioCampaignListResponseDTO { + @JsonProperty("start_date") + private LocalDate startDate; + + @JsonProperty("end_date") + private LocalDate endDate; + + @JsonProperty("children_vaccinated") + private Double numberOfChildren; + + @JsonProperty("campaign_photos") + private List campaignPhotos; + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java new file mode 100644 index 00000000..a6504236 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java @@ -0,0 +1,9 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class PolioCampaignResponseDTO { + private Long id; + private PolioCampaignListResponseDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SAMResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SAMResponseDTO.java new file mode 100644 index 00000000..99e0d68a --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SAMResponseDTO.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.SamVisitResponseDTO; +import lombok.Data; + +import java.util.Map; + +@Data +public class SAMResponseDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private SamVisitResponseDTO fields; // for dynamic form fields +} + diff --git a/src/main/java/com/iemr/flw/dto/iemr/SamDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SamDTO.java new file mode 100644 index 00000000..fd2305a7 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SamDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import jakarta.mail.Multipart; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.time.LocalDate; +@Data +public class SamDTO { + private Long id; + private Long beneficiaryId; + private Long houseHoldId; + private String visitDate; + private String userName; + private SamListDTO fields; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SamListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SamListDTO.java new file mode 100644 index 00000000..6f4b6644 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SamListDTO.java @@ -0,0 +1,48 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +import java.time.LocalDate; +import java.util.ArrayList; + +@Data +public class SamListDTO { + + + @SerializedName("visit_label") + private String visit_label; + + @SerializedName("muac") + private String muac; + + @SerializedName("weight_for_height_status") + private String weight_for_height_status; + + @SerializedName("is_child_referred_nrc") + private String is_child_referred_nrc; + + @SerializedName("is_child_admitted_nrc") + private String is_child_admitted_nrc; + + @SerializedName("nrc_admission_date") + private String nrc_admission_date; + + @SerializedName("is_child_discharged_nrc") + private String is_child_discharged_nrc; + + @SerializedName("nrc_discharge_date") + private String nrc_discharge_date; + + @SerializedName("follow_up_visit_date") + private ArrayList follow_up_visit_date; + + @SerializedName("sam_status") + private String sam_status; + + @SerializedName("discharge_summary") + private String discharge_summary; + + @SerializedName("view_discharge_docs") + private String view_discharge_docs; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SammelanListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SammelanListResponseDTO.java new file mode 100644 index 00000000..12efee50 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SammelanListResponseDTO.java @@ -0,0 +1,12 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class SammelanListResponseDTO { + private List data; + private Integer statusCode; + private String status; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SammelanRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SammelanRequestDTO.java new file mode 100644 index 00000000..a39b84d7 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SammelanRequestDTO.java @@ -0,0 +1,22 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; +@Data +public class SammelanRequestDTO { + + private Integer ashaId; // ASHA worker ID + private Long date; // Meeting date + private String place; // Dropdown: HWC / Anganwadi Centre / Community Center + private Integer participants; + + @JsonIgnore + private MultipartFile[] sammelanImages; // up to 5 images +// Number of participants attended + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SammelanResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SammelanResponseDTO.java new file mode 100644 index 00000000..ee2a0b79 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SammelanResponseDTO.java @@ -0,0 +1,23 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.SammelanAttachment; +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Data +public class SammelanResponseDTO { + + private Long id; + private Integer ashaId; + private Long date; + private String place; + private Integer participants; + private List imagePaths; + + + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/StandardResponse.java b/src/main/java/com/iemr/flw/dto/iemr/StandardResponse.java new file mode 100644 index 00000000..84ab4ded --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/StandardResponse.java @@ -0,0 +1,12 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import java.util.List; + +@Data +public class StandardResponse { + private int statusCode; + private String errorMessage; + private String status; + private T data; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCasesResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCasesResponseDTO.java new file mode 100644 index 00000000..42504dcd --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCasesResponseDTO.java @@ -0,0 +1,11 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.TBConfirmedCase; +import lombok.Data; + +import java.util.List; +@Data +public class TBConfirmedCasesResponseDTO { + Integer userId ; + List tbConfirmedCases; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedRequestDTO.java new file mode 100644 index 00000000..d3e76a4a --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedRequestDTO.java @@ -0,0 +1,13 @@ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; +import lombok.Data; +import java.util.List; + +@Data +public class TBConfirmedRequestDTO { + + private Long userId; + + private List tbConfirmedList; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java index 270526bd..36f48dfc 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -29,91 +29,15 @@ public class TBScreeningDTO { private Boolean familySufferingFromTB; - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getBenId() { - return benId; - } - - public void setBenId(Long benId) { - this.benId = benId; - } - - public Timestamp getVisitDate() { - return visitDate; - } - - public void setVisitDate(Timestamp visitDate) { - this.visitDate = visitDate; - } - - public Boolean getCoughMoreThan2Weeks() { - return coughMoreThan2Weeks; - } - - public void setCoughMoreThan2Weeks(Boolean coughMoreThan2Weeks) { - this.coughMoreThan2Weeks = coughMoreThan2Weeks; - } - - public Boolean getBloodInSputum() { - return bloodInSputum; - } - - public void setBloodInSputum(Boolean bloodInSputum) { - this.bloodInSputum = bloodInSputum; - } - - public Boolean getFeverMoreThan2Weeks() { - return feverMoreThan2Weeks; - } - - public void setFeverMoreThan2Weeks(Boolean feverMoreThan2Weeks) { - this.feverMoreThan2Weeks = feverMoreThan2Weeks; - } - - public Boolean getLossOfWeight() { - return lossOfWeight; - } - - public void setLossOfWeight(Boolean lossOfWeight) { - this.lossOfWeight = lossOfWeight; - } - - public Boolean getNightSweats() { - return nightSweats; - } - - public void setNightSweats(Boolean nightSweats) { - this.nightSweats = nightSweats; - } - - public Boolean getHistoryOfTb() { - return historyOfTb; - } - - public void setHistoryOfTb(Boolean historyOfTb) { - this.historyOfTb = historyOfTb; - } - - public Boolean getTakingAntiTBDrugs() { - return takingAntiTBDrugs; - } - - public void setTakingAntiTBDrugs(Boolean takingAntiTBDrugs) { - this.takingAntiTBDrugs = takingAntiTBDrugs; - } - - public Boolean getFamilySufferingFromTB() { - return familySufferingFromTB; - } - - public void setFamilySufferingFromTB(Boolean familySufferingFromTB) { - this.familySufferingFromTB = familySufferingFromTB; - } + private Boolean riseOfFever; + private Boolean lossOfAppetite; + private Boolean age; + private Boolean diabetic; + private Boolean tobaccoUser; + private Boolean bmi; + private Boolean contactWithTBPatient; + private Boolean historyOfTBInLastFiveYrs; + private String sympotomatic; + private String asymptomatic; + private String recommandateTest; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java index 8d224a9c..29fb25f6 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -10,18 +10,20 @@ public class TBSuspectedDTO { private Long id; private Long benId; - + private String visitLabel; private Timestamp visitDate; - + private String typeOfTBCase; + private String reasonForSuspicion; private Boolean isSputumCollected; - private String sputumSubmittedAt; - private String nikshayId; - private String sputumTestResult; - + private Boolean isChestXRayDone; + private String chestXRayResult; + private String referralFacility; + private Boolean isTBConfirmed; + private Boolean isConfirmed; + private Boolean isDRTBConfirmed; private Boolean referred; - private String followUps; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/UwinSessionRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UwinSessionRequestDTO.java new file mode 100644 index 00000000..f5456269 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/UwinSessionRequestDTO.java @@ -0,0 +1,17 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import org.springframework.web.multipart.MultipartFile; + +import java.sql.Timestamp; +import java.util.List; + +@Data +public class UwinSessionRequestDTO { + private Integer ashaId; + private Timestamp date; + private String place; + private Integer participants; + private MultipartFile[] attachments; + private String createdBy; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/UwinSessionResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UwinSessionResponseDTO.java new file mode 100644 index 00000000..a740881b --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/UwinSessionResponseDTO.java @@ -0,0 +1,18 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; +import org.apache.poi.hssf.record.TabIdRecord; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.List; + +@Data +public class UwinSessionResponseDTO { + private Long id; + private Integer ashaId; + private Timestamp date; + private String place; + private Integer participants; + private List attachments; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java new file mode 100644 index 00000000..bee7f247 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java @@ -0,0 +1,50 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import jakarta.persistence.Column; +import lombok.Data; + +@Data +public class VHNDFormDTO { + private String vhndDate; + private String place; + private Integer noOfBeneficiariesAttended; + private String image1; + private String image2; + private Integer vhndPlaceId; + private String pregnantWomenAnc; + private String lactatingMothersPnc; + private String childrenImmunization; + private Boolean selectAllEducation; + private String knowledgeBalancedDiet; + private String careDuringPregnancy; + private String importanceBreastfeeding; + private String complementaryFeeding; + private String hygieneSanitation; + private String familyPlanningHealthcare; +} + + diff --git a/src/main/java/com/iemr/flw/dto/iemr/VhncDto.java b/src/main/java/com/iemr/flw/dto/iemr/VhncDto.java new file mode 100644 index 00000000..54f6f92c --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/VhncDto.java @@ -0,0 +1,35 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; + +@Data +public class VhncDto { + private Integer userId; + private List entries; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java new file mode 100644 index 00000000..a2515b42 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java @@ -0,0 +1,45 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class VhncFormDTO { + private int id; + private String vhncDate; + private String place; + private Integer noOfBeneficiariesAttended; + private String image1; + private String image2; + private String villageName; + private Integer anm; + private Integer aww; + private Integer noOfPragnentWoment; + private Integer noOfLactingMother; + private Integer noOfCommittee; + private Boolean followupPrevius; + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/VhndDto.java b/src/main/java/com/iemr/flw/dto/iemr/VhndDto.java new file mode 100644 index 00000000..60c68d07 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/VhndDto.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.util.List; +@Data +public class VhndDto { + private Integer userId; + private List entries; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/masterEnum/DiseaseType.java b/src/main/java/com/iemr/flw/masterEnum/DiseaseType.java new file mode 100644 index 00000000..c182f5fa --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/DiseaseType.java @@ -0,0 +1,31 @@ +package com.iemr.flw.masterEnum; + + +public enum DiseaseType { + MALARIA(1), + KALA_AZAR(2), + AES_JE(3), + FILARIA(4), + LEPROSY(5); + + private final int id; + + DiseaseType(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + + + public static DiseaseType fromId(int id) { + for (DiseaseType disease : values()) { + if (disease.id == id) { + return disease; + } + } + throw new IllegalArgumentException("Invalid Disease ID: " + id); + } +} diff --git a/src/main/java/com/iemr/flw/masterEnum/GroupName.java b/src/main/java/com/iemr/flw/masterEnum/GroupName.java new file mode 100644 index 00000000..e53733b0 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/GroupName.java @@ -0,0 +1,38 @@ +package com.iemr.flw.masterEnum; + +public enum GroupName { + CHILD_HEALTH("CHILD HEALTH"), + IMMUNIZATION("IMMUNIZATION"), + MATERNAL_HEALTH("MATERNAL HEALTH"), + JSY("JSY"), + FAMILY_PLANNING("FAMILY PLANNING"), + ADOLESCENT_HEALTH("ADOLESCENT HEALTH"), + ASHA_MONTHLY_ROUTINE("ASHA MONTHLY ROUTINE"), + UMBRELLA_PROGRAMMES("UMBRELLA PROGRAMMES"), + NCD("NCD"), + ADDITIONAL_INCENTIVE("ADDITIONAL INCENTIVE"), + OTHER_INCENTIVES("OTHER INCENTIVES"), + ACTIVITY("ACTIVITY"); + + private final String originalDisplayName; + private static boolean isCh = false; + + GroupName(String displayName) { + this.originalDisplayName = displayName; + } + + // Set the master flag + public static void setIsCh(boolean flag) { + isCh = flag; + } + + // Get display name based on isCh + public String getDisplayName() { + return isCh ? "ACTIVITY" : originalDisplayName; + } +} + + + + + diff --git a/src/main/java/com/iemr/flw/masterEnum/StateCode.java b/src/main/java/com/iemr/flw/masterEnum/StateCode.java new file mode 100644 index 00000000..76a2ef31 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/StateCode.java @@ -0,0 +1,28 @@ +package com.iemr.flw.masterEnum; + +public enum StateCode { + AM(5), + CG(8); + + private final int stateCode; + + StateCode(int stateCode) { + this.stateCode = stateCode; + } + + public int getStateCode() { + return stateCode; + } + + + + public static StateCode fromId(int id) { + for (StateCode stateCode : values()) { + if (stateCode.stateCode == id) { + return stateCode; + } + } + throw new IllegalArgumentException("Invalid State ID: " + id); + } + +} diff --git a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java index af10b332..245b32f9 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -12,7 +12,9 @@ import java.math.BigInteger; import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +import java.util.Optional; @Repository public interface BeneficiaryRepo extends JpaRepository { @@ -20,13 +22,23 @@ public interface BeneficiaryRepo extends JpaRepository findById(Long benID); + + @Query(value = "SELECT beneficiaryRegID FROM db_identity.i_beneficiarydetails_rmnch WHERE BeneficiaryId = :benId", nativeQuery = true) + Long getBenRegIdFromBenId(@Param("benId") Long benId); + @Query(nativeQuery = true, value = " SELECT userid FROM db_iemr.m_user WHERE UserName = :userName ") Integer getUserIDByUserName(@Param("userName") String userName); - @Query(value = " SELECT t FROM RMNCHMBeneficiaryaddress t WHERE DATE(t.createdDate) BETWEEN DATE(:fromDate) " - + " AND DATE(:toDate) AND t.createdBy = :userName ") - Page getBenDataWithinDates(@Param("userName") String userName, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate, Pageable pageable); + + @Query("SELECT t FROM RMNCHMBeneficiaryaddress t " + + "WHERE t.createdDate BETWEEN :fromDate AND :toDate " + + "AND t.createdBy = :userName") + Page getBenDataWithinDates( + @Param("userName") String userName, + @Param("fromDate") Timestamp fromDate, + @Param("toDate") Timestamp toDate, + Pageable pageable); @Query(value = " SELECT t FROM RMNCHMBeneficiaryaddress t WHERE t.createdBy = :userName ") Page getBenDataByUser(@Param("userName") String userName, Pageable pageable); @@ -34,6 +46,9 @@ Page getBenDataWithinDates(@Param("userName") String u @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benAddressId = :addressID") RMNCHMBeneficiarymapping getByAddressID(@Param("addressID") BigInteger addressID); + @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benRegId = :BenRegId") + RMNCHMBeneficiarymapping getById(@Param("BenRegId") BigInteger BenRegId); + @Query(value = " SELECT t FROM RMNCHMBeneficiarydetail t WHERE t.id = :vanSerialNo") RMNCHMBeneficiarydetail getDetailsById(@Param("vanSerialNo") BigInteger vanSerialNo); @@ -61,9 +76,38 @@ Page getBenDataWithinDates(@Param("userName") String u @Query(" SELECT t.benRegId FROM RMNCHMBeneficiaryregidmapping t WHERE t.beneficiaryID = :benID ") Long getRegIDFromBenId(@Param("benID") Long benID); + @Query(nativeQuery = true, value = " SELECT HealthIdNumber,HealthID FROM db_iemr.m_benhealthidmapping WHERE BeneficiaryRegID = :benRegId ") Object[] getBenHealthIdNumber(@Param("benRegId") BigInteger benRegId); @Query(nativeQuery = true, value = " SELECT HealthID,HealthIdNumber,isNewAbha FROM db_iemr.t_healthid WHERE HealthIdNumber = :healthIdNumber ") ArrayList getBenHealthDetails(@Param("healthIdNumber") String healthIdNumber); + + @Query("SELECT b FROM RMNCHMBeneficiarymapping b WHERE b.benRegId = :benRegId") + RMNCHMBeneficiarymapping findByBenRegIdFromMapping(@Param("benRegId") BigInteger benRegId); + + @Query("SELECT d FROM RMNCHMBeneficiarydetail d WHERE d.beneficiaryDetailsId = :beneficiaryDetailsId") + RMNCHMBeneficiarydetail findByBeneficiaryDetailsId(@Param("beneficiaryDetailsId") BigInteger beneficiaryDetailsId); + + + // BeneficiaryRepo — replaces 3 separate queries per beneficiary + @Query(value = """ + SELECT + ibd.BeneficiaryId AS benId, + bd.firstName AS firstName, + bd.lastName AS lastName + FROM db_identity.i_beneficiarydetails_rmnch ibd + JOIN db_identity.i_beneficiarymapping bm + ON bm.BenRegId = ibd.BeneficiaryRegID + JOIN db_identity.i_beneficiarydetails bd + ON bd.beneficiaryDetailsId = bm.BenDetailsId + WHERE ibd.BeneficiaryId IN :benIds + """, nativeQuery = true) + List findBenNamesByBenIds(@Param("benIds") List benIds); + +// BeneficiaryRepo — replaces the per-row getBenIdFromRegID call +@Query("SELECT b.BenRegId, b.benficieryid " + + "FROM RMNCHBeneficiaryDetailsRmnch b " + + "WHERE b.BenRegId IN :regIds AND b.benficieryid IS NOT NULL") +List getBenIdsFromRegIDs(@Param("regIds") List regIds); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/AHDFormRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AHDFormRepo.java new file mode 100644 index 00000000..8f8b2188 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AHDFormRepo.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.AHDForm; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AHDFormRepo extends JpaRepository { + // You can add custom query methods here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java index 8fc40fc1..067e6acc 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java @@ -17,6 +17,8 @@ public interface ANCVisitRepo extends JpaRepository { List getANCForPW(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + @Query - ANCVisit findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, Boolean isActive); + ANCVisit findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); + } diff --git a/src/main/java/com/iemr/flw/repo/iemr/AdolescentHealthRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AdolescentHealthRepo.java new file mode 100644 index 00000000..17be21d8 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AdolescentHealthRepo.java @@ -0,0 +1,15 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Optional; + +@Repository +public interface AdolescentHealthRepo extends JpaRepository { + Optional findByBenId(BigInteger benId); + List findByUserId(Integer userId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java new file mode 100644 index 00000000..714dae59 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.AncCare; +import com.iemr.flw.domain.iemr.AncCounsellingCare; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface AncCounsellingCareRepo extends JpaRepository { + List findAllByUserId(Integer userId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaProfileRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaProfileRepo.java new file mode 100644 index 00000000..a3a397d3 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaProfileRepo.java @@ -0,0 +1,16 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.AshaWorker; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface AshaProfileRepo extends JpaRepository { + Optional findByEmployeeId(Integer employeeId); + + Optional findById(Long id); + + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java new file mode 100644 index 00000000..f2c915f4 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java @@ -0,0 +1,49 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.repo.iemr; + + +import com.iemr.flw.domain.iemr.BenReferDetails; + +import io.swagger.v3.oas.annotations.info.License; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + + +@Repository +public interface BenReferDetailsRepo extends JpaRepository { + + + @Query("SELECT b.referredToInstituteName FROM BenReferDetails b WHERE b.beneficiaryRegID = :benRegID") + String findInstituteNameByBeneficiaryRegID(@Param("benRegID") Long benRegID); + + + @Query("SELECT b.referralReason FROM BenReferDetails b WHERE b.beneficiaryRegID = :benRegID") + String findReasonByBeneficiaryRegID(@Param("benRegID") Long benRegID); + + List findByCreatedBy(String userName); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java index 0c8ae89e..dfd605ef 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java @@ -4,6 +4,8 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; +import java.util.List; + @Repository public interface BenVisitDetailsRepo extends JpaRepository { -} + public List findByBeneficiaryRegId(Long benRegID);} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BeneficiaryRepository.java b/src/main/java/com/iemr/flw/repo/iemr/BeneficiaryRepository.java new file mode 100644 index 00000000..fe3175a9 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BeneficiaryRepository.java @@ -0,0 +1,10 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.GeneralOpdEntry; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface BeneficiaryRepository extends JpaRepository { + List findByAshaIdOrderByVisitDateDesc(String ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/CbacIemrDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/CbacIemrDetailsRepo.java new file mode 100644 index 00000000..5e93dfad --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/CbacIemrDetailsRepo.java @@ -0,0 +1,44 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.CbacDetailsImer; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + + +import java.util.List; + +@Repository +public interface CbacIemrDetailsRepo extends CrudRepository { + + public CbacDetailsImer findByBeneficiaryRegIdAndVisitCode(Long beneficiaryRegId, Long visitCode); + + List findByCreatedBy(String userName); + + @Query(value = "SELECT BeneficiaryID FROM db_identity.m_beneficiaryregidmapping " + + "WHERE BenRegId = :benRegId AND Deleted = 0", nativeQuery = true) + Long getBeneficiaryId(@Param("benRegId") Long benRegId); + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java index f412a4f6..9ed0943c 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java @@ -23,6 +23,8 @@ List getChildVaccinationDetails(@Param("userId") String userId "v.category = 'CHILD'", nativeQuery = true) Integer getFirstYearVaccineCountForBenId(@Param("benRegId") Long benRegId); + + @Query(value = "select count(*) from db_iemr.m_immunizationservicevaccination v where v.Currentimmunizationserviceid in (1,2,3,4,5) " + "and v.category = 'CHILD'", nativeQuery = true) Integer getFirstYearVaccineCount(); diff --git a/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java new file mode 100644 index 00000000..e63835a9 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java @@ -0,0 +1,14 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ChronicDiseaseVisitEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface ChronicDiseaseVisitRepository + extends JpaRepository { + + List findByUserID(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/DewormingFormRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DewormingFormRepo.java new file mode 100644 index 00000000..a1b3ee7c --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DewormingFormRepo.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.DewormingForm; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface DewormingFormRepo extends JpaRepository { + // You can add custom query methods here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseAESJERepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseAESJERepository.java new file mode 100644 index 00000000..03cc8fd0 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseAESJERepository.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ScreeningAesje; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface DiseaseAESJERepository extends JpaRepository { + Optional findByBenId(Long benId); + // Custom queries can be added here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseFilariasisRepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseFilariasisRepository.java new file mode 100644 index 00000000..4e2e88b8 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseFilariasisRepository.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ScreeningFilariasis; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface DiseaseFilariasisRepository extends JpaRepository { + Optional findByBenId(Long benId); + // Custom queries can be added here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseKalaAzarRepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseKalaAzarRepository.java new file mode 100644 index 00000000..caa0fa64 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseKalaAzarRepository.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ScreeningKalaAzar; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface DiseaseKalaAzarRepository extends JpaRepository { + Optional findByBenId(Long benId); + // Custom queries can be added here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java new file mode 100644 index 00000000..567b62a5 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java @@ -0,0 +1,19 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ScreeningLeprosy; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface DiseaseLeprosyRepository extends JpaRepository { + Optional findByBenId(Long benId); + + // Custom queries can be added here if needed + @Query("SELECT s FROM ScreeningLeprosy s WHERE s.createdBy = :createdBy") + List getByCreatedBy(@Param("createdBy") String createdBy); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseMalariaRepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseMalariaRepository.java new file mode 100644 index 00000000..80c1c1bb --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseMalariaRepository.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.ScreeningMalaria; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Optional; + +@Repository +public interface DiseaseMalariaRepository extends JpaRepository { + Optional findByBenId(Long benId); + // Custom queries can be added here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java index 41a17fc1..d3ac8edf 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java @@ -4,8 +4,9 @@ import org.springframework.stereotype.Repository; import com.iemr.flw.domain.iemr.M_User; - @Repository public interface EmployeeMasterRepo extends JpaRepository { + M_User findByUserID(Integer userID); + M_User getUserByUserID(Integer parseLong); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java new file mode 100644 index 00000000..fd713c44 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java @@ -0,0 +1,14 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.EyeCheckupVisit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public +interface EyeCheckUpVisitRepo extends JpaRepository { + List findByUserId(Integer userId); + List findByCreatedBy(String userName); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/FilariasisCampaignRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FilariasisCampaignRepo.java new file mode 100644 index 00000000..1fe0d3e2 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/FilariasisCampaignRepo.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.FilariasisCampaign; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FilariasisCampaignRepo extends JpaRepository { + Page findByUserId(Integer userId, Pageable pageable); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/GeneralOpdRepo.java b/src/main/java/com/iemr/flw/repo/iemr/GeneralOpdRepo.java new file mode 100644 index 00000000..fe944765 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/GeneralOpdRepo.java @@ -0,0 +1,68 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* @@ -0,0 +1,212 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.GeneralOpdData; +import io.lettuce.core.dynamic.annotation.Param; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + + +@Repository +public interface GeneralOpdRepo extends JpaRepository { + + @Query(value = """ + SELECT ibfo.* + FROM db_iemr.i_ben_flow_outreach ibfo + JOIN db_identity.m_beneficiaryregidmapping mbrm + ON ibfo.beneficiary_reg_id = mbrm.BenRegId + WHERE ibfo.visit_category = 'General OPD' + AND ibfo.beneficiary_visit_code <> 0 + AND ibfo.villageID = :villageID + AND ibfo.created_by =:userName + AND (ibfo.deleted IS NULL OR ibfo.deleted = 0) + AND (mbrm.Deleted IS NULL OR mbrm.Deleted = 0) + ORDER BY ibfo.created_date DESC + """, + countQuery = """ + SELECT COUNT(*) + FROM db_iemr.i_ben_flow_outreach ibfo + JOIN db_identity.m_beneficiaryregidmapping mbrm + ON ibfo.beneficiary_reg_id = mbrm.BenRegId + WHERE ibfo.visit_category = 'General OPD' + AND ibfo.beneficiary_visit_code <> 0 + AND ibfo.villageID = :villageID + AND (ibfo.deleted IS NULL OR ibfo.deleted = 0) + AND (mbrm.Deleted IS NULL OR mbrm.Deleted = 0) + """, + nativeQuery = true) + Page findFilteredOutreachData( + @Param("villageID") Integer villageID, + Pageable pageable,@Param("userName") String userName); + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java index 706e07f0..655c0547 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java @@ -12,9 +12,14 @@ @Repository public interface HbncVisitRepo extends JpaRepository { - @Query(value = "SELECT hbnc FROM HbncVisit hbnc WHERE hbnc.createdBy = :userId and hbnc.createdDate >= :fromDate and hbnc.createdDate <= :toDate") - List getHbncVisitDetails(@Param("userId") String userId, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); +// @Query(value = "SELECT hbnc FROM HbncVisit hbnc WHERE hbnc.createdBy = :userId and hbnc.createdDate >= :fromDate and hbnc.createdDate <= :toDate") +// List getHbncVisitDetails(@Param("userId") String userId, +// @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + + @Query("SELECT v FROM HbncVisit v WHERE v.beneficiaryId = :beneficiaryId AND v.visit_day = :visitDay") + HbncVisit findByBeneficiaryIdAndVisit_day(@Param("beneficiaryId") Long beneficiaryId, + @Param("visitDay") String visitDay); + + List findByAshaId(Integer ashaId); - HbncVisit findHbncVisitByBenIdAndVisitNo(Long benId, Integer visitNo); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/HbycRepo.java b/src/main/java/com/iemr/flw/repo/iemr/HbycRepo.java index 18d37b3d..15f35e23 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/HbycRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/HbycRepo.java @@ -1,6 +1,8 @@ package com.iemr.flw.repo.iemr; import com.iemr.flw.domain.iemr.HBYC; +import com.iemr.flw.domain.iemr.HbncVisit; +import com.iemr.flw.domain.iemr.HbycChildVisit; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -10,11 +12,13 @@ import java.util.List; @Repository -public interface HbycRepo extends JpaRepository { +public interface HbycRepo extends JpaRepository { - HBYC findHBYCByBenIdAndCreatedDate(Long benId, Timestamp createdDate); - @Query(" SELECT hbyc FROM HBYC hbyc WHERE hbyc.createdBy = :userId and hbyc.createdDate >= :fromDate and hbyc.createdDate <= :toDate") - List getAllHbycByBenId(@Param("userId") String userId, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + List findByUserId(Integer ashaId); + + @Query("SELECT v FROM HbycChildVisit v WHERE v.beneficiaryId = :beneficiaryId AND v.visit_day = :visitDay") + HbycChildVisit findByBeneficiaryIdAndVisit_day(@Param("beneficiaryId") Long beneficiaryId, + @Param("visitDay") String visitDay); + } diff --git a/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java new file mode 100644 index 00000000..40cbd60b --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java @@ -0,0 +1,12 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.IFAFormSubmissionData; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import java.util.List; + +@Repository +public interface IFAFormSubmissionRepository extends JpaRepository { + + List findByUserId(Integer userName); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/IRSRoundRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IRSRoundRepo.java new file mode 100644 index 00000000..e083fed4 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IRSRoundRepo.java @@ -0,0 +1,14 @@ + +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.IRSRound; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public +interface IRSRoundRepo extends JpaRepository { + List findByHouseholdId(Long householdId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/IfaDistributionRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IfaDistributionRepository.java new file mode 100644 index 00000000..a1a3ae8d --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IfaDistributionRepository.java @@ -0,0 +1,10 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.IfaDistribution; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface IfaDistributionRepository extends JpaRepository { + List findByUserId(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java new file mode 100644 index 00000000..4ba40dc6 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java @@ -0,0 +1,14 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.IncentiveActivityLangMapping; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +public interface IncentiveActivityLangMappingRepo extends JpaRepository { + IncentiveActivityLangMapping findByIdAndName(Long activityId,String activityName); + List findAllByIdIn(List ids); + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java new file mode 100644 index 00000000..9bac8d21 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java @@ -0,0 +1,18 @@ +package com.iemr.flw.repo.iemr; + +import java.util.Optional; +import com.iemr.flw.domain.iemr.IncentivePendingActivity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + + +@Repository +public interface IncentivePendingActivityRepository extends JpaRepository { + + Optional + findByUserIdAndModuleNameAndActivityId( + Integer userId, + String moduleName, + Long activityId + ); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java index 4d473911..2c10f69e 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -16,6 +16,41 @@ public interface IncentiveRecordRepo extends JpaRepository= :fromDate and record.startDate <= :toDate and record.endDate >= :fromDate and record.endDate <= :toDate ") List findRecordsByAsha(@Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate,@Param("toDate") Timestamp toDate); + + + + @Query("select record from IncentiveActivityRecord record where record.ashaId = :ashaId") + List findRecordsByAsha(@Param("ashaId") Integer ashaId); + + + // RecordRepo — existing records batch mein fetch karo + @Query("SELECT r FROM IncentiveActivityRecord r " + + "WHERE r.activityId = :activityId " + + "AND r.benId IN :benIds " + + "AND r.ashaId = :ashaId") + List findExistingRecords( + @Param("activityId") Long activityId, + @Param("benIds") List benIds, + @Param("ashaId") Integer ashaId + ); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java index ff169687..5dda5900 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java @@ -9,7 +9,9 @@ import org.springframework.stereotype.Repository; import java.sql.Timestamp; +import java.util.Collection; import java.util.List; +import java.util.Set; @Repository public interface IncentivesRepo extends JpaRepository { @@ -17,8 +19,29 @@ public interface IncentivesRepo extends JpaRepository { @Query("select inc from IncentiveActivity inc where inc.name = :name and inc.group = :group and inc.isDeleted = false") IncentiveActivity findIncentiveMasterByNameAndGroup(@Param("name") String name, @Param("group") String group); -// @Query("select record from IncentiveActivityRecord record where record.activityId = :id and record.createdDate = :createdDate and record.benId = :benId") -// IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId(@Param("id") Long id, @Param("createdDate") Timestamp createdDate, @Param("benId") Long benId); -// -// List getByUserId(Integer ashaId, Timestamp fromDate, Timestamp toDate); -} + @Query("SELECT a FROM IncentiveActivity a " + + "WHERE a.id = :activityId AND " + + "((:isActivity = true AND a.group = 'ACTIVITY') OR (:isActivity = false AND a.group <> 'ACTIVITY'))") + IncentiveActivity findIncentiveMasterById( + @Param("activityId") Long activityId, + @Param("isActivity") boolean isActivity + ); + + + @Query("select record from IncentiveActivityRecord record where record.activityId = :id and record.createdDate = :createdDate and record.benId = :benId") + IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId(@Param("id") Long id, @Param("createdDate") Timestamp createdDate, @Param("benId") Long benId); + + List findByGroupAndIsDeleted(String group, Boolean isDeleted); + + List findByGroupNotAndIsDeleted(String group, Boolean isDeleted); + + // IncentivesRepo — replaces N calls to findIncentiveMasterById() + @Query("SELECT i.id FROM IncentiveActivity i WHERE i.id IN :ids AND i.isDeleted = false AND " + + "(:isCG = true AND i.group = 'ACTIVITY' OR :isCG = false AND i.group != 'ACTIVITY')") + Set findValidActivityIds(@Param("ids") List ids, @Param("isCG") boolean isCG); + + @Query("SELECT i FROM IncentiveActivity i WHERE i.name IN :names AND i.group = :groupName") + List findIncentiveMasterByNameAndGroup( + @Param("names") List names, + @Param("groupName") String groupName + );} diff --git a/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java b/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java new file mode 100644 index 00000000..4227fb3a --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java @@ -0,0 +1,20 @@ +package com.iemr.flw.repo.iemr; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.iemr.flw.domain.iemr.LeprosyFollowUp; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface LeprosyFollowUpRepository extends JpaRepository { + Optional findByBenId(Long benId); + + // Custom queries can be added here if needed + @Query("SELECT s FROM LeprosyFollowUp s WHERE s.createdBy = :createdBy") + List getByCreatedBy(@Param("createdBy") String createdBy); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/MaaMeetingRepository.java b/src/main/java/com/iemr/flw/repo/iemr/MaaMeetingRepository.java new file mode 100644 index 00000000..230aac54 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/MaaMeetingRepository.java @@ -0,0 +1,12 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.MaaMeeting; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface MaaMeetingRepository extends JpaRepository { + List findByAshaId(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/MalariaFollowUpRepository.java b/src/main/java/com/iemr/flw/repo/iemr/MalariaFollowUpRepository.java new file mode 100644 index 00000000..743d2631 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/MalariaFollowUpRepository.java @@ -0,0 +1,35 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.MalariaFollowUp; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Collection; +import java.util.List; + +public interface MalariaFollowUpRepository extends JpaRepository { + List findByUserId(Integer userId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/MdaFormSubmissionRepository.java b/src/main/java/com/iemr/flw/repo/iemr/MdaFormSubmissionRepository.java new file mode 100644 index 00000000..a9eddd4a --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/MdaFormSubmissionRepository.java @@ -0,0 +1,17 @@ +package com.iemr.flw.repo.iemr; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.iemr.flw.domain.iemr.MdaDistributionData; +import com.iemr.flw.dto.iemr.MdaFormSubmissionResponse; + +import java.util.List; + +@Repository +public interface MdaFormSubmissionRepository extends JpaRepository { + List findByCreatedBy(String createdBy); + + List findByUserName(String userName); + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/MicroBirthPlanRepository.java b/src/main/java/com/iemr/flw/repo/iemr/MicroBirthPlanRepository.java new file mode 100644 index 00000000..0cec1fba --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/MicroBirthPlanRepository.java @@ -0,0 +1,15 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.MicroBirthPlan; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface MicroBirthPlanRepository extends JpaRepository { + Optional findByBenId(Long benId); + + List findByUserId(Integer userId); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/MosquitoNetRepository.java b/src/main/java/com/iemr/flw/repo/iemr/MosquitoNetRepository.java new file mode 100644 index 00000000..4d85eade --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/MosquitoNetRepository.java @@ -0,0 +1,12 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.MosquitoNetEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface MosquitoNetRepository extends JpaRepository { + List findByUserId(Integer userId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/OrsCampaignRepo.java b/src/main/java/com/iemr/flw/repo/iemr/OrsCampaignRepo.java new file mode 100644 index 00000000..fbbe380b --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/OrsCampaignRepo.java @@ -0,0 +1,17 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.web.bind.annotation.RequestBody; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface OrsCampaignRepo extends JpaRepository { + Page findByUserId(Integer userId, Pageable pageable); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/OrsDistributionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/OrsDistributionRepo.java new file mode 100644 index 00000000..3d291e7d --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/OrsDistributionRepo.java @@ -0,0 +1,14 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.OrsDistribution; +import com.iemr.flw.domain.iemr.SamVisit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface OrsDistributionRepo extends JpaRepository { + + List findByUserId(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/PHCReviewFormRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PHCReviewFormRepo.java new file mode 100644 index 00000000..5f59e90f --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/PHCReviewFormRepo.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.PHCReviewForm; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PHCReviewFormRepo extends JpaRepository { + // You can add custom query methods here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/PulsePolioCampaignRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PulsePolioCampaignRepo.java new file mode 100644 index 00000000..c2cded97 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/PulsePolioCampaignRepo.java @@ -0,0 +1,13 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PulsePolioCampaignRepo extends JpaRepository { + Page findByUserId(Integer userId, Pageable pageable); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SMSTemplateRepository.java b/src/main/java/com/iemr/flw/repo/iemr/SMSTemplateRepository.java new file mode 100644 index 00000000..7009a03c --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SMSTemplateRepository.java @@ -0,0 +1,45 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ +package com.iemr.flw.repo.iemr; + +import java.util.List; +import java.util.Optional; + +import com.iemr.flw.domain.iemr.SMSTemplate; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + + +@Repository +public abstract interface SMSTemplateRepository extends CrudRepository +{ + + Optional findBySmsTemplateName(String smsTemplateName); + + SMSTemplate findBySmsTemplateID(Integer smsTemplateID); + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SamVisitRepository.java b/src/main/java/com/iemr/flw/repo/iemr/SamVisitRepository.java new file mode 100644 index 00000000..54b4ea05 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SamVisitRepository.java @@ -0,0 +1,26 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.SamVisit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +@Repository +public interface SamVisitRepository extends JpaRepository { + + // Find all visits for a particular beneficiary + List findByBeneficiaryId(Long beneficiaryId); + + // Optional: Get latest visit record for a beneficiary + SamVisit findTopByBeneficiaryIdOrderByVisitDateDesc(Long beneficiaryId); + + // Optional: Check if a visit exists for a given date + boolean existsByBeneficiaryIdAndVisitDate(Long beneficiaryId, java.time.LocalDate visitDate); + + List findByUserId(Integer ashaId); + + Optional findByBeneficiaryIdAndVisitDate(Long beneficiaryId, LocalDate visitDate); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SammelanAttachmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/SammelanAttachmentRepository.java new file mode 100644 index 00000000..9563e986 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SammelanAttachmentRepository.java @@ -0,0 +1,14 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.SammelanAttachment; +import com.iemr.flw.domain.iemr.SammelanRecord; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface SammelanAttachmentRepository extends JpaRepository { + + List findBySammelanRecord(SammelanRecord record); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SammelanRecordRepository.java b/src/main/java/com/iemr/flw/repo/iemr/SammelanRecordRepository.java new file mode 100644 index 00000000..1ea31437 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SammelanRecordRepository.java @@ -0,0 +1,16 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.SammelanRecord; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.time.LocalDate; +import java.util.List; + +@Repository +public interface SammelanRecordRepository extends JpaRepository { + + + // Fetch history + List findByAshaId(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java new file mode 100644 index 00000000..31345dd4 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -0,0 +1,17 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.TBConfirmedCase; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface TBConfirmedTreatmentRepository + extends JpaRepository { + + List findByBenId(Long benId); + List findByUserId(Integer benId); + +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java index 4a7b09ac..899a7ffd 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -20,4 +20,8 @@ public interface UserServiceRoleRepo extends JpaRepository { + List findByAshaId(Integer ashaId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/VhncFormRepo.java b/src/main/java/com/iemr/flw/repo/iemr/VhncFormRepo.java new file mode 100644 index 00000000..4b7ed3cf --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/VhncFormRepo.java @@ -0,0 +1,34 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.VhncForm; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface VhncFormRepo extends JpaRepository { + // You can add custom query methods here if needed +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/VhndRepo.java b/src/main/java/com/iemr/flw/repo/iemr/VhndRepo.java new file mode 100644 index 00000000..e792cfb8 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/VhndRepo.java @@ -0,0 +1,38 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.VHNDForm; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface VhndRepo extends JpaRepository { + + + List findByUserId(long longValue); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/AdolescentHealthService.java b/src/main/java/com/iemr/flw/service/AdolescentHealthService.java new file mode 100644 index 00000000..522b40d6 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/AdolescentHealthService.java @@ -0,0 +1,13 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.AdolescentHealthDTO; +import org.springframework.stereotype.Service; + +import java.util.List; +public interface AdolescentHealthService { + String saveAll(AdolescentHealthDTO adolescentHealthDTO); + List getAllAdolescentHealth(GetBenRequestHandler getBenRequestHandler); + +} diff --git a/src/main/java/com/iemr/flw/service/AshaProfileService.java b/src/main/java/com/iemr/flw/service/AshaProfileService.java new file mode 100644 index 00000000..a5071409 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/AshaProfileService.java @@ -0,0 +1,12 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.AshaWorker; +import org.springframework.stereotype.Service; + +@Service +public interface AshaProfileService { + AshaWorker saveEditData(AshaWorker ashaWorkerRequest); + + AshaWorker getProfileData(Integer userId ); + +} diff --git a/src/main/java/com/iemr/flw/service/BeneficiaryService.java b/src/main/java/com/iemr/flw/service/BeneficiaryService.java index 2be7260b..e69bc887 100644 --- a/src/main/java/com/iemr/flw/service/BeneficiaryService.java +++ b/src/main/java/com/iemr/flw/service/BeneficiaryService.java @@ -1,9 +1,16 @@ package com.iemr.flw.service; import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.EyeCheckupRequestDTO; +import com.iemr.flw.dto.iemr.SAMResponseDTO; + +import java.util.List; public interface BeneficiaryService { String getBenData(GetBenRequestHandler requestDTO, String authorisation) throws Exception; + String saveEyeCheckupVsit(List eyeCheckupRequestDTOS,String token); + + List getEyeCheckUpVisit(GetBenRequestHandler request,String token); } diff --git a/src/main/java/com/iemr/flw/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java new file mode 100644 index 00000000..26c67a6a --- /dev/null +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -0,0 +1,24 @@ +package com.iemr.flw.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.domain.iemr.FilariasisCampaign; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.utils.exception.IEMRException; + +import java.util.List; + +public interface CampaignService { + List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException, JsonProcessingException; + + List savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException, JsonProcessingException; + + List getOrsCampaign(String token) throws IEMRException; + + List getPolioCampaign(String token) throws IEMRException; + + List saveFilariasisCampaign(List filariasisCampaignDTOS, String token) throws IEMRException, JsonProcessingException; + + List getAllFilariasisCampaign(String token) throws IEMRException; +} diff --git a/src/main/java/com/iemr/flw/service/ChildCareService.java b/src/main/java/com/iemr/flw/service/ChildCareService.java index cb5ec515..bbd5c96f 100644 --- a/src/main/java/com/iemr/flw/service/ChildCareService.java +++ b/src/main/java/com/iemr/flw/service/ChildCareService.java @@ -1,20 +1,19 @@ package com.iemr.flw.service; +import com.iemr.flw.domain.iemr.IfaDistribution; +import com.iemr.flw.domain.iemr.SamVisitResponseDTO; import com.iemr.flw.dto.identity.GetBenRequestHandler; -import com.iemr.flw.dto.iemr.ChildVaccinationDTO; -import com.iemr.flw.dto.iemr.HbncRequestDTO; -import com.iemr.flw.dto.iemr.HbycDTO; -import com.iemr.flw.dto.iemr.VaccineDTO; +import com.iemr.flw.dto.iemr.*; import java.util.List; public interface ChildCareService { - String registerHBYC(List hbycDTOs); + String registerHBYC(List hbycDTOs); - List getHbycRecords(GetBenRequestHandler dto); + List getHbycRecords(GetBenRequestHandler dto); - List getHBNCDetails(GetBenRequestHandler dto); + List getHBNCDetails(GetBenRequestHandler dto); String saveHBNCDetails(List hbncRequestDTOs); @@ -23,4 +22,18 @@ public interface ChildCareService { String saveChildVaccinationDetails(List childVaccinationDTOs); List getAllChildVaccines(String category); + + String saveSamDetails(List samRequest); + + List getSamVisitsByBeneficiary(GetBenRequestHandler dto); + + String saveOrsDistributionDetails(List orsDistributionDTOS); + + List getOrdDistrubtion(GetBenRequestHandler request); + + List saveAllIfa(List dtoList); + + List getByBeneficiaryId(GetBenRequestHandler request); + + } diff --git a/src/main/java/com/iemr/flw/service/CoupleService.java b/src/main/java/com/iemr/flw/service/CoupleService.java index b6f60177..0dd27341 100644 --- a/src/main/java/com/iemr/flw/service/CoupleService.java +++ b/src/main/java/com/iemr/flw/service/CoupleService.java @@ -3,12 +3,12 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.EligibleCoupleDTO; import com.iemr.flw.dto.iemr.EligibleCoupleTrackingDTO; +import org.springframework.web.multipart.MultipartFile; import java.util.List; public interface CoupleService { - String registerEligibleCouple(List eligibleCoupleDTOs); String registerEligibleCoupleTracking(List eligibleCoupleTrackingDTOs); @@ -16,4 +16,8 @@ public interface CoupleService { List getEligibleCoupleTracking(GetBenRequestHandler requestDto); + String registerEligibleCouple(List eligibleCoupleDTOs, MultipartFile kitPhoto1, MultipartFile kitPhoto2); + + String registerEligibleCouple(List eligibleCoupleDTOs); + } diff --git a/src/main/java/com/iemr/flw/service/CrashLogService.java b/src/main/java/com/iemr/flw/service/CrashLogService.java new file mode 100644 index 00000000..f0ffe35e --- /dev/null +++ b/src/main/java/com/iemr/flw/service/CrashLogService.java @@ -0,0 +1,9 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.crashlogs.CrashLogRequest; +import org.springframework.web.multipart.MultipartFile; +import com.iemr.flw.utils.exception.IEMRException; + +public interface CrashLogService { + String saveCrashLog(CrashLogRequest request, Integer userId, MultipartFile file) throws IEMRException; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/DiseaseControlService.java b/src/main/java/com/iemr/flw/service/DiseaseControlService.java new file mode 100644 index 00000000..65e315dc --- /dev/null +++ b/src/main/java/com/iemr/flw/service/DiseaseControlService.java @@ -0,0 +1,52 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service; + +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.utils.exception.IEMRException; + +import java.util.List; + +public interface DiseaseControlService { + public String saveMalaria(MalariaDTO diseaseControlDTO); + public String saveKalaAzar(KalaAzarDTO kalaAzarDTO); + public String saveAES(AesJeDTO aesJeDTO); + public String saveFilaria(FilariaDTO filariaDTO); + public String saveLeprosy(LeprosyDTO leprosyDTO); + public Object getAllScreeningData(GetDiseaseRequestHandler getDiseaseRequestHandler); + + public List saveMosquitoMobilizationNet(List mosquitoNetDTOList); + + List getAllMosquitoMobilizationNet(Integer userId); + List getAllLeprosyData(String createdBy); + + public String saveLeprosyFollowUp(LeprosyFollowUpDTO leprosyDTO); + List getAllLeprosyFollowUpData(String createdBy); + + List saveChronicDiseaseVisit(List requestList,String token) throws IEMRException; + + List getCdtfVisits(GetBenRequestHandler getBenRequestHandler); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java b/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java new file mode 100644 index 00000000..1c4369da --- /dev/null +++ b/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java @@ -0,0 +1,13 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.M_User; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface EmployeeMasterInter { + public M_User getUserDetails(Integer userID); + + List getAllUsers(); +} diff --git a/src/main/java/com/iemr/flw/service/FileStorageService.java b/src/main/java/com/iemr/flw/service/FileStorageService.java new file mode 100644 index 00000000..d22352ce --- /dev/null +++ b/src/main/java/com/iemr/flw/service/FileStorageService.java @@ -0,0 +1,38 @@ +package com.iemr.flw.service; + +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.UUID; + +@Service +public class FileStorageService { + + private static final String UPLOAD_DIR = "uploads/"; // Define your upload directory + + public String storeFile(MultipartFile file) throws IOException { + if (file.isEmpty()) { + throw new IllegalStateException("Cannot store empty file."); + } + + // Create directories if they do not exist + File uploadDir = new File(UPLOAD_DIR); + if (!uploadDir.exists()) { + uploadDir.mkdirs(); + } + + // Generate a unique file name + String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename(); + Path filePath = Paths.get(UPLOAD_DIR + fileName); + + // Save file + Files.write(filePath, file.getBytes()); + + return filePath.toString(); // Return the saved file path + } +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/GeneralOpdService.java b/src/main/java/com/iemr/flw/service/GeneralOpdService.java new file mode 100644 index 00000000..daa46636 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/GeneralOpdService.java @@ -0,0 +1,36 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* @@ -0,0 +1,212 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.GeneralOpdData; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.GeneralOpdDto; +import org.springframework.data.domain.Page; + +import java.util.List; + +public interface GeneralOpdService { + public Page getOutreachData(Integer villageId,String userName); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java b/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java new file mode 100644 index 00000000..1ecd338d --- /dev/null +++ b/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java @@ -0,0 +1,14 @@ +package com.iemr.flw.service; + + +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.IFAFormSubmissionRequest; +import com.iemr.flw.dto.iemr.IFAFormSubmissionResponse; +import org.springframework.stereotype.Service; + +import java.util.List; +@Service +public interface IFAFormSubmissionService { + String saveFormData(List requests); + List getFormData(GetBenRequestHandler getBenRequestHandler); +} diff --git a/src/main/java/com/iemr/flw/service/IRSRoundService.java b/src/main/java/com/iemr/flw/service/IRSRoundService.java new file mode 100644 index 00000000..438702d5 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/IRSRoundService.java @@ -0,0 +1,14 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.IRSRound; +import com.iemr.flw.dto.iemr.IRSRoundDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface IRSRoundService { + List addRounds(List dtos,Integer userId,String userName); + + List getRounds(Long householdId); +} diff --git a/src/main/java/com/iemr/flw/service/IncentiveService.java b/src/main/java/com/iemr/flw/service/IncentiveService.java index ab49a0cd..d6bb5550 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveService.java @@ -3,6 +3,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.IncentiveActivityDTO; import com.iemr.flw.dto.iemr.IncentiveRequestDTO; +import com.iemr.flw.dto.iemr.PendingActivityDTO; import java.util.List; @@ -13,4 +14,6 @@ public interface IncentiveService { String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO); String getAllIncentivesByUserId(GetBenRequestHandler requestDTO); + + String updateIncentive(PendingActivityDTO pendingActivityDTO); } diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java new file mode 100644 index 00000000..cb23b7b9 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -0,0 +1,242 @@ +package com.iemr.flw.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.*; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.MaaMeetingRequestDTO; +import com.iemr.flw.dto.iemr.MaaMeetingResponseDTO; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.sql.Timestamp; +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class MaaMeetingService { + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + private final MaaMeetingRepository repository; + private final ObjectMapper objectMapper; + + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + + public MaaMeetingService(MaaMeetingRepository repository, ObjectMapper objectMapper) { + this.repository = repository; + this.objectMapper = objectMapper; + } + + public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { + MaaMeeting meeting = new MaaMeeting(); + meeting.setMeetingDate(req.getMeetingDate()); + meeting.setPlace(req.getPlace()); + meeting.setParticipants(req.getParticipants()); + meeting.setAshaId(req.getAshaId()); + meeting.setNoOfLactingMother(req.getNoOfLactingMother()); + meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); + meeting.setVillageName(req.getVillageName()); + meeting.setMitaninActivityCheckList(req.getMitaninActivityCheckList()); + + meeting.setCreatedBy(req.getCreatedBY()); + + // Convert meeting images to Base64 JSON + if (req.getMeetingImages() != null && req.getMeetingImages().length > 0) { + List base64Images = Arrays.stream(req.getMeetingImages()) + .filter(file -> !file.isEmpty()) + .map(file -> { + try { + return Base64.getEncoder().encodeToString(file.getBytes()); + } catch (IOException e) { + throw new RuntimeException("Error converting image to Base64", e); + } + }) + .collect(Collectors.toList()); + + String imagesJson = objectMapper.writeValueAsString(base64Images); + meeting.setMeetingImagesJson(imagesJson); + } + + checkAndAddIncentive(meeting); + + + return repository.save(meeting); + } + + public MaaMeeting updateMeeting(MaaMeetingRequestDTO req) throws JsonProcessingException { + MaaMeeting existingMeeting = repository.findById(req.getId()) + .orElseThrow(() -> new EntityNotFoundException("Meeting not found: " + req.getId())); + + // ✅ NULL CHECK + if (req.getMeetingDate() != null) { + existingMeeting.setMeetingDate(req.getMeetingDate()); + } + if (req.getPlace() != null) { + existingMeeting.setPlace(req.getPlace()); + } + if (req.getParticipants() != null) { + existingMeeting.setParticipants(req.getParticipants()); + } + if (req.getAshaId() != null) { + existingMeeting.setAshaId(req.getAshaId()); + } + if (req.getCreatedBY() != null) { // ✅ Typo fixed: CreatedBY → CreatedBy + existingMeeting.setCreatedBy(req.getCreatedBY()); + } + + // Images - only if provided + if (req.getMeetingImages() != null && req.getMeetingImages().length > 0) { + List base64Images = Arrays.stream(req.getMeetingImages()) + .filter(file -> file != null && !file.isEmpty()) + .map(this::convertToBase64) + .collect(Collectors.toList()); + existingMeeting.setMeetingImagesJson(objectMapper.writeValueAsString(base64Images)); + } + + checkAndAddIncentive(existingMeeting); + if (existingMeeting.getMeetingImagesJson() != null) { + checkAndUpdateIncentive(existingMeeting); + + } + return repository.save(existingMeeting); + } + + + private String convertToBase64(MultipartFile file) { + try { + return Base64.getEncoder().encodeToString(file.getBytes()); + } catch (IOException e) { + throw new RuntimeException("Failed to convert image to Base64: " + file.getOriginalFilename(), e); + } + } + + + public List getAllMeetings(GetBenRequestHandler getBenRequestHandler) throws Exception { + List meetings = repository.findByAshaId(getBenRequestHandler.getAshaId()); + + return meetings.stream().map(meeting -> { + MaaMeetingResponseDTO dto = new MaaMeetingResponseDTO(); + dto.setId(meeting.getId()); + dto.setMeetingDate(meeting.getMeetingDate()); + dto.setPlace(meeting.getPlace()); + dto.setParticipants(meeting.getParticipants()); + dto.setAshaId(meeting.getAshaId()); + dto.setVillageName(meeting.getVillageName()); + dto.setNoOfLactingMother(String.valueOf(meeting.getNoOfLactingMother())); + dto.setNoOfPragnentWomen(String.valueOf(meeting.getNoOfPragnentWomen())); + dto.setMitaninActivityCheckList(meeting.getMitaninActivityCheckList()); + dto.setCreatedBy(meeting.getCreatedBy()); + + try { + if (meeting.getMeetingImagesJson() != null) { + List base64Images = objectMapper.readValue( + meeting.getMeetingImagesJson(), + new TypeReference>() { + } + ); + + dto.setMeetingImages(base64Images); + } else { + dto.setMeetingImages(List.of()); + } + } catch (Exception e) { + dto.setMeetingImages(List.of()); + } + + return dto; + }).collect(Collectors.toList()); + } + + private void updatePendingActivity(Integer userId, Long recordId, Long activityId, String moduleName) { + IncentivePendingActivity incentivePendingActivity = new IncentivePendingActivity(); + incentivePendingActivity.setActivityId(activityId); + incentivePendingActivity.setRecordId(recordId); + incentivePendingActivity.setUserId(userId); + incentivePendingActivity.setModuleName(moduleName); + if (incentivePendingActivity != null) { + incentivePendingActivityRepository.save(incentivePendingActivity); + } + + } + + private void checkAndUpdateIncentive(MaaMeeting meeting) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("MAA_QUARTERLY_MEETING", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("MAA_QUARTERLY_MEETING", GroupName.ACTIVITY.getDisplayName()); + if (incentiveActivityAM != null) { + updateIncentive(incentiveActivityAM, meeting); + } + if (incentiveActivityCH != null) { + updateIncentive(incentiveActivityCH, meeting); + + } + + } + + private void checkAndAddIncentive(MaaMeeting meeting) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("MAA_QUARTERLY_MEETING", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("MAA_QUARTERLY_MEETING", GroupName.ACTIVITY.getDisplayName()); + if (incentiveActivityAM != null) { + addIncentive(incentiveActivityAM, meeting); + } + if (incentiveActivityCH != null) { + addIncentive(incentiveActivityCH, meeting); + + } + + } + + private void addIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay())); + record.setCreatedBy(meeting.getCreatedBy()); + record.setStartDate(Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay())); + record.setEndDate(Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay())); + record.setUpdatedDate(Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay())); + record.setUpdatedBy(meeting.getCreatedBy()); + record.setBenId(0L); + record.setAshaId(meeting.getAshaId()); + if (meeting.getMeetingImagesJson() != null) { + record.setIsEligible(true); + } else { + record.setIsEligible(false); + // updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); + + } + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } + + } + + private void updateIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); + + if (record != null) { + record = new IncentiveActivityRecord(); + record.setIsEligible(true); + recordRepo.save(record); + } + + } + + +} diff --git a/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java b/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java new file mode 100644 index 00000000..324c6cd6 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java @@ -0,0 +1,16 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.iemr.MalariaFollowListUpDTO; +import com.iemr.flw.dto.iemr.MalariaFollowUpDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +public interface MalariaFollowUpService { + + + public Boolean saveFollowUp(MalariaFollowUpDTO dto,String token) ; + + + List getByUserId(Integer userId); +} diff --git a/src/main/java/com/iemr/flw/service/MaternalHealthService.java b/src/main/java/com/iemr/flw/service/MaternalHealthService.java index c4af2768..33de9bc9 100644 --- a/src/main/java/com/iemr/flw/service/MaternalHealthService.java +++ b/src/main/java/com/iemr/flw/service/MaternalHealthService.java @@ -2,6 +2,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.utils.exception.IEMRException; import org.springframework.stereotype.Component; import java.util.List; @@ -25,4 +26,7 @@ public interface MaternalHealthService { String savePNCVisit(List pncVisitDTOs); + String saveANCVisitQuestions(List ancVisitQuestionsDTOS, String authorization) throws IEMRException; + + List getANCCounselling(GetBenRequestHandler requestDTO); } diff --git a/src/main/java/com/iemr/flw/service/MicroBirthPlanService.java b/src/main/java/com/iemr/flw/service/MicroBirthPlanService.java new file mode 100644 index 00000000..9a6e422b --- /dev/null +++ b/src/main/java/com/iemr/flw/service/MicroBirthPlanService.java @@ -0,0 +1,20 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.MicroBirthPlan; +import com.iemr.flw.dto.iemr.MicroBirthPlanDTO; +import com.iemr.flw.repo.iemr.MicroBirthPlanRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; + +public interface MicroBirthPlanService { + public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan); + public List getAllMicroBirthPlans(Integer userId); + + + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/SammelanService.java b/src/main/java/com/iemr/flw/service/SammelanService.java new file mode 100644 index 00000000..ed2e9cb7 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/SammelanService.java @@ -0,0 +1,25 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.iemr.*; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +public interface SammelanService { + /** + * Submit a new Saas Bahu Sammelan record + * @param dto request data + * @return saved SammelanResponseDTO with incentive details + */ + public SammelanResponseDTO submitSammelan(SammelanRequestDTO sammelanRequestDTO); + + /** + * Fetch Sammelan history for given ASHA worker + * @param ashaId ASHA worker ID + * @return list of past SammelanResponseDTO + */ + List getSammelanHistory(Integer ashaId); + +} diff --git a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java new file mode 100644 index 00000000..64505b79 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java @@ -0,0 +1,16 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface TBConfirmedCaseService { + + String save(List tbConfirmedCaseDTO, String token) throws Exception; + + String getByBenId(Long benId, String authorisation) throws Exception; + + String getByUserId(String authorisation) throws Exception; +} diff --git a/src/main/java/com/iemr/flw/service/UwinSessionService.java b/src/main/java/com/iemr/flw/service/UwinSessionService.java new file mode 100644 index 00000000..0756de83 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/UwinSessionService.java @@ -0,0 +1,12 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.UwinSession; +import com.iemr.flw.dto.iemr.UwinSessionRequestDTO; +import com.iemr.flw.dto.iemr.UwinSessionResponseDTO; + +import java.util.List; + +public interface UwinSessionService { + UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exception; + List getSessionsByAsha(Integer ashaId) throws Exception; +} diff --git a/src/main/java/com/iemr/flw/service/VillageLevelFormService.java b/src/main/java/com/iemr/flw/service/VillageLevelFormService.java new file mode 100644 index 00000000..2227acaa --- /dev/null +++ b/src/main/java/com/iemr/flw/service/VillageLevelFormService.java @@ -0,0 +1,45 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service; + +import com.iemr.flw.dto.iemr.*; +import org.springframework.stereotype.Service; + +import java.util.List; +@Service +public interface VillageLevelFormService { + + Boolean saveForm(VhndDto dto); + + Boolean saveVhncForm(VhncDto dto); + + Boolean savePhcForm(PhcReviewMeetingDTO dto); + + Boolean saveAhdForm(AhdMeetingDto dto); + + Boolean saveDewormingForm(DewormingDto dto); + + List getAll(GetVillageLevelRequestHandler getVillageLevelRequestHandler); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/health/HealthService.java b/src/main/java/com/iemr/flw/service/health/HealthService.java new file mode 100644 index 00000000..084ffe5e --- /dev/null +++ b/src/main/java/com/iemr/flw/service/health/HealthService.java @@ -0,0 +1,517 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +*/ + +package com.iemr.flw.service.health; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; +import jakarta.annotation.PreDestroy; +import javax.sql.DataSource; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import java.lang.management.ManagementFactory; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +@Service +public class HealthService { + + private static final Logger logger = LoggerFactory.getLogger(HealthService.class); + + private static final String STATUS_KEY = "status"; + private static final String STATUS_UP = "UP"; + private static final String STATUS_DOWN = "DOWN"; + private static final String STATUS_DEGRADED = "DEGRADED"; + private static final String SEVERITY_KEY = "severity"; + private static final String SEVERITY_OK = "OK"; + private static final String SEVERITY_WARNING = "WARNING"; + private static final String SEVERITY_CRITICAL = "CRITICAL"; + private static final String ERROR_KEY = "error"; + private static final String MESSAGE_KEY = "message"; + private static final String RESPONSE_TIME_KEY = "responseTimeMs"; + private static final long MYSQL_TIMEOUT_SECONDS = 3; + private static final long REDIS_TIMEOUT_SECONDS = 3; + + private static final long ADVANCED_CHECKS_THROTTLE_SECONDS = 30; + private static final long RESPONSE_TIME_THRESHOLD_MS = 2000; + + private static final String DIAGNOSTIC_LOCK_WAIT = "MYSQL_LOCK_WAIT"; + private static final String DIAGNOSTIC_SLOW_QUERIES = "MYSQL_SLOW_QUERIES"; + private static final String DIAGNOSTIC_POOL_EXHAUSTED = "MYSQL_POOL_EXHAUSTED"; + private static final String DIAGNOSTIC_LOG_TEMPLATE = "Diagnostic: {}"; + + private final DataSource dataSource; + private final RedisTemplate redisTemplate; + private final ExecutorService executorService; + + private volatile long lastAdvancedCheckTime = 0; + private volatile AdvancedCheckResult cachedAdvancedCheckResult = null; + private final ReentrantReadWriteLock advancedCheckLock = new ReentrantReadWriteLock(); + private final AtomicBoolean advancedCheckInProgress = new AtomicBoolean(false); + + private static final boolean ADVANCED_HEALTH_CHECKS_ENABLED = true; + + public HealthService(DataSource dataSource, + @Autowired(required = false) RedisTemplate redisTemplate) { + this.dataSource = dataSource; + this.redisTemplate = redisTemplate; + this.executorService = Executors.newFixedThreadPool(6); + } + + @PreDestroy + public void shutdown() { + if (executorService != null && !executorService.isShutdown()) { + try { + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + logger.warn("ExecutorService did not terminate gracefully"); + } + } catch (InterruptedException e) { + executorService.shutdownNow(); + Thread.currentThread().interrupt(); + logger.warn("ExecutorService shutdown interrupted", e); + } + } + } + + public Map checkHealth() { + Map response = new LinkedHashMap<>(); + response.put("timestamp", Instant.now().toString()); + + Map mysqlStatus = new ConcurrentHashMap<>(); + Map redisStatus = new ConcurrentHashMap<>(); + + if (!executorService.isShutdown()) { + performHealthChecks(mysqlStatus, redisStatus); + } + + ensurePopulated(mysqlStatus, "MySQL"); + ensurePopulated(redisStatus, "Redis"); + + Map> components = new LinkedHashMap<>(); + components.put("mysql", mysqlStatus); + components.put("redis", redisStatus); + + response.put("components", components); + response.put(STATUS_KEY, computeOverallStatus(components)); + + return response; + } + + private void performHealthChecks(Map mysqlStatus, Map redisStatus) { + Future mysqlFuture = null; + Future redisFuture = null; + try { + mysqlFuture = executorService.submit( + () -> performHealthCheck("MySQL", mysqlStatus, this::checkMySQLHealthSync)); + redisFuture = executorService.submit( + () -> performHealthCheck("Redis", redisStatus, this::checkRedisHealthSync)); + + awaitHealthChecks(mysqlFuture, redisFuture); + } catch (TimeoutException e) { + logger.warn("Health check aggregate timeout after {} seconds", getMaxTimeout()); + cancelFutures(mysqlFuture, redisFuture); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + logger.warn("Health check was interrupted"); + cancelFutures(mysqlFuture, redisFuture); + } catch (Exception e) { + logger.warn("Health check execution error: {}", e.getMessage()); + cancelFutures(mysqlFuture, redisFuture); + } + } + + private void awaitHealthChecks(Future mysqlFuture, Future redisFuture) throws TimeoutException, InterruptedException, ExecutionException { + long maxTimeout = getMaxTimeout(); + long deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(maxTimeout); + + mysqlFuture.get(maxTimeout, TimeUnit.SECONDS); + long remainingNs = deadlineNs - System.nanoTime(); + + if (remainingNs > 0) { + redisFuture.get(remainingNs, TimeUnit.NANOSECONDS); + } else { + redisFuture.cancel(true); + } + } + + private long getMaxTimeout() { + return Math.max(MYSQL_TIMEOUT_SECONDS, REDIS_TIMEOUT_SECONDS) + 1; + } + + private void cancelFutures(Future mysqlFuture, Future redisFuture) { + if (mysqlFuture != null) mysqlFuture.cancel(true); + if (redisFuture != null) redisFuture.cancel(true); + } + + private void ensurePopulated(Map status, String componentName) { + if (!status.containsKey(STATUS_KEY)) { + status.put(STATUS_KEY, STATUS_DOWN); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, componentName + " health check did not complete in time"); + } + } + + private HealthCheckResult checkMySQLHealthSync() { + try (Connection connection = dataSource.getConnection(); + PreparedStatement stmt = connection.prepareStatement("SELECT 1 as health_check")) { + + stmt.setQueryTimeout((int) MYSQL_TIMEOUT_SECONDS); + + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) { + return new HealthCheckResult(false, "No result from health check query", false); + } + } + } catch (Exception e) { + logger.warn("MySQL health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "MySQL connection failed", false); + } + boolean isDegraded = performAdvancedMySQLChecksWithThrottle(); + return new HealthCheckResult(true, null, isDegraded); + } + + private HealthCheckResult checkRedisHealthSync() { + if (redisTemplate == null) { + return new HealthCheckResult(true, "Redis not configured — skipped", false); + } + + try { + String pong = redisTemplate.execute((org.springframework.data.redis.core.RedisCallback) (connection) -> connection.ping()); + + if ("PONG".equals(pong)) { + return new HealthCheckResult(true, null, false); + } + + return new HealthCheckResult(false, "Redis PING failed", false); + + } catch (Exception e) { + logger.warn("Redis health check failed: {}", e.getMessage(), e); + return new HealthCheckResult(false, "Redis connection failed", false); + } + } + + private Map performHealthCheck(String componentName, + Map status, + Supplier checker) { + long startTime = System.currentTimeMillis(); + + try { + HealthCheckResult result = checker.get(); + long responseTime = System.currentTimeMillis() - startTime; + + String componentStatus; + if (!result.isHealthy) { + componentStatus = STATUS_DOWN; + } else if (result.isDegraded) { + componentStatus = STATUS_DEGRADED; + } else { + componentStatus = STATUS_UP; + } + status.put(STATUS_KEY, componentStatus); + + status.put(RESPONSE_TIME_KEY, responseTime); + + String severity = determineSeverity(result.isHealthy, responseTime, result.isDegraded); + status.put(SEVERITY_KEY, severity); + + if (result.error != null) { + String fieldKey = result.isHealthy ? MESSAGE_KEY : ERROR_KEY; + status.put(fieldKey, result.error); + } + + return status; + + } catch (Exception e) { + long responseTime = System.currentTimeMillis() - startTime; + logger.error("{} health check failed with exception: {}", componentName, e.getMessage(), e); + + status.put(STATUS_KEY, STATUS_DOWN); + status.put(RESPONSE_TIME_KEY, responseTime); + status.put(SEVERITY_KEY, SEVERITY_CRITICAL); + status.put(ERROR_KEY, "Health check failed with an unexpected error"); + + return status; + } + } + + private String determineSeverity(boolean isHealthy, long responseTimeMs, boolean isDegraded) { + if (!isHealthy) { + return SEVERITY_CRITICAL; + } + + if (isDegraded) { + return SEVERITY_WARNING; + } + + if (responseTimeMs > RESPONSE_TIME_THRESHOLD_MS) { + return SEVERITY_WARNING; + } + + return SEVERITY_OK; + } + + private String computeOverallStatus(Map> components) { + boolean hasCritical = false; + boolean hasDegraded = false; + + for (Map componentStatus : components.values()) { + String status = (String) componentStatus.get(STATUS_KEY); + String severity = (String) componentStatus.get(SEVERITY_KEY); + + if (STATUS_DOWN.equals(status) || SEVERITY_CRITICAL.equals(severity)) { + hasCritical = true; + } + + if (STATUS_DEGRADED.equals(status)) { + hasDegraded = true; + } + + if (SEVERITY_WARNING.equals(severity)) { + hasDegraded = true; + } + } + + if (hasCritical) { + return STATUS_DOWN; + } + + if (hasDegraded) { + return STATUS_DEGRADED; + } + + return STATUS_UP; + } + + private boolean performAdvancedMySQLChecksWithThrottle() { + if (!ADVANCED_HEALTH_CHECKS_ENABLED) { + return false; + } + + long currentTime = System.currentTimeMillis(); + + advancedCheckLock.readLock().lock(); + try { + if (cachedAdvancedCheckResult != null && + (currentTime - lastAdvancedCheckTime) < ADVANCED_CHECKS_THROTTLE_SECONDS * 1000) { + return cachedAdvancedCheckResult.isDegraded; + } + } finally { + advancedCheckLock.readLock().unlock(); + } + + // Only one thread may submit; others fall back to the (stale) cache + if (!advancedCheckInProgress.compareAndSet(false, true)) { + advancedCheckLock.readLock().lock(); + try { + return cachedAdvancedCheckResult != null && cachedAdvancedCheckResult.isDegraded; + } finally { + advancedCheckLock.readLock().unlock(); + } + } + + try { + // Perform DB I/O outside the write lock to avoid lock contention + AdvancedCheckResult result; + try (Connection connection = dataSource.getConnection()) { + result = performAdvancedMySQLChecks(connection); + } catch (Exception e) { + if (e.getCause() instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + logger.debug("Failed to get connection for advanced checks: {}", e.getMessage()); + result = new AdvancedCheckResult(false); + } + + // Re-acquire write lock only to update the cache atomically + advancedCheckLock.writeLock().lock(); + try { + lastAdvancedCheckTime = currentTime; + cachedAdvancedCheckResult = result; + return result.isDegraded; + } finally { + advancedCheckLock.writeLock().unlock(); + } + } finally { + advancedCheckInProgress.set(false); + } + } + + private AdvancedCheckResult performAdvancedMySQLChecks(Connection connection) { + try { + boolean hasIssues = false; + + if (hasLockWaits(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_LOCK_WAIT); + hasIssues = true; + } + + if (hasSlowQueries(connection)) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_SLOW_QUERIES); + hasIssues = true; + } + + if (hasConnectionPoolExhaustion()) { + logger.warn(DIAGNOSTIC_LOG_TEMPLATE, DIAGNOSTIC_POOL_EXHAUSTED); + hasIssues = true; + } + + return new AdvancedCheckResult(hasIssues); + } catch (Exception e) { + logger.debug("Advanced MySQL checks encountered exception, marking degraded"); + return new AdvancedCheckResult(true); + } + } + + private boolean hasLockWaits(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE (state = 'Waiting for table metadata lock' " + + " OR state = 'Waiting for row lock' " + + " OR state = 'Waiting for lock') " + + "AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int lockCount = rs.getInt(1); + return lockCount > 0; + } + } + } catch (Exception e) { + logger.debug("Could not check for lock waits"); + } + return false; + } + + + private boolean hasSlowQueries(Connection connection) { + try (PreparedStatement stmt = connection.prepareStatement( + "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PROCESSLIST " + + "WHERE command != 'Sleep' AND time > ? AND user = SUBSTRING_INDEX(USER(), '@', 1)")) { + stmt.setQueryTimeout(2); + stmt.setInt(1, 10); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int slowQueryCount = rs.getInt(1); + return slowQueryCount > 3; + } + } + } catch (Exception e) { + logger.debug("Could not check for slow queries"); + } + return false; + } + + private boolean hasConnectionPoolExhaustion() { + if (dataSource instanceof HikariDataSource hikariDataSource) { + try { + HikariPoolMXBean poolMXBean = hikariDataSource.getHikariPoolMXBean(); + + if (poolMXBean != null) { + int activeConnections = poolMXBean.getActiveConnections(); + int maxPoolSize = hikariDataSource.getMaximumPoolSize(); + + int threshold = (int) (maxPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + logger.debug("Could not retrieve HikariCP pool metrics"); + } + } + + return checkPoolMetricsViaJMX(); + } + + private boolean checkPoolMetricsViaJMX() { + try { + MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); + ObjectName objectName = new ObjectName("com.zaxxer.hikari:type=Pool (*)"); + var mBeans = mBeanServer.queryMBeans(objectName, null); + + for (var mBean : mBeans) { + if (evaluatePoolMetrics(mBeanServer, mBean.getObjectName())) { + return true; + } + } + } catch (Exception e) { + logger.debug("Could not access HikariCP pool metrics via JMX"); + } + + logger.debug("Pool exhaustion check disabled: HikariCP metrics unavailable"); + return false; + } + + private boolean evaluatePoolMetrics(MBeanServer mBeanServer, ObjectName objectName) { + try { + Integer activeConnections = (Integer) mBeanServer.getAttribute(objectName, "ActiveConnections"); + Integer maximumPoolSize = (Integer) mBeanServer.getAttribute(objectName, "MaximumPoolSize"); + + if (activeConnections != null && maximumPoolSize != null) { + int threshold = (int) (maximumPoolSize * 0.8); + return activeConnections > threshold; + } + } catch (Exception e) { + // Continue to next MBean + } + return false; + } + + private static class AdvancedCheckResult { + final boolean isDegraded; + + AdvancedCheckResult(boolean isDegraded) { + this.isDegraded = isDegraded; + } + } + + private static class HealthCheckResult { + final boolean isHealthy; + final String error; + final boolean isDegraded; + + HealthCheckResult(boolean isHealthy, String error, boolean isDegraded) { + this.isHealthy = isHealthy; + this.error = error; + this.isDegraded = isDegraded; + } + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java new file mode 100644 index 00000000..43986a8c --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java @@ -0,0 +1,173 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.AdolescentHealthDTO; +import com.iemr.flw.repo.iemr.AdolescentHealthRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.service.AdolescentHealthService; +import jakarta.transaction.Transactional; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +@Service +public class AdolescentHealthServiceImpl implements AdolescentHealthService { + @Autowired + private AdolescentHealthRepo adolescentHealthRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + private static final String INCENTIVE_GROUP = "ADOLESCENT_HEALTH"; + + + @Override + @Transactional + public String saveAll(AdolescentHealthDTO adolescentHealthDTO) { + if (adolescentHealthDTO == null || adolescentHealthDTO.getAdolescentHealths() == null + || adolescentHealthDTO.getAdolescentHealths().isEmpty()) { + return "No records to process"; + } + + for (AdolescentHealth adolescentHealth : adolescentHealthDTO.getAdolescentHealths()) { + // Check if a record with the same benId already exists in the database + Optional existingRecord = adolescentHealthRepo.findByBenId(adolescentHealth.getBenId()); + + if (existingRecord.isPresent()) { + // If record exists, update the existing one + updateAdolescentHealth(existingRecord, adolescentHealth); + } else { + // If the record does not exist, create a new one + adolescentHealthRepo.save(adolescentHealth); + checkAndAddIncentives(adolescentHealth); + } + } + + return "Records updated/added successfully!"; + } + + + public List getAllAdolescentHealth(GetBenRequestHandler getBenRequestHandler) { + // Fetch all records from the database + List adolescentHealths = adolescentHealthRepo.findByUserId(getBenRequestHandler.getUserId()); + + // Convert the list of entity objects to DTO objects + return adolescentHealths.stream() + .map(this::copyEntity) + .collect(Collectors.toList()); + } + + private void updateAdolescentHealth(Optional existingRecord, AdolescentHealth adolescentHealth) { + AdolescentHealth existingAdolescentHealth = existingRecord.get(); + + // Update fields of the existing record with values from the DTO + existingAdolescentHealth.setUserId(adolescentHealth.getUserId()); + existingAdolescentHealth.setVisitDate(adolescentHealth.getVisitDate()); + existingAdolescentHealth.setHealthStatus(adolescentHealth.getHealthStatus()); + existingAdolescentHealth.setIfaTabletDistribution(adolescentHealth.getIfaTabletDistribution()); + existingAdolescentHealth.setQuantityOfIfaTablets(adolescentHealth.getQuantityOfIfaTablets()); + existingAdolescentHealth.setMenstrualHygieneAwarenessGiven(adolescentHealth.getMenstrualHygieneAwarenessGiven()); + existingAdolescentHealth.setSanitaryNapkinDistributed(adolescentHealth.getSanitaryNapkinDistributed()); + existingAdolescentHealth.setNoOfPacketsDistributed(adolescentHealth.getNoOfPacketsDistributed()); + existingAdolescentHealth.setPlace(adolescentHealth.getPlace()); + existingAdolescentHealth.setReferredToHealthFacility(adolescentHealth.getReferredToHealthFacility()); + existingAdolescentHealth.setCounselingProvided(adolescentHealth.getCounselingProvided()); + existingAdolescentHealth.setCounselingType(adolescentHealth.getCounselingType()); + existingAdolescentHealth.setFollowUpDate(adolescentHealth.getFollowUpDate()); + existingAdolescentHealth.setReferralStatus(adolescentHealth.getReferralStatus()); + existingAdolescentHealth.setCreatedBy(adolescentHealth.getCreatedBy()); + existingAdolescentHealth.setCreatedDate(adolescentHealth.getCreatedDate()); + + // Save the updated record back to the database + adolescentHealthRepo.save(existingAdolescentHealth); + } + + private AdolescentHealth copyEntity(AdolescentHealth adolescentHealth) { + AdolescentHealth dto = new AdolescentHealth(); + dto.setId(adolescentHealth.getId()); + dto.setBenId(adolescentHealth.getBenId()); + dto.setUserId(adolescentHealth.getUserId()); + dto.setVisitDate(adolescentHealth.getVisitDate()); + dto.setHealthStatus(adolescentHealth.getHealthStatus()); + dto.setIfaTabletDistribution(adolescentHealth.getIfaTabletDistribution()); + dto.setQuantityOfIfaTablets(adolescentHealth.getQuantityOfIfaTablets()); + dto.setMenstrualHygieneAwarenessGiven(adolescentHealth.getMenstrualHygieneAwarenessGiven()); + dto.setSanitaryNapkinDistributed(adolescentHealth.getSanitaryNapkinDistributed()); + dto.setNoOfPacketsDistributed(adolescentHealth.getNoOfPacketsDistributed()); + dto.setPlace(adolescentHealth.getPlace()); + dto.setReferredToHealthFacility(adolescentHealth.getReferredToHealthFacility()); + dto.setCounselingProvided(adolescentHealth.getCounselingProvided()); + dto.setCounselingType(adolescentHealth.getCounselingType()); + dto.setFollowUpDate(adolescentHealth.getFollowUpDate()); + dto.setReferralStatus(adolescentHealth.getReferralStatus()); + return dto; + } + + private void checkAndAddIncentives(AdolescentHealth adolescentHealth) { + if (adolescentHealth == null || adolescentHealth.getBenId() == null) { + return; + } + + IncentiveActivity sellingSanitaryActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("SELLING_SANITARY", INCENTIVE_GROUP); + IncentiveActivity mobilizingADHActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MOBILIZING_ADOLESCENTS", INCENTIVE_GROUP); + + if (sellingSanitaryActivity != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(sellingSanitaryActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(sellingSanitaryActivity.getId()); + record.setCreatedDate(adolescentHealth.getCreatedDate()); + record.setCreatedBy(adolescentHealth.getCreatedBy()); + record.setStartDate(adolescentHealth.getCreatedDate()); + record.setEndDate(adolescentHealth.getCreatedDate()); + record.setUpdatedDate(adolescentHealth.getCreatedDate()); + record.setUpdatedBy(adolescentHealth.getCreatedBy()); + record.setBenId(adolescentHealth.getBenId().longValue()); + record.setAshaId(adolescentHealth.getUserId()); + record.setName(sellingSanitaryActivity.getName()); + // Validate packets number before calculation + Integer packetsDistributed = adolescentHealth.getNoOfPacketsDistributed(); + long rate = sellingSanitaryActivity.getRate() != null ? sellingSanitaryActivity.getRate() : 0; + long amount = rate * (packetsDistributed != null ? packetsDistributed : 0); + record.setAmount(amount); + recordRepo.save(record); + } + } + + + if (mobilizingADHActivity != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(mobilizingADHActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(mobilizingADHActivity.getId()); + record.setCreatedDate(adolescentHealth.getCreatedDate()); + record.setCreatedBy(adolescentHealth.getCreatedBy()); + record.setStartDate(adolescentHealth.getCreatedDate()); + record.setEndDate(adolescentHealth.getCreatedDate()); + record.setUpdatedDate(adolescentHealth.getCreatedDate()); + record.setUpdatedBy(adolescentHealth.getCreatedBy()); + record.setBenId(adolescentHealth.getBenId().longValue()); + record.setAshaId(adolescentHealth.getUserId()); + record.setName(mobilizingADHActivity.getName()); + record.setAmount(Long.valueOf(mobilizingADHActivity.getRate()) * adolescentHealth.getNoOfPacketsDistributed()); + recordRepo.save(record); + } + } + } +} + diff --git a/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java new file mode 100644 index 00000000..29ca30da --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java @@ -0,0 +1,184 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.AshaWorker; +import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.repo.iemr.AshaProfileRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.service.AshaProfileService; +import com.iemr.flw.service.EmployeeMasterInter; + +import com.iemr.flw.repo.iemr.EmployeeMasterRepo; +import com.iemr.flw.service.AshaProfileService; +import com.iemr.flw.service.EmployeeMasterInter; +import com.iemr.flw.utils.JwtAuthenticationUtil; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import io.jsonwebtoken.Claims; +import jakarta.transaction.Transactional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.util.Objects; + +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +@Service +public class AshaProfileImpl implements AshaProfileService { + @Autowired + AshaProfileRepo ashaProfileRepo; + @Autowired + EmployeeMasterInter employeeMasterInter; + @Autowired + private RedisTemplate redisTemplate; + @Autowired + private EmployeeMasterRepo userLoginRepo; + @Autowired + JwtUtil jwtUtil; + @Autowired + JwtAuthenticationUtil jwtAuthenticationUtil; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + private final Logger logger = LoggerFactory.getLogger(AshaProfileImpl.class); + + @Transactional + @Override + public AshaWorker saveEditData(AshaWorker request) { + try { + Objects.requireNonNull(request, "ASHA worker request must not be null"); + + Long id = request.getId(); + + // ---------- CREATE Case ---------- + if (id == null || id == 0) { + // treat id=0 as null (frontend mistake) + if (id != null && id == 0) { + request.setId(null); + } + + AshaWorker saved = ashaProfileRepo.save(request); + logger.info("Created ASHA Worker: {}", saved.getId()); + return saved; + } + + // ---------- UPDATE Case ---------- + AshaWorker updated = updateProfile(request); + logger.info("Updated ASHA Worker: {}", updated.getId()); + return updated; + + } catch (Exception e) { + logger.error("Error saving ASHA worker: {}", e.getMessage(), e); + throw new RuntimeException("Failed to save ASHA worker", e); + } + } + + + @Override + public AshaWorker getProfileData(Integer userId) { + + try { + + Objects.requireNonNull(userId, "employeeId must not be null"); + return ashaProfileRepo.findByEmployeeId(userId) + .orElseGet(() -> { + return getDetails(userId); + }); + } catch (Exception e) { + throw new RuntimeException("Failed to retrieve ASHA worker profile", e); + } + } + + private AshaWorker getDetails(Integer userID) { + try { + M_User m_user = Objects.requireNonNull(employeeMasterInter.getUserDetails(userID), "User details not found for ID: " + userID); + AshaWorker ashaWorker = new AshaWorker(); + ashaWorker.setEmployeeId(m_user.getUserID()); + // Convert DOB (Timestamp) to LocalDate + java.sql.Timestamp dobTimestamp = m_user.getDOB(); + LocalDate dob = dobTimestamp != null ? dobTimestamp.toLocalDateTime().toLocalDate() : null; + ashaWorker.setDob(dob); + // Convert DOJ (Timestamp) to LocalDate + java.sql.Timestamp dojTimestamp = m_user.getDOJ(); + LocalDate doj = dojTimestamp != null ? dojTimestamp.toLocalDateTime().toLocalDate() : LocalDate.now(); + ashaWorker.setDateOfJoining(doj); + ashaWorker.setName(String.format("%s %s", Objects.toString(m_user.getFirstName(), ""), Objects.toString(m_user.getLastName(), "")).trim()); + ashaWorker.setMobileNumber(m_user.getContactNo()); + ashaWorker.setAlternateMobileNumber(m_user.getEmergencyContactNo()); + ashaWorker.setProviderServiceMapID(m_user.getServiceProviderID()); + ashaWorker.setProfileImage(""); + ashaWorker.setSupervisorName(""); + ashaWorker.setAwwName(""); + ashaWorker.setVillage(""); + ashaWorker.setSupervisorMobile(""); + ashaWorker.setFatherOrSpouseName(""); + ashaWorker.setChoName(""); + ashaWorker.setAnm1Name(""); + ashaWorker.setAnm2Mobile(""); + ashaWorker.setAnm1Mobile(""); + ashaWorker.setBankAccount(""); + ashaWorker.setIfsc(""); + ashaWorker.setIsFatherOrSpouse(false); + ashaWorker.setPopulationCovered(0); + ashaWorker.setVillage(""); + ashaWorker.setAwwMobile(""); + ashaWorker.setAnm2Name(""); + ashaWorker.setAbhaNumber(""); + ashaWorker.setAshaHouseholdRegistration(""); + ashaWorker.setAshaFamilyMember(""); + ashaWorker.setId(0L); + ashaWorker.setChoMobile(""); + + return ashaWorker; + } catch (Exception e) { + logger.error("Error creating ASHA worker profile from user details for ID {}: {}", userID, e.getMessage(), e); + throw new RuntimeException("Failed to create ASHA worker profile from user details", e); + } + } + + public AshaWorker updateProfile(AshaWorker request) { + AshaWorker existing = ashaProfileRepo.findByEmployeeId(request.getEmployeeId()).orElseThrow(() -> new RuntimeException("ASHA worker not found")); + if (isValid(request.getAbhaNumber())) existing.setAbhaNumber(request.getAbhaNumber()); + if (request.getEmployeeId() != null) existing.setEmployeeId(request.getEmployeeId()); + if (request.getDob() != null) existing.setDob(request.getDob()); + if (isValid(request.getAlternateMobileNumber())) + existing.setAlternateMobileNumber(request.getAlternateMobileNumber()); + if (isValid(request.getAnm1Mobile())) existing.setAnm1Mobile(request.getAnm1Mobile()); + if (isValid(request.getAnm2Name())) existing.setAnm2Name(request.getAnm2Name()); + if (isValid(request.getIfsc())) existing.setIfsc(request.getIfsc()); + if (isValid(request.getAwwName())) existing.setAwwName(request.getAwwName()); + if (isValid(request.getName())) existing.setName(request.getName()); + if (isValid(request.getVillage())) existing.setVillage(request.getVillage()); + if (isValid(request.getBankAccount())) existing.setBankAccount(request.getBankAccount()); + if (isValid(request.getChoName())) existing.setChoName(request.getChoName()); + if (isValid(request.getChoMobile())) existing.setChoMobile(request.getChoMobile()); + if (isValid(request.getAshaFamilyMember())) existing.setAshaFamilyMember(request.getAshaFamilyMember()); + if (request.getDateOfJoining() != null) existing.setDateOfJoining(request.getDateOfJoining()); + if (isValid(request.getMobileNumber())) existing.setMobileNumber(request.getMobileNumber()); + if (isValid(request.getAshaHouseholdRegistration())) + existing.setAshaHouseholdRegistration(request.getAshaHouseholdRegistration()); + if (isValid(request.getFatherOrSpouseName())) existing.setFatherOrSpouseName(request.getFatherOrSpouseName()); + if (request.getPopulationCovered() != null) existing.setPopulationCovered(request.getPopulationCovered()); + if (isValid(request.getAnm1Name())) existing.setAnm1Name(request.getAnm1Name()); + if (isValid(request.getAnm2Mobile())) existing.setAnm2Mobile(request.getAnm2Mobile()); + if (isValid(request.getAwwMobile())) existing.setAwwMobile(request.getAwwMobile()); + if (request.getProviderServiceMapID() != null) + existing.setProviderServiceMapID(request.getProviderServiceMapID()); + if (isValid(request.getProfileImage())) existing.setProfileImage(request.getProfileImage()); + if (request.getIsFatherOrSpouse() != null) existing.setIsFatherOrSpouse(request.getIsFatherOrSpouse()); + if (isValid(request.getSupervisorName())) existing.setSupervisorName(request.getSupervisorName()); + if (isValid(request.getSupervisorMobile())) existing.setSupervisorMobile(request.getSupervisorMobile()); + return existing; + } + + private boolean isValid(String value) { + return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim()); + } + + +} diff --git a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java index d46538c3..9d60729d 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -3,13 +3,23 @@ import java.math.BigInteger; import java.sql.Date; import java.text.SimpleDateFormat; +import java.time.LocalDate; import java.time.Period; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; - +import java.util.stream.Collectors; + +import com.iemr.flw.domain.iemr.EyeCheckupVisit; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.dto.iemr.EyeCheckupListDTO; +import com.iemr.flw.dto.iemr.EyeCheckupRequestDTO; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.utils.JwtUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -53,11 +63,37 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { private final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); @Value("${door-to-door-page-size}") private String door_to_door_page_size; + + @Value("${fhir-url}") + private String fhirUrl; + + @Value("${getHealthID}") + private String getHealthID; @Autowired private BeneficiaryRepo beneficiaryRepo; @Autowired private HouseHoldRepo houseHoldRepo; + @Autowired + private GeneralOpdRepo generalOpdRepo; + + @Autowired + IncentivesRepo incentivesRepo; + + @Autowired + IncentiveRecordRepo recordRepo; + + @Autowired + private EyeCheckUpVisitRepo eyeCheckUpVisitRepo; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserServiceRoleRepo userRepo; + + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + @Override @@ -355,6 +391,21 @@ private String getMappingsForAddressIDs(List addressLi resultMap.put("abhaHealthDetails", healthDetails); resultMap.put("houseoldId", benDetailsRMNCH_OBJ.getHouseoldId()); resultMap.put("benficieryid", benDetailsRMNCH_OBJ.getBenficieryid()); + resultMap.put("isDeath", benDetailsRMNCH_OBJ.getIsDeath()); + resultMap.put("isDeathValue", benDetailsRMNCH_OBJ.getIsDeathValue()); + resultMap.put("dateOfDeath",benDetailsRMNCH_OBJ.getDateOfDeath()); + resultMap.put("timeOfDeath", benDetailsRMNCH_OBJ.getTimeOfDeath()); + resultMap.put("reasonOfDeath", benDetailsRMNCH_OBJ.getReasonOfDeath()); + resultMap.put("reasonOfDeathId", benDetailsRMNCH_OBJ.getReasonOfDeathId()); + resultMap.put("placeOfDeath", benDetailsRMNCH_OBJ.getPlaceOfDeath()); + resultMap.put("placeOfDeathId", benDetailsRMNCH_OBJ.getPlaceOfDeathId()); + resultMap.put("isSpouseAdded", benDetailsRMNCH_OBJ.getIsSpouseAdded()); + resultMap.put("isChildrenAdded", benDetailsRMNCH_OBJ.getIsChildrenAdded()); + resultMap.put("noOfchildren", benDetailsRMNCH_OBJ.getNoOfchildren()); + resultMap.put("isMarried", benDetailsRMNCH_OBJ.getIsMarried()); + resultMap.put("doYouHavechildren", benDetailsRMNCH_OBJ.getDoYouHavechildren()); + resultMap.put("noofAlivechildren",benDetailsRMNCH_OBJ.getNoofAlivechildren()); + resultMap.put("isDeactivate",benDetailsRMNCH_OBJ.getIsDeactivate()); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id @@ -374,7 +425,7 @@ private String getMappingsForAddressIDs(List addressLi // mapping not available } } catch (Exception e) { - logger.error("error for addressID :" + a.getId() + " and vanID : " + a.getVanID()); + logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } } @@ -386,6 +437,7 @@ private String getMappingsForAddressIDs(List addressLi return gson.toJson(response); } + private Map getBenHealthDetails(BigInteger benRegId) { Map healthDetails = new HashMap<>(); if (null != benRegId) { @@ -414,6 +466,22 @@ private Map getBenHealthDetails(BigInteger benRegId) { return healthDetails; } + private Map getBenBenVisitDetails(BigInteger benRegId) { + Map healthDetails = new HashMap<>(); + if (null != benRegId) { + String benHealthIdNumber = String.valueOf(beneficiaryRepo.getBenHealthIdNumber(benRegId)); + if (null != benHealthIdNumber) { + ArrayList health = beneficiaryRepo.getBenHealthDetails(benHealthIdNumber); + for (Object[] objects : health) { + healthDetails.put("HealthID", objects[0]); + healthDetails.put("HealthIdNumber", objects[1]); + healthDetails.put("isNewAbha", objects[2]); + } + } + } + return healthDetails; + } + public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { Map requestMap = new HashMap(); requestMap.put("beneficiaryRegID", benRegID); @@ -424,8 +492,8 @@ public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map header = new HashMap(); header.put("Authorization", authorization); - String responseStr = utils.post(ConfigProperties.getPropertyByName("fhir-url") + "/" - + ConfigProperties.getPropertyByName("getHealthID"), new Gson().toJson(requestMap), header); + String responseStr = utils.post(fhirUrl + "/" + + getHealthID, new Gson().toJson(requestMap), header); JsonElement jsnElmnt = jsnParser.parse(responseStr); JsonObject jsnOBJ = new JsonObject(); jsnOBJ = jsnElmnt.getAsJsonObject(); @@ -450,4 +518,72 @@ public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map eyeCheckupRequestDTOS,String token) { + + try { + for (EyeCheckupRequestDTO dto : eyeCheckupRequestDTOS) { + EyeCheckupVisit visit = new EyeCheckupVisit(); + + visit.setBeneficiaryId(dto.getBeneficiaryId()); + visit.setHouseholdId(dto.getHouseHoldId()); + visit.setUserId(jwtUtil.extractUserId(token)); + visit.setCreatedBy(dto.getUserName()); + StringBuilder sb = new StringBuilder(); + + + // fields mapping + EyeCheckupListDTO f = dto.getFields(); + sb.append(f.getDischarge_summary_upload()); + String longText = sb.toString(); + visit.setVisitDate(LocalDate.parse(f.getVisit_date(), FORMATTER)); + visit.setSymptomsObserved(f.getSymptoms_observed()); + visit.setEyeAffected(f.getEye_affected()); + visit.setReferredTo(f.getReferred_to()); + visit.setDischargeSummaryUpload(longText); + visit.setFollowUpStatus(f.getFollow_up_status()); + visit.setDateOfSurgery(f.getDate_of_surgery()); + + // save/update + eyeCheckUpVisitRepo.save(visit); + } + return "Eye checkup data saved successfully."; + } catch (Exception e) { + e.printStackTrace(); + + } + return null ; + } + + @Override + public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { + + List visits = eyeCheckUpVisitRepo.findByCreatedBy(jwtUtil.extractUsername(token)); + + return visits.stream().map(v -> { + EyeCheckupRequestDTO dto = new EyeCheckupRequestDTO(); + dto.setId(v.getId()); + dto.setBeneficiaryId(v.getBeneficiaryId()); + dto.setHouseHoldId(v.getHouseholdId()); + dto.setUserName(v.getCreatedBy()); + dto.setVisitDate(v.getVisitDate().format(FORMATTER)); + + EyeCheckupListDTO fields = new EyeCheckupListDTO(); + fields.setVisit_date(v.getVisitDate().format(FORMATTER)); + fields.setSymptoms_observed(v.getSymptomsObserved()); + fields.setEye_affected(v.getEyeAffected()); + fields.setReferred_to(v.getReferredTo()); + fields.setFollow_up_status(v.getFollowUpStatus()); + fields.setDate_of_surgery(v.getDateOfSurgery()); + fields.setDischarge_summary_upload(v.getDischargeSummaryUpload()); + + + dto.setFields(fields); + return dto; + }).collect(Collectors.toList()); + } + + } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java new file mode 100644 index 00000000..620ae6c6 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -0,0 +1,506 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.*; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.CampaignService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; + +@Service +public class CampaignServiceImpl implements CampaignService { + + @Autowired + private OrsCampaignRepo orsCampaignRepo; + + @Autowired + private PulsePolioCampaignRepo pulsePolioCampaignRepo; + + @Autowired + private FilariasisCampaignRepo filariasisCampaignRepo; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + IncentivesRepo incentivesRepo; + + @Autowired + IncentiveRecordRepo recordRepo; + + @Autowired + private ObjectMapper objectMapper = new ObjectMapper(); + + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + + @Override + @Transactional + public List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException, JsonProcessingException { + if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { + return Collections.emptyList(); // + } + + List campaignOrsRequest = new ArrayList<>(); + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + + for (OrsCampaignDTO campaignDTO : orsCampaignDTO) { + if (campaignDTO.getFields() == null) { + continue; + } + + CampaignOrs campaignOrsEntity = new CampaignOrs(); + campaignOrsEntity.setUserId(userId); + campaignOrsEntity.setCreatedBy(userName); + campaignOrsEntity.setUpdatedBy(userName); + campaignOrsEntity.setStartDate(campaignDTO.getFields().getStartDate()); + campaignOrsEntity.setEndDate(campaignDTO.getFields().getEndDate()); + + try { + String familiesStr = campaignDTO.getFields().getNumberOfFamilies(); + if (familiesStr != null && !familiesStr.trim().isEmpty()) { + double familiesDouble = Double.parseDouble(familiesStr); + campaignOrsEntity.setNumberOfFamilies((int) familiesDouble); + } else { + campaignOrsEntity.setNumberOfFamilies(0); // default 0 + } + } catch (NumberFormatException e) { + throw new IEMRException("Invalid number format for families: " + campaignDTO.getFields().getNumberOfFamilies()); + } + + OrsCampaignListDTO campaignListDTO = campaignDTO.getFields(); + + if(campaignListDTO!=null){ + String photosJson = objectMapper.writeValueAsString(campaignListDTO.getCampaignPhotos()); + campaignOrsEntity.setCampaignPhotos(photosJson); + } + + campaignOrsRequest.add(campaignOrsEntity); + } + + if (!campaignOrsRequest.isEmpty()) { + List savedCampaigns = orsCampaignRepo.saveAll(campaignOrsRequest); + savedCampaigns.forEach(ors->{ + checkMonthlyPulseOrsDistribution(ors.getUserId(),ors.getStartDate(),ors.getEndDate()); + }); + return savedCampaigns; + } + + return Collections.emptyList(); + } + + @Override + public List getOrsCampaign(String token) throws IEMRException { + Integer userId = jwtUtil.extractUserId(token); + List orsCampaignDTOSResponse = new ArrayList<>(); + int page = 0; + int pageSize = 10; + Page campaignOrsPage; + do { + Pageable pageable = PageRequest.of(page, pageSize); + campaignOrsPage = orsCampaignRepo.findByUserId(userId, pageable); + for (CampaignOrs campaignOrs : campaignOrsPage.getContent()) { + OrsCampaignResponseDTO dto = convertOrsToDTO(campaignOrs); + orsCampaignDTOSResponse.add(dto); + } + page++; + } while (campaignOrsPage.hasNext()); + return orsCampaignDTOSResponse; + } + + + @Override + @Transactional + public List savePolioCampaign(List polioCampaignDTOs, String token) + throws IEMRException, JsonProcessingException { + + if (polioCampaignDTOs == null || polioCampaignDTOs.isEmpty()) { + throw new IEMRException("Campaign data is required"); + } + + List campaignPolioRequest = new ArrayList<>(); + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + + for (PolioCampaignDTO campaignDTO : polioCampaignDTOs) { + if (campaignDTO.getFields() == null) { + continue; + } + + PulsePolioCampaign campaignPolioEntity = new PulsePolioCampaign(); + campaignPolioEntity.setUserId(userId); + campaignPolioEntity.setCreatedBy(userName); + campaignPolioEntity.setUpdatedBy(userName); + + // Set start and end dates + campaignPolioEntity.setStartDate(campaignDTO.getFields().getStartDate()); + campaignPolioEntity.setEndDate(campaignDTO.getFields().getEndDate()); + + // Parse number of children + try { + String childrenStr = campaignDTO.getFields().getNumberOfChildren(); + if (childrenStr != null && !childrenStr.trim().isEmpty()) { + try { + // parse as double first, then cast to int + double childrenDouble = Double.parseDouble(childrenStr); + campaignPolioEntity.setNumberOfChildren((int) childrenDouble); + } catch (NumberFormatException e) { + campaignPolioEntity.setNumberOfChildren(0); // default 0 if invalid + } + } else { + campaignPolioEntity.setNumberOfChildren(0); + } + } catch (NumberFormatException e) { + throw new IEMRException("Invalid number format for children: " + e.getMessage()); + } + + // Convert photos to base64 JSON array + + PolioCampaignListDTO polioCampaignListDTO = campaignDTO.getFields(); + if(polioCampaignListDTO!=null){ + String photosJson = objectMapper.writeValueAsString(polioCampaignListDTO.getCampaignPhotos()); + campaignPolioEntity.setCampaignPhotos(photosJson); + + + } + + campaignPolioRequest.add(campaignPolioEntity); + } + + if (!campaignPolioRequest.isEmpty()) { + List savedCampaigns = pulsePolioCampaignRepo.saveAll(campaignPolioRequest); + savedCampaigns.forEach(pulsePolioCampaign -> { + checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + + });{ + + } + return savedCampaigns; + } + + throw new IEMRException("No valid campaign data to save"); + } + + + @Override + @Transactional + public List saveFilariasisCampaign(List filariasisCampaignDTOS, String token) throws IEMRException, JsonProcessingException { + + if (filariasisCampaignDTOS == null || filariasisCampaignDTOS.isEmpty()) { + throw new IEMRException("Campaign data is required"); + } + + List campaignPolioRequest = new ArrayList<>(); + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + + for (FilariasisCampaignDTO campaignDTO : filariasisCampaignDTOS) { + if (campaignDTO.getFields() == null) { + continue; + } + + FilariasisCampaign filariasisCampaign = new FilariasisCampaign(); + filariasisCampaign.setUserId(userId); + filariasisCampaign.setCreatedBy(userName); + filariasisCampaign.setUpdatedBy(userName); + + // Set start and end dates + filariasisCampaign.setStartDate(campaignDTO.getFields().getStartDate()); + filariasisCampaign.setEndDate(campaignDTO.getFields().getEndDate()); + + // Parse number of children + try { + String numberOfFamilies = (campaignDTO != null && campaignDTO.getFields() != null) + ? campaignDTO.getFields().getNumberOfFamilies() + : null; + + String numberOfIndividuals = (campaignDTO != null && campaignDTO.getFields() != null) + ? campaignDTO.getFields().getNumberOfIndividuals() + : null; + if (numberOfFamilies != null && !numberOfFamilies.trim().isEmpty()) { + try { + // parse as double first, then cast to int + double noDouble = Double.parseDouble(numberOfFamilies); + filariasisCampaign.setNumberOfFamilies((int) noDouble); + } catch (NumberFormatException e) { + filariasisCampaign.setNumberOfFamilies(0); // default 0 if invalid + } + } else { + filariasisCampaign.setNumberOfFamilies(0); + } + + if (numberOfIndividuals != null && !numberOfIndividuals.trim().isEmpty()) { + try { + // parse as double first, then cast to int + double noDouble = Double.parseDouble(numberOfIndividuals); + filariasisCampaign.setNumberOfIndividuals((int) noDouble); + } catch (NumberFormatException e) { + filariasisCampaign.setNumberOfIndividuals(0); // default 0 if invalid + } + } else { + filariasisCampaign.setNumberOfIndividuals(0); + } + } catch (NumberFormatException e) { + throw new IEMRException("Invalid number format for children: " + e.getMessage()); + } + + // Convert photos to base64 JSON array + FilariasisCampaignListDTO filariasisCampaignListDTO = campaignDTO.getFields(); + if(filariasisCampaignListDTO!=null){ + String photosJson = objectMapper.writeValueAsString(filariasisCampaignListDTO.getMdaPhotos()); + filariasisCampaign.setCampaignPhotos(photosJson); + + + } + + campaignPolioRequest.add(filariasisCampaign); + } + + if (!campaignPolioRequest.isEmpty()) { + List savedCampaigns = filariasisCampaignRepo.saveAll(campaignPolioRequest); + + savedCampaigns.forEach(filariasisCampaign -> { + checkMonthlyFilariasisIncentive(filariasisCampaign.getUserId(),filariasisCampaign.getStartDate(),filariasisCampaign.getEndDate()); + + });{ + + } + return savedCampaigns; + } + + throw new IEMRException("No valid campaign data to save"); + } + + + + @Override + public List getPolioCampaign(String token) throws IEMRException { + Integer userId = jwtUtil.extractUserId(token); + List polioCampaignDTOSResponse = new ArrayList<>(); + int page = 0; + int pageSize = 10; + Page campaignPolioPage; + do { + Pageable pageable = PageRequest.of(page, pageSize); + campaignPolioPage = pulsePolioCampaignRepo.findByUserId(userId, pageable); + for (PulsePolioCampaign campaignOrs : campaignPolioPage.getContent()) { + PolioCampaignResponseDTO dto = convertPolioToDTO(campaignOrs); + polioCampaignDTOSResponse.add(dto); + } + page++; + } while (campaignPolioPage.hasNext()); + return polioCampaignDTOSResponse; + } + + @Override + public List getAllFilariasisCampaign(String token) throws IEMRException { + Integer userId = jwtUtil.extractUserId(token); + List filariasisResponseDTOS = new ArrayList<>(); + int page = 0; + int pageSize = 10; + Page campaignPolioPage; + do { + Pageable pageable = PageRequest.of(page, pageSize); + campaignPolioPage = filariasisCampaignRepo.findByUserId(userId, pageable); + for (FilariasisCampaign campaignOrs : campaignPolioPage.getContent()) { + FilariasisResponseDTO dto = convertFilariasisDTO(campaignOrs); + filariasisResponseDTOS.add(dto); + } + page++; + } while (campaignPolioPage.hasNext()); + return filariasisResponseDTOS; + } + + + private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { + OrsCampaignResponseDTO dto = new OrsCampaignResponseDTO(); + OrsCampaignListResponseDTO orsCampaignListDTO = new OrsCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + ObjectMapper objectMapper = new ObjectMapper(); + List photosList = new ArrayList<>(); + + String photoStr = campaign.getCampaignPhotos(); + + if (photoStr != null && !photoStr.trim().isEmpty()) { + try { + // try JSON list + photosList = objectMapper.readValue( + photoStr, + new TypeReference>() {} + ); + } catch (Exception e) { + // fallback: single image + photosList.add(photoStr.trim()); + } + } + orsCampaignListDTO.setCampaignPhotos(photosList); + } + orsCampaignListDTO.setEndDate(campaign.getEndDate()); + orsCampaignListDTO.setStartDate(campaign.getStartDate()); + orsCampaignListDTO.setNumberOfFamilies(Double.valueOf(campaign.getNumberOfFamilies())); + dto.setId(campaign.getId()); + dto.setFields(orsCampaignListDTO); + + return dto; + } + + private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) { + PolioCampaignResponseDTO dto = new PolioCampaignResponseDTO(); + PolioCampaignListResponseDTO polioCampaignListDTO = new PolioCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + List photosList = new ArrayList<>(); + + String photoStr = campaign.getCampaignPhotos(); + + if (photoStr != null && !photoStr.trim().isEmpty()) { + try { + // try JSON list + photosList = objectMapper.readValue( + photoStr, + new TypeReference>() {} + ); + } catch (Exception e) { + // fallback: single image + photosList.add(photoStr.trim()); + } + } + + polioCampaignListDTO.setCampaignPhotos(photosList); + } + polioCampaignListDTO.setEndDate(campaign.getEndDate()); + polioCampaignListDTO.setStartDate(campaign.getStartDate()); + polioCampaignListDTO.setNumberOfChildren(Double.valueOf(campaign.getNumberOfChildren())); + dto.setId(campaign.getId()); + dto.setFields(polioCampaignListDTO); + return dto; + } + + private FilariasisResponseDTO convertFilariasisDTO(FilariasisCampaign campaign) { + FilariasisResponseDTO dto = new FilariasisResponseDTO(); + FilariasisCampaignListResponseDTO filariasisCampaignListDTO = new FilariasisCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + List photosList = new ArrayList<>(); + String photoStr = campaign.getCampaignPhotos(); + + if (photoStr != null && !photoStr.trim().isEmpty()) { + try { + // try JSON list + photosList = objectMapper.readValue( + photoStr, + new TypeReference>() {} + ); + } catch (Exception e) { + // fallback: single image + photosList.add(photoStr.trim()); + } + } + + filariasisCampaignListDTO.setMdaPhotos(photosList); + } + filariasisCampaignListDTO.setEndDate(campaign.getEndDate()); + filariasisCampaignListDTO.setStartDate(campaign.getStartDate()); + Double numberOfIndividuals = null; + Double numberOfFamilies = null; + + if (campaign.getNumberOfIndividuals() != null) { + numberOfIndividuals = Double.valueOf(campaign.getNumberOfIndividuals()); + } + + if (campaign.getNumberOfFamilies() != null) { + numberOfFamilies = Double.valueOf(campaign.getNumberOfFamilies()); + } + + filariasisCampaignListDTO.setNumberOfIndividuals(numberOfIndividuals); + filariasisCampaignListDTO.setNumberOfFamilies(numberOfFamilies); + + dto.setFields(filariasisCampaignListDTO); + return dto; + } + private List parseBase64Json(String jsonString) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readValue(jsonString, new TypeReference>() {}); + } catch (JsonProcessingException e) { + return Collections.emptyList(); + } + } + + private void checkMonthlyPulsePolioIncentive(Integer ashaId,LocalDate startDate,LocalDate endDate) { + + IncentiveActivity CHILD_MOBILIZATION_SESSIONS = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_MOBILIZATION_SESSIONS", GroupName.ACTIVITY.getDisplayName()); + if (CHILD_MOBILIZATION_SESSIONS != null) { + addAshaIncentiveRecord(CHILD_MOBILIZATION_SESSIONS, ashaId,startDate,endDate); + } + + } + + private void checkMonthlyFilariasisIncentive(Integer ashaId,LocalDate startDate,LocalDate endDate) { + IncentiveActivity FILARIASIS_MEDICINE_DISTRIBUTION = incentivesRepo.findIncentiveMasterByNameAndGroup("FILARIASIS_MEDICINE_DISTRIBUTION", GroupName.ACTIVITY.getDisplayName()); + if (FILARIASIS_MEDICINE_DISTRIBUTION != null) { + addAshaIncentiveRecord(FILARIASIS_MEDICINE_DISTRIBUTION, ashaId,startDate,endDate); + } + + } + + private void checkMonthlyPulseOrsDistribution(Integer ashaId,LocalDate startDate,LocalDate endDate) { + IncentiveActivity ORS_DISTRIBUTION = incentivesRepo.findIncentiveMasterByNameAndGroup("ORS_DISTRIBUTION", GroupName.ACTIVITY.getDisplayName()); + if (ORS_DISTRIBUTION != null) { + addAshaIncentiveRecord(ORS_DISTRIBUTION, ashaId,startDate,endDate); + } + + } + + private void addAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId,LocalDate startDate,LocalDate endDate) { + Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); + + Timestamp startOfMonth = Timestamp.valueOf(startDate.atStartOfDay()); + Timestamp endOfMonth = Timestamp.valueOf(endDate.atStartOfDay()); + + IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivity.getId(), + startOfMonth, + endOfMonth, + 0L, + ashaId + ); + + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(timestamp); + record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId)); + record.setStartDate(timestamp); + record.setEndDate(timestamp); + record.setUpdatedDate(timestamp); + record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId)); + record.setBenId(0L); + record.setAshaId(ashaId); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } + } + +} + diff --git a/src/main/java/com/iemr/flw/service/impl/CbacServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CbacServiceImpl.java index b9d5278c..a618885b 100644 --- a/src/main/java/com/iemr/flw/service/impl/CbacServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CbacServiceImpl.java @@ -11,6 +11,9 @@ import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.identity.CbacAdditionalDetailRepo; import com.iemr.flw.repo.identity.CbacRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.CbacService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -22,10 +25,7 @@ import org.springframework.stereotype.Service; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; @Service public class CbacServiceImpl implements CbacService { @@ -39,6 +39,15 @@ public class CbacServiceImpl implements CbacService { private CbacAdditionalDetailRepo cbacAddRepo; @Autowired private BeneficiaryRepo beneficiaryRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; @Value("10") private String cbac_page_size; @@ -125,10 +134,12 @@ public String save(List cbacList) { }); if (cbacAdditionalDetailsList.size() > 0) { cbacAddRepo.saveAll(cbacAdditionalDetailsList); + } Gson gson = new GsonBuilder() .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format .create(); return gson.toJson(result); } + } diff --git a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java index 38381dfa..43a9eb1f 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -1,21 +1,32 @@ package com.iemr.flw.service.impl; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.utils.JwtUtil; +import org.aspectj.weaver.ast.Or; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import java.io.File; +import java.io.IOException; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; import java.util.stream.Collectors; @Service @@ -32,14 +43,6 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private HbncVisitRepo hbncVisitRepo; - @Autowired - private HbncVisitCardRepo hbncVisitCardRepo; - - @Autowired - private HbncPart1Repo hbncPart1Repo; - - @Autowired - private HbncPart2repo hbncPart2repo; @Autowired private IncentivesRepo incentivesRepo; @@ -53,6 +56,12 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private ChildVaccinationRepo childVaccinationRepo; + @Autowired + private SamVisitRepository samVisitRepository; + + @Autowired + private IfaDistributionRepository ifaDistributionRepository; + @Autowired private VaccineRepo vaccineRepo; @@ -60,26 +69,76 @@ public class ChildCareServiceImpl implements ChildCareService { ModelMapper modelMapper = new ModelMapper(); + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private OrsDistributionRepo orsDistributionRepo; + + + @Override - public String registerHBYC(List hbycDTOs) { + public String registerHBYC(List hbycDTOs) { try { - List hbycList = new ArrayList<>(); - hbycDTOs.forEach(it ->{ - HBYC hbyc = - hbycRepo.findHBYCByBenIdAndCreatedDate(it.getBenId(), it.getCreatedDate()); - if(hbyc != null) { + List hbycList = new ArrayList<>(); + hbycDTOs.forEach(it -> { + HbycDTO hbycDTO = it.getFields(); + hbycDTO.setVisit_date(it.getVisitDate()); + HbycChildVisit hbyc = + hbycRepo.findByBeneficiaryIdAndVisit_day(it.getBeneficiaryId(), hbycDTO.getVisit_day()); + + if (hbyc != null) { Long id = hbyc.getId(); - modelMapper.map(it, hbyc); + modelMapper.map(it, hbycDTO); hbyc.setId(id); + hbyc.setUserId(userRepo.getUserIdByName(it.getUserName())); + hbyc.setCreated_by(it.getUserName()); } else { - hbyc = new HBYC(); - modelMapper.map(it, hbyc); + hbyc = new HbycChildVisit(); + modelMapper.map(it, hbycDTO); hbyc.setId(null); + hbyc.setUserId(userRepo.getUserIdByName(it.getUserName())); + hbyc.setCreated_by(it.getUserName()); + hbyc.setBeneficiaryId(it.getBeneficiaryId()); + hbyc.setVisit_date(it.getVisitDate()); + hbyc.setHousehold_id(it.getHouseHoldId()); + hbyc.setVisit_day(hbycDTO.getVisit_day()); + hbyc.setHbyc_due_date(hbycDTO.getDue_date()); + hbyc.setBaby_weight(hbycDTO.getBaby_weight()); + hbyc.setPlace_of_death(hbycDTO.getPlace_of_death()); + hbyc.setReason_for_death(hbycDTO.getReason_for_death()); + hbyc.setOther_place_of_death(hbycDTO.getOther_place_of_death()); + hbyc.setIs_child_sick(convertBollen(hbycDTO.getIs_child_sick())); + + hbyc.setIs_baby_alive(convertBollen(hbycDTO.getIs_baby_alive())); + hbyc.setDate_of_death(hbycDTO.getDate_of_death()); + hbyc.setExclusive_breastfeeding(convertBollen(hbycDTO.getExclusive_breastfeeding())); + hbyc.setMother_counseled_ebf(convertBollen(hbycDTO.getMother_counseled_ebf())); + hbyc.setComplementary_feeding(convertBollen(hbycDTO.getComplementary_feeding())); + hbyc.setMother_counseled_cf(convertBollen((hbycDTO.getMother_counseled_cf()))); + hbyc.setWeight_recorded(convertBollen(hbycDTO.getWeight_recorded())); + hbyc.setDevelopmental_delay(convertBollen(hbycDTO.getDevelopmental_delay())); + hbyc.setMeasles_vaccine(convertBollen(hbycDTO.getMeasles_vaccine())); + hbyc.setVitamin_a(convertBollen(hbycDTO.getVitamin_a())); + hbyc.setOrs_available(convertBollen(hbycDTO.getOrs_available())); + hbyc.setIfa_available(convertBollen(hbycDTO.getIfa_available())); + hbyc.setOrs_given(convertBollen(hbycDTO.getOrs_given())); + hbyc.setIfa_given(convertBollen(hbycDTO.getIfa_given())); + hbyc.setHandwash_counseling(convertBollen(hbycDTO.getHandwash_counseling())); + hbyc.setParenting_counseling(convertBollen(hbycDTO.getParenting_counseling())); + hbyc.setFamily_planning_counseling(convertBollen(hbycDTO.getFamily_planning_counseling())); + hbyc.setDiarrhoea_episode(convertBollen(hbycDTO.getDiarrhoea_episode())); + hbyc.setBreathing_difficulty(convertBollen(hbycDTO.getBreathing_difficulty())); + hbyc.setTemperature(hbycDTO.getTemperature_check()); + hbyc.setMcp_card_images(hbycDTO.getMcp_card_images()); + } hbycList.add(hbyc); }); hbycRepo.saveAll(hbycList); + checkAndAddHbyncIncentives(hbycList); + return "no of hbyc details saved: " + hbycDTOs.size(); } catch (Exception e) { logger.info("error while saving hbyc details: " + e.getMessage()); @@ -88,91 +147,160 @@ public String registerHBYC(List hbycDTOs) { } @Override - public List getHbycRecords(GetBenRequestHandler dto) { - try{ - String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List hbycList = - hbycRepo.getAllHbycByBenId(user, dto.getFromDate(), dto.getToDate()); - return hbycList.stream() - .map(hbyc -> mapper.convertValue(hbyc, HbycDTO.class)) - .collect(Collectors.toList()); + public List getHbycRecords(GetBenRequestHandler dto) { + List result = new ArrayList<>(); + + try { + List hbycChildVisits = hbycRepo.findByUserId(dto.getAshaId()); + + for (HbycChildVisit hbycChildVisit : hbycChildVisits) { + HbycVisitResponseDTO hbycRequestDTO = new HbycVisitResponseDTO(); + hbycRequestDTO.setId(hbycChildVisit.getId()); + hbycRequestDTO.setBeneficiaryId(hbycChildVisit.getBeneficiaryId()); + hbycRequestDTO.setHouseHoldId(hbycChildVisit.getHousehold_id()); + hbycRequestDTO.setVisitDate(hbycChildVisit.getVisit_date()); + + // Prepare dynamic fields map + Map fields = new HashMap<>(); + + addIfValid(fields, "visit_day", hbycChildVisit.getVisit_day()); + addIfValid(fields, "due_date", hbycChildVisit.getHbyc_due_date()); + addIfValid(fields, "visit_date", hbycChildVisit.getVisit_date()); + addIfValid(fields, "is_baby_alive", convert(hbycChildVisit.getIs_baby_alive())); + addIfValid(fields, "date_of_death", hbycChildVisit.getDate_of_death()); + addIfValid(fields, "reason_for_death", hbycChildVisit.getReason_for_death()); + addIfValid(fields, "place_of_death", hbycChildVisit.getPlace_of_death()); + addIfValid(fields, "other_place_of_death", hbycChildVisit.getOther_place_of_death()); + addIfValid(fields, "baby_weight", hbycChildVisit.getBaby_weight()); + addIfValid(fields, "is_child_sick", convert(hbycChildVisit.getIs_child_sick())); + addIfValid(fields, "exclusive_breastfeeding", convert(hbycChildVisit.getExclusive_breastfeeding())); + addIfValid(fields, "mother_counseled_ebf", convert(hbycChildVisit.getMother_counseled_ebf())); +// addIfValid(fields, "complementary_feeding", convert(hbycChildVisit.getComplementary_feeding())); + addIfValid(fields, "mother_counseled_cf", convert(hbycChildVisit.getMother_counseled_cf())); + addIfValid(fields, "weight_recorded", convert(hbycChildVisit.getWeight_recorded())); + addIfValid(fields, "developmental_delay", convert(hbycChildVisit.getDevelopmental_delay())); + addIfValid(fields, "measles_vaccine", convert(hbycChildVisit.getMeasles_vaccine())); + addIfValid(fields, "vitamin_a", convert(hbycChildVisit.getVitamin_a())); + addIfValid(fields, "ors_available", convert(hbycChildVisit.getOrs_available())); + addIfValid(fields, "ifa_available", convert(hbycChildVisit.getIfa_available())); + addIfValid(fields, "ors_given", convert(hbycChildVisit.getOrs_given())); + addIfValid(fields, "ifa_given", convert(hbycChildVisit.getIfa_given())); + addIfValid(fields, "handwash_counseling", convert(hbycChildVisit.getHandwash_counseling())); + addIfValid(fields, "parenting_counseling", convert(hbycChildVisit.getParenting_counseling())); + addIfValid(fields, "family_planning_counseling", convert(hbycChildVisit.getFamily_planning_counseling())); + addIfValid(fields, "diarrhoea_episode", convert(hbycChildVisit.getDiarrhoea_episode())); +// addIfValid(fields, "breathing_difficulty", convert(hbycChildVisit.getBreathing_difficulty())); + addIfValid(fields, "temperature_check", hbycChildVisit.getTemperature()); + addIfValid(fields, "mcp_card_images", hbycChildVisit.getMcp_card_images()); + + + // Set fields map in DTO + hbycRequestDTO.setFields(fields); + result.add(hbycRequestDTO); + } + } catch (Exception e) { - logger.info("error while fetching hbyc details: " + e.getMessage()); + logger.error("Error while fetching HBYC details: ", e); } - return null; + + return result; + } @Override - public List getHBNCDetails(GetBenRequestHandler dto) { + public List getHBNCDetails(GetBenRequestHandler dto) { + List result = new ArrayList<>(); try { - List result = new ArrayList<>(); - String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List hbncVisits = hbncVisitRepo.getHbncVisitDetails(user, dto.getFromDate(), dto.getToDate()); - hbncVisits.forEach( hbnc -> { - HbncVisitDTO hbncVisitDTO = mapper.convertValue(hbnc, HbncVisitDTO.class); - HbncRequestDTO hbncRequestDTO = new HbncRequestDTO(); - hbncRequestDTO.setId(hbncVisitDTO.getId()); - hbncRequestDTO.setBenId(hbncVisitDTO.getBenId()); - hbncRequestDTO.setHomeVisitDate(hbncVisitDTO.getVisitNo()); - hbncRequestDTO.setHbncVisitDTO(hbncVisitDTO); - result.add(hbncRequestDTO); - }); + List hbncVisits = hbncVisitRepo.findByAshaId(dto.getAshaId()); - List hbncVisitCards = hbncVisitCardRepo.getHbncVisitCardDetails(user, dto.getFromDate(), dto.getToDate()); - hbncVisitCards.forEach( hbnc -> { - HbncVisitCardDTO hbncVisitCardDTO = mapper.convertValue(hbnc, HbncVisitCardDTO.class); - HbncRequestDTO hbncRequestDTO = new HbncRequestDTO(); - hbncRequestDTO.setId(hbncVisitCardDTO.getId()); - hbncRequestDTO.setBenId(hbncVisitCardDTO.getBenId()); - hbncRequestDTO.setHomeVisitDate(hbncVisitCardDTO.getVisitNo()); - hbncRequestDTO.setHbncVisitCardDTO(hbncVisitCardDTO); - result.add(hbncRequestDTO); - }); + for (HbncVisit visit : hbncVisits) { + HbncVisitResponseDTO responseDTO = new HbncVisitResponseDTO(); + responseDTO.setId(visit.getId()); + responseDTO.setBeneficiaryId(visit.getBeneficiaryId()); // Update with actual value + responseDTO.setHouseHoldId(visit.getHouseHoldId()); // Update with actual value + responseDTO.setVisitDate(visit.getVisit_date().split(" ")[0]); // Format visit.getVisitDate() - List hbncPart1List = hbncPart1Repo.getHbncPart1Details(user, dto.getFromDate(), dto.getToDate()); - hbncPart1List.forEach( hbnc -> { - HbncPart1DTO hbncPart1DTO = mapper.convertValue(hbnc, HbncPart1DTO.class); - HbncRequestDTO hbncRequestDTO = new HbncRequestDTO(); - hbncRequestDTO.setId(hbncPart1DTO.getId()); - hbncRequestDTO.setBenId(hbncPart1DTO.getBenId()); - hbncRequestDTO.setHomeVisitDate(hbncPart1DTO.getVisitNo()); - hbncRequestDTO.setHbncPart1DTO(hbncPart1DTO); - result.add(hbncRequestDTO); - }); + // Convert all fields to Map + Map fields = new HashMap<>(); + addIfValid(fields, "visit_day", visit.getVisit_day()); + addIfValid(fields, "due_date", visit.getDue_date()); + addIfValid(fields, "is_baby_alive", convert(visit.getIs_baby_alive())); + addIfValid(fields, "date_of_death", visit.getDate_of_death()); + addIfValid(fields, "reason_for_death", visit.getReasonForDeath()); + addIfValid(fields, "place_of_death", visit.getPlace_of_death()); + addIfValid(fields, "other_place_of_death", visit.getOther_place_of_death()); + addIfValid(fields, "baby_weight", visit.getBaby_weight()); + addIfValid(fields, "urine_passed", convert(visit.getUrine_passed())); + addIfValid(fields, "stool_passed", convert(visit.getStool_passed())); + addIfValid(fields, "diarrhoea", convert(visit.getDiarrhoea())); + addIfValid(fields, "vomiting", convert(visit.getVomiting())); + addIfValid(fields, "convulsions", convert(visit.getConvulsions())); + addIfValid(fields, "activity", visit.getActivity()); + addIfValid(fields, "sucking", visit.getSucking()); + addIfValid(fields, "breathing", visit.getBreathing()); + addIfValid(fields, "chest_indrawing", visit.getChest_indrawing()); + addIfValid(fields, "temperature", visit.getTemperature()); + addIfValid(fields, "jaundice", convert(visit.getJaundice())); + addIfValid(fields, "umbilical_stump", visit.getUmbilical_stump()); + addIfValid(fields, "discharged_from_sncu", convert(visit.getDischarged_from_sncu())); + addIfValid(fields, "discharge_summary_upload", visit.getDischarge_summary_upload()); - List hbncPart2List = hbncPart2repo.getHbncPart2Details(user, dto.getFromDate(), dto.getToDate()); - hbncPart2List.forEach( hbnc -> { - HbncPart2DTO hbncPart2DTO = mapper.convertValue(hbnc, HbncPart2DTO.class); - HbncRequestDTO hbncRequestDTO = new HbncRequestDTO(); - hbncRequestDTO.setId(hbncPart2DTO.getId()); - hbncRequestDTO.setBenId(hbncPart2DTO.getBenId()); - hbncRequestDTO.setHomeVisitDate(hbncPart2DTO.getVisitNo()); - hbncRequestDTO.setHbncPart2DTO(hbncPart2DTO); - result.add(hbncRequestDTO); - }); + // Add more fields as required + + responseDTO.setFields(fields); + result.add(responseDTO); + } - return result; } catch (Exception e) { - logger.error(e.getMessage()); + logger.error("Error in getHBNCDetails: ", e); } - return null; + return result; + } + + private void addIfValid(Map map, String key, Object value) { + if (value == null) return; + + if (value instanceof String && ((String) value).trim().isEmpty()) return; + + map.put(key, value); } + private String convert(Boolean value) { + if (value == null) return null; + return value ? "Yes" : "No"; + } + + private Boolean convertBollen(String value) { + if (value.equals("Yes")) { + return true; + } else { + return false; + } + } + + private String convert(Object value) { + if (value == null) return null; + if (value instanceof Boolean) return (Boolean) value ? "Yes" : "No"; + return value.toString(); + } + + + private String convert(String value) { + return "true".equalsIgnoreCase(value) ? "Yes" : "No"; + } + + @Override public String saveHBNCDetails(List hbncRequestDTOs) { try { List hbncList = new ArrayList<>(); - List hbncCardList = new ArrayList<>(); - List hbncPart1List = new ArrayList<>(); - List hbncPart2List = new ArrayList<>(); + hbncRequestDTOs.forEach(it -> { - if(it.getHbncVisitDTO() != null) { - HbncVisitDTO hbncVisitDTO = it.getHbncVisitDTO(); - hbncVisitDTO.setId(it.getId()); - hbncVisitDTO.setBenId(it.getBenId()); - hbncVisitDTO.setVisitNo(it.getHomeVisitDate()); - HbncVisit hbncVisit = - hbncVisitRepo.findHbncVisitByBenIdAndVisitNo(hbncVisitDTO.getBenId(), hbncVisitDTO.getVisitNo()); + if (it.getVisitDate() != null) { + + HbncVisitDTO hbncVisitDTO = it.getFields(); + hbncVisitDTO.setVisit_date(it.getVisitDate()); + HbncVisit hbncVisit = hbncVisitRepo.findByBeneficiaryIdAndVisit_day(it.getBeneficiaryId(), hbncVisitDTO.getVisit_day()); if (hbncVisit != null) { Long id = hbncVisit.getId(); @@ -181,72 +309,23 @@ public String saveHBNCDetails(List hbncRequestDTOs) { } else { hbncVisit = new HbncVisit(); modelMapper.map(hbncVisitDTO, hbncVisit); + hbncVisit.setBeneficiaryId(it.getBeneficiaryId()); + hbncVisit.setAshaId(userRepo.getUserIdByName(it.getUserName())); + hbncVisit.setCreatedBy(it.getUserName()); + hbncVisit.setHouseHoldId(it.getHouseHoldId()); hbncVisit.setId(null); } hbncList.add(hbncVisit); - } else if(it.getHbncVisitCardDTO() != null) { - HbncVisitCardDTO hbncVisitCardDTO = it.getHbncVisitCardDTO(); - hbncVisitCardDTO.setId(it.getId()); - hbncVisitCardDTO.setBenId(it.getBenId()); - hbncVisitCardDTO.setVisitNo(it.getHomeVisitDate()); - HbncVisitCard hbncVisitCard = - hbncVisitCardRepo.findHbncVisitCardByBenIdAndVisitNo(hbncVisitCardDTO.getBenId(), hbncVisitCardDTO.getVisitNo()); - - if (hbncVisitCard != null) { - Long id = hbncVisitCard.getId(); - modelMapper.map(hbncVisitCardDTO, hbncVisitCard); - hbncVisitCard.setId(id); - } else { - hbncVisitCard = new HbncVisitCard(); - modelMapper.map(hbncVisitCardDTO, hbncVisitCard); - hbncVisitCard.setId(null); - } - hbncCardList.add(hbncVisitCard); - } else if(it.getHbncPart1DTO() != null) { - HbncPart1DTO hbncPart1DTO = it.getHbncPart1DTO(); - hbncPart1DTO.setId(it.getId()); - hbncPart1DTO.setBenId(it.getBenId()); - hbncPart1DTO.setVisitNo(it.getHomeVisitDate()); - HbncPart1 hbncPart1 = - hbncPart1Repo.findHbncPart1ByBenIdAndVisitNo(hbncPart1DTO.getBenId(), hbncPart1DTO.getVisitNo()); - - if (hbncPart1 != null) { - Long id = hbncPart1.getId(); - modelMapper.map(hbncPart1DTO, hbncPart1); - hbncPart1.setId(id); - } else { - hbncPart1 = new HbncPart1(); - modelMapper.map(hbncPart1DTO, hbncPart1); - hbncPart1.setId(null); - } - hbncPart1List.add(hbncPart1); - } else if(it.getHbncPart2DTO() != null) { - HbncPart2DTO hbncPart2DTO = it.getHbncPart2DTO(); - hbncPart2DTO.setId(it.getId()); - hbncPart2DTO.setBenId(it.getBenId()); - hbncPart2DTO.setVisitNo(it.getHomeVisitDate()); - HbncPart2 hbncPart2 = - hbncPart2repo.findHbncPart2ByBenIdAndVisitNo(hbncPart2DTO.getBenId(), hbncPart2DTO.getVisitNo()); - - if (hbncPart2 != null) { - Long id = hbncPart2.getId(); - modelMapper.map(hbncPart2DTO, hbncPart2); - hbncPart2.setId(id); - } else { - hbncPart2 = new HbncPart2(); - modelMapper.map(hbncPart2DTO, hbncPart2); - hbncPart2.setId(null); - } - hbncPart2List.add(hbncPart2); } }); + + hbncVisitRepo.saveAll(hbncList); - hbncVisitCardRepo.saveAll(hbncCardList); - hbncPart1Repo.saveAll(hbncPart1List); - hbncPart2repo.saveAll(hbncPart2List); + checkAndAddHbncIncentives(hbncList); + + logger.info("HBNC details saved"); - return "no of hbnc details saved: " + (hbncList.size() + hbncCardList.size() + - hbncPart1List.size() + hbncPart2List.size()); + return "no of hbnc details saved: " + (hbncList.size()); } catch (Exception e) { logger.info("Saving HBNC details failed with error : " + e.getMessage()); } @@ -266,6 +345,7 @@ public List getChildVaccinationDetails(GetBenRequestHandler vaccinationDTO.setBeneficiaryId(benId.longValue()); result.add(vaccinationDTO); + checkAndAddIncentives(vaccinationDetails); }); return result; } catch (Exception e) { @@ -354,45 +434,460 @@ public List getAllChildVaccines(String category) { } return null; } + + @Override + public String saveSamDetails(List samRequest) { + try { + List vaccinationList = new ArrayList<>(); + + samRequest.forEach(samDTO -> { + logger.info("Processing SAM record for Beneficiary: {}", samDTO.getBeneficiaryId()); + + LocalDate visitDate = LocalDate.parse(samDTO.getVisitDate()); + + // 🔍 Check if this beneficiary already has a record for this visit date + SamVisit samVisit = samVisitRepository + .findByBeneficiaryIdAndVisitDate(samDTO.getBeneficiaryId(), visitDate) + .orElse(new SamVisit()); // 🧠 If exists → update, else create new + + samVisit.setBeneficiaryId(samDTO.getBeneficiaryId()); + samVisit.setHouseholdId(samDTO.getHouseHoldId()); + + // ✅ Visit date parsing + samVisit.setVisitDate(LocalDate.parse(samDTO.getVisitDate())); + + // ✅ Common user details + samVisit.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); + samVisit.setCreatedBy(jwtUtil.getUserNameFromStorage()); + if (samVisit.getCreatedBy() == null) { + samVisit.setCreatedBy(jwtUtil.getUserNameFromStorage()); + } + + // ✅ Field mapping + samVisit.setMuac(samDTO.getFields().getMuac()); + samVisit.setSamStatus(samDTO.getFields().getSam_status()); + samVisit.setVisitLabel(samDTO.getFields().getVisit_label()); + samVisit.setWeightForHeightStatus(samDTO.getFields().getWeight_for_height_status()); + samVisit.setIsChildReferredNrc(samDTO.getFields().getIs_child_referred_nrc()); + samVisit.setNrcAdmissionDate(samDTO.getFields().getNrc_admission_date()); + samVisit.setIsChildDischargedNrc(samDTO.getFields().getIs_child_discharged_nrc()); + samVisit.setNrcDischargeDate(samDTO.getFields().getNrc_discharge_date()); + + // ✅ Convert follow-up visit dates to JSON + try { + String followUpDatesJson = mapper.writeValueAsString(samDTO.getFields().getFollow_up_visit_date()); + samVisit.setFollowUpVisitDate(followUpDatesJson); + } catch (JsonProcessingException e) { + throw new RuntimeException("Error parsing follow-up visit dates", e); + } + + samVisit.setDischargeSummary(samDTO.getFields().getDischarge_summary()); + samVisit.setViewDischargeDocs(samDTO.getFields().getView_discharge_docs()); + + vaccinationList.add(samVisit); + }); + + // ✅ Save or update all + samVisitRepository.saveAll(vaccinationList); + + // ✅ Handle incentive logic + checkAndAddSamVisitNRCReferalIncentive(vaccinationList); + + return "Saved/Updated " + samRequest.size() + " SAM visit records successfully"; + } catch (Exception e) { + logger.error("Error saving SAM visit details: {}", e.getMessage(), e); + return "Failed to save SAM visit details: " + e.getMessage(); + } + } + + @Override + public List getSamVisitsByBeneficiary(GetBenRequestHandler request) { + + List entities = samVisitRepository.findByUserId(request.getAshaId()); + List samResponseListDTO = new ArrayList<>(); + int visitCounter = 1; + Map visitMap = new HashMap<>(); + + for (SamVisit entity : entities) { + + LocalDate vDate = entity.getVisitDate(); + + // ✅ Assign visit number based on unique date + if (!visitMap.containsKey(vDate)) { + visitMap.put(vDate, visitCounter++); + } + + int visitNo = visitMap.get(vDate); + + SAMResponseDTO samResponseDTO = new SAMResponseDTO(); + samResponseDTO.setBeneficiaryId(entity.getBeneficiaryId()); + samResponseDTO.setVisitDate(vDate != null ? vDate.toString() : null); + samResponseDTO.setHouseHoldId(entity.getHouseholdId()); + samResponseDTO.setId(entity.getId()); + + SamVisitResponseDTO dto = new SamVisitResponseDTO(); + dto.setBeneficiaryId(entity.getBeneficiaryId()); + dto.setVisitDate(vDate); + + // ✅ Final Visit Label + dto.setVisitLabel("Visit-" + visitNo); + + dto.setMuac(Double.parseDouble(entity.getMuac())); + dto.setWeightForHeightStatus(entity.getWeightForHeightStatus()); + dto.setIsChildReferredNrc(entity.getIsChildReferredNrc()); + dto.setIsChildAdmittedNrc(entity.getIsChildAdmittedNrc()); + dto.setNrcAdmissionDate(entity.getNrcAdmissionDate()); + dto.setIsChildDischargedNrc(entity.getIsChildDischargedNrc()); + dto.setNrcDischargeDate(entity.getNrcDischargeDate()); + + if (entity.getFollowUpVisitDate() != null) { + try { + List followUpDates = mapper.readValue( + entity.getFollowUpVisitDate(), + new TypeReference>() {}); + dto.setFollowUpVisitDate(followUpDates); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + dto.setSamStatus(entity.getSamStatus()); + dto.setDischargeSummary(entity.getDischargeSummary()); + + samResponseDTO.setFields(dto); + samResponseListDTO.add(samResponseDTO); + } + + + + return samResponseListDTO; + } + + @Override + public String saveOrsDistributionDetails(List orsDistributionDTOS) { + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + List orsDistributionList = new ArrayList<>(); + orsDistributionDTOS.forEach(orsDistributionDTO -> { + OrsDistribution orsDistribution = new OrsDistribution(); + orsDistribution.setId(orsDistributionDTO.getId()); + orsDistribution.setBeneficiaryId(orsDistributionDTO.getBeneficiaryId()); + orsDistribution.setNumOrsPackets(orsDistributionDTO.getFields().getNum_ors_packets().toString()); + orsDistribution.setChildCount(orsDistributionDTO.getFields().getNum_under5_children().toString()); + orsDistribution.setHouseholdId(orsDistributionDTO.getHouseHoldId()); + orsDistribution.setUserId(userRepo.getUserIdByName(orsDistributionDTO.getUserName())); + orsDistribution.setVisitDate(LocalDate.parse(orsDistributionDTO.getFields().getVisit_date(),formatter)); + orsDistributionList.add(orsDistribution); + + }); + logger.info("orsList"+orsDistributionList.size()); + if(!orsDistributionList.isEmpty()){ + orsDistributionRepo.saveAll(orsDistributionList); + checkAndAddOrdDistributionIncentive(orsDistributionList); + + return "Saved " + orsDistributionList.size() + " ORS visit records successfully"; + + } + }catch (Exception e){ + logger.error("ORS Error"+e); + + + } + + return null ; + } + + + @Override + public List getOrdDistrubtion(GetBenRequestHandler request) { + List entities = orsDistributionRepo.findByUserId(request.getAshaId()); + List orsDistributionResponseDTOSList = new ArrayList<>(); + + for(OrsDistribution orsDistribution: entities){ + + OrsDistributionResponseDTO orsDistributionResponseDTO = new OrsDistributionResponseDTO(); + OrsDistributionResponseListDTO orsDistributionResponseListDTO = new OrsDistributionResponseListDTO(); + orsDistributionResponseDTO.setId(orsDistribution.getId()); + orsDistributionResponseDTO.setBeneficiaryId(orsDistribution.getBeneficiaryId()); + orsDistributionResponseDTO.setHouseHoldId(orsDistribution.getHouseholdId()); + orsDistributionResponseListDTO.setNum_ors_packets(orsDistribution.getNumOrsPackets().toString()); + orsDistributionResponseListDTO.setNum_under5_children(orsDistribution.getChildCount().toString()); + orsDistributionResponseDTO.setFields(orsDistributionResponseListDTO); + orsDistributionResponseDTO.setVisitDate(parseDate(orsDistribution.getVisitDate().toString()).toString()); + orsDistributionResponseDTOSList.add(orsDistributionResponseDTO); + + + + } + return orsDistributionResponseDTOSList; + + } + + private LocalDate parseDate(String dateStr) { + if (dateStr == null || dateStr.isEmpty()) return null; + List formatters = List.of( + DateTimeFormatter.ofPattern("dd-MM-yyyy"), + DateTimeFormatter.ofPattern("yyyy-MM-dd") + ); + + for (DateTimeFormatter f : formatters) { + try { + return LocalDate.parse(dateStr, f); + } catch (Exception ignored) {} + } + + throw new DateTimeParseException("Invalid date format: " + dateStr, dateStr, 0); + } + @Override + public List saveAllIfa(List dtoList) { + return dtoList.stream() + .map(this::mapToEntity) + .map(ifaDistributionRepository::save) + .toList(); + } + + + + @Override + public List getByBeneficiaryId(GetBenRequestHandler requestHandler) { + return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()).stream() + .map(this::mapToDTO) + .toList(); + } + // 🔁 Entity → DTO (date formatted as dd-MM-yyyy) + private IfaDistributionDTO mapToDTO(IfaDistribution entity) { + final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + IfaDistributionDTO dto = new IfaDistributionDTO(); + + dto.setBeneficiaryId(entity.getBeneficiaryId()); + dto.setHouseHoldId(entity.getHouseHoldId()); + dto.setFormId(entity.getFormId()); + dto.setVisitDate(entity.getVisitDate()); + + IfaDistributionDTO.FieldsDTO fields = new IfaDistributionDTO.FieldsDTO(); + + if (entity.getIfaProvisionDate() != null) { + fields.setIfa_provision_date(entity.getIfaProvisionDate().format(FORMATTER)); + } + fields.setMcp_card_upload(entity.getMcpCardUpload()); + fields.setIfa_bottle_count(Double.valueOf(entity.getIfaBottleCount())); + + dto.setFields(fields); + return dto; + } + + // 🔄 Helper method to convert DTO → Entity + private IfaDistribution mapToEntity(IfaDistributionDTO dto) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + IfaDistribution entity = new IfaDistribution(); + + entity.setBeneficiaryId(dto.getBeneficiaryId()); + entity.setHouseHoldId(dto.getHouseHoldId()); + entity.setFormId(dto.getFormId()); + entity.setVisitDate(dto.getVisitDate()); + entity.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); + + if (dto.getFields() != null) { + if (dto.getFields().getIfa_provision_date() != null) { + try { + entity.setIfaProvisionDate(LocalDate.parse( + dto.getFields().getIfa_provision_date(), + DateTimeFormatter.ofPattern("dd-MM-yyyy") + )); + } catch (Exception e) { + entity.setIfaProvisionDate(null); + } + } + entity.setIfaBottleCount(dto.getFields().getIfa_bottle_count().toString()); + entity.setMcpCardUpload(dto.getFields().getMcp_card_upload()); + } + + return entity; + } + + private void checkAndAddSamVisitNRCReferalIncentive(List samVisits){ + samVisits.forEach(samVisit -> { + IncentiveActivity samreferralnrcActivityAm = + incentivesRepo.findIncentiveMasterByNameAndGroup("SAM_REFERRAL_NRC", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity samreferralnrcActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("SAM_REFERRAL_NRC", GroupName.ACTIVITY.getDisplayName()); + if(samreferralnrcActivityAm!=null){ + if(samVisit.getIsChildReferredNrc().equals("Yes")){ + createIncentiveRecordforSamReferalToNrc(samVisit,samVisit.getBeneficiaryId(),samreferralnrcActivityAm,jwtUtil.getUserNameFromStorage()); + } + } + + if(samreferralnrcActivityCH!=null){ + if(samVisit.getIsChildReferredNrc().equals("Yes")){ + createIncentiveRecordforSamReferalToNrc(samVisit,samVisit.getBeneficiaryId(),samreferralnrcActivityCH,jwtUtil.getUserNameFromStorage()); + } + } + + + }); + + } + private void checkAndAddOrdDistributionIncentive(List orsDistributionList){ + orsDistributionList.forEach(orsDistribution -> { + IncentiveActivity orsPacketActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("ORS_DISTRIBUTION", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity orsPacketActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("ORS_DISTRIBUTION", GroupName.ACTIVITY.getDisplayName()); + if(orsPacketActivityAM!=null){ + if(orsDistribution.getNumOrsPackets()!=null){ + createIncentiveRecordforOrsDistribution(orsDistribution,orsDistribution.getBeneficiaryId(),orsPacketActivityAM,userRepo.getUserNamedByUserId(orsDistribution.getUserId()),false); + } + } + + if(orsPacketActivityCH!=null){ + if(orsDistribution.getNumOrsPackets()!=null){ + createIncentiveRecordforOrsDistribution(orsDistribution,orsDistribution.getBeneficiaryId(),orsPacketActivityCH,userRepo.getUserNamedByUserId(orsDistribution.getUserId()),true); + } + } + + + }); + + } + + private void checkAndAddHbyncIncentives(List hbycList) { + IncentiveActivity hbync15MonethVisitActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HBYC_QUARTERLY_VISITS", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity hbyncVisitActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("HBYC_QUARTERLY_VISITS", GroupName.CHILD_HEALTH.getDisplayName()); + + + IncentiveActivity hbyncOrsPacketActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("ORS_DISTRIBUTION", GroupName.ACTIVITY.getDisplayName()); + + hbycList.forEach(hbyc -> { + Set eligibleHbycVisits = Set.of("3 Months", "6 Months", "9 Months", "12 Months", "15 Months"); + + if (hbyncVisitActivity != null && eligibleHbycVisits.contains(hbyc.getVisit_day())) { + createIncentiveRecordforHbyncVisit(hbyc, hbyc.getBeneficiaryId(), hbyncVisitActivity, hbyc.getCreated_by()); + } + + if (hbync15MonethVisitActivityCH != null && eligibleHbycVisits.contains(hbyc.getVisit_day())) { + createIncentiveRecordforHbyncVisit(hbyc, hbyc.getBeneficiaryId(), hbync15MonethVisitActivityCH, hbyc.getCreated_by()); + } + + + + + + if (hbyncOrsPacketActivityCH != null) { + if (hbyc.getOrs_given()) { + createIncentiveRecordforHbyncOrsDistribution(hbyc, hbyc.getBeneficiaryId(), hbyncOrsPacketActivityCH, hbyc.getCreated_by()); + + } + + } + + }); + + + } + + private void checkAndAddHbncIncentives(List hbncVisits) { + hbncVisits.forEach(hbncVisit -> { + boolean isVisitDone = List.of("1st Day", "3rd Day", "7th Day", "42nd Day") + .stream() + .allMatch(hbncVisits::contains); + + GroupName.setIsCh(false); + Long benId = hbncVisit.getBeneficiaryId(); + if (hbncVisit.getVisit_day().equals("42nd Day")) { + IncentiveActivity visitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS_CH"); + + } + logger.info("getDischarged_from_sncu" + hbncVisit.getDischarged_from_sncu()); + + if (hbncVisit.getVisit_day().equals("42nd Day") && hbncVisit.getDischarged_from_sncu() && hbncVisit.getBaby_weight() <=2.5) { + IncentiveActivity babyDisChargeSNCUAActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("SNCU_LBW_FOLLOWUP", GroupName.CHILD_HEALTH.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, babyDisChargeSNCUAActivity, "SNCU_LBW_FOLLOWUP"); + + } + logger.info("getIs_baby_alive" + hbncVisit.getIs_baby_alive()); + if (!hbncVisit.getIs_baby_alive()) { + IncentiveActivity isChildDeathActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, isChildDeathActivity, "CHILD_DEATH_REPORTING"); + } + + + }); + + + } + + private void checkAndAddIncentives(List vaccinationList) { - vaccinationList.forEach( vaccination -> { + + vaccinationList.forEach(vaccination -> { Long benId = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()).longValue(); Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); - if(immunizationServiceId < 6) { - IncentiveActivity immunizationActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("IMMUNIZATION_0_1", "IMMUNIZATION"); - if (immunizationActivity != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + if (immunizationServiceId < 6) { + IncentiveActivity immunizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.ACTIVITY.getDisplayName()); + + + if (immunizationActivityAM != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity); + createIncentiveRecord(vaccination, benId, userId, immunizationActivityAM); } - } else if(immunizationServiceId == 7) { - IncentiveActivity immunizationActivity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup("IMMUNIZATION_1_2", "IMMUNIZATION"); - if (immunizationActivity2 != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + + if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getFirstYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + } + } else if (immunizationServiceId == 7) { + IncentiveActivity immunizationActivity2AM = + incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivity2CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity2AM != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2); + createIncentiveRecord(vaccination, benId, userId, immunizationActivity2AM); } - } else if(immunizationServiceId == 8) { - IncentiveActivity immunizationActivity5 = - incentivesRepo.findIncentiveMasterByNameAndGroup("IMMUNIZATION_5", "IMMUNIZATION"); - if (immunizationActivity5 != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity5); + if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getSecondYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); } } + IncentiveActivity immunizationActivity5AM = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.IMMUNIZATION.getDisplayName()); + if (immunizationActivity5AM != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5AM); + } + + IncentiveActivity immunizationActivity5CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); + } }); } private void createIncentiveRecord(ChildVaccination vaccination, Long benId, Integer userId, IncentiveActivity immunizationActivity) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), vaccination.getCreatedDate(), benId); + if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(immunizationActivity.getId()); record.setCreatedDate(vaccination.getCreatedDate()); record.setCreatedBy(vaccination.getCreatedBy()); - record.setName(immunizationActivity.getName()); record.setStartDate(vaccination.getCreatedDate()); record.setEndDate(vaccination.getCreatedDate()); record.setUpdatedDate(vaccination.getCreatedDate()); @@ -404,7 +899,167 @@ record = new IncentiveActivityRecord(); } } + private void createIncentiveRecordforHbncVisit(HbncVisit hbncVisit, Long benId, IncentiveActivity immunizationActivity, String activityName) { + logger.info("RecordIncentive" + activityName); + + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), hbncVisit.getCreatedDate(), benId); + + if (record == null) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + // Convert to LocalDate + LocalDate localDate = LocalDate.parse(hbncVisit.getVisit_date(), formatter); + + // Convert LocalDate to Timestamp (00:00:00 by default) + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(visitDate); + record.setCreatedBy(hbncVisit.getCreatedBy()); + record.setStartDate(visitDate); + record.setEndDate(visitDate); + record.setUpdatedDate(visitDate); + record.setUpdatedBy(hbncVisit.getCreatedBy()); + record.setBenId(benId); + record.setAshaId(hbncVisit.getAshaId()); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } + } + + private void createIncentiveRecordforHbyncVisit(HbycChildVisit data, Long benId, IncentiveActivity immunizationActivity, String createdBy) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + // Convert to LocalDate + LocalDate localDate = LocalDate.parse(data.getVisit_date(), formatter); + + // Convert LocalDate to Timestamp (00:00:00 by default) + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId); + + + if (record == null) { + + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(visitDate); + record.setCreatedBy(createdBy); + record.setStartDate(visitDate); + record.setEndDate(visitDate); + record.setUpdatedDate(visitDate); + record.setUpdatedBy(createdBy); + record.setBenId(benId); + record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } + } + + + private void createIncentiveRecordforHbyncOrsDistribution(HbycChildVisit data, Long benId, IncentiveActivity immunizationActivity, String createdBy) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + // Convert to LocalDate + LocalDate localDate = LocalDate.parse(data.getVisit_date(), formatter); + + // Convert LocalDate to Timestamp (00:00:00 by default) + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId); + + + if (record == null) { + + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(visitDate); + record.setCreatedBy(createdBy); + record.setStartDate(visitDate); + record.setEndDate(visitDate); + record.setUpdatedDate(visitDate); + record.setUpdatedBy(createdBy); + record.setBenId(benId); + record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } + } + + private void createIncentiveRecordforOrsDistribution(OrsDistribution data, Long benId, IncentiveActivity immunizationActivity, String createdBy,boolean isCH) { + try { + // Convert to LocalDate + Timestamp visitDate = Timestamp.valueOf(data.getVisitDate().atStartOfDay()); + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId); + double packets = Double.parseDouble(data.getNumOrsPackets()); + double rate = immunizationActivity.getRate(); + + if (record == null) { + + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(visitDate); + record.setCreatedBy(createdBy); + record.setStartDate(visitDate); + record.setEndDate(visitDate); + record.setUpdatedDate(visitDate); + record.setUpdatedBy(createdBy); + record.setBenId(benId); + record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + if(isCH){ + record.setAmount((long) rate); + + }else { + record.setAmount((long) (rate * packets)); + + } + recordRepo.save(record); + } + }catch (Exception e){ + logger.error("Exp"+e.getMessage()); + + } + + } + + private void createIncentiveRecordforSamReferalToNrc(SamVisit data, Long benId, IncentiveActivity incentiveActivity, String createdBy) { + try { + // Convert to LocalDate + Timestamp visitDate = Timestamp.valueOf(data.getVisitDate().atStartOfDay()); + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), visitDate, benId); + + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(visitDate); + record.setCreatedBy(createdBy); + record.setStartDate(visitDate); + record.setEndDate(visitDate); + record.setUpdatedDate(visitDate); + record.setUpdatedBy(createdBy); + record.setBenId(benId); + record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAmount((long) incentiveActivity.getRate()); + recordRepo.save(record); + } + }catch (Exception e){ + logger.error("Exp"+e.getMessage()); + + } + + } + + private Integer getImmunizationServiceIdForVaccine(Short vaccineId) { return vaccineRepo.getImmunizationServiceIdByVaccineId(vaccineId); } + + public void getTomorrowImmunizationReminders(Integer userID) { + + } + } diff --git a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java index a171e4f3..95b0557b 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -1,12 +1,16 @@ package com.iemr.flw.service.impl; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.EligibleCoupleDTO; import com.iemr.flw.dto.iemr.EligibleCoupleTrackingDTO; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.CoupleService; @@ -15,8 +19,13 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import java.math.BigInteger; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; import java.util.List; import java.util.stream.Collectors; @@ -25,10 +34,10 @@ public class CoupleServiceImpl implements CoupleService { ObjectMapper mapper = new ObjectMapper(); ModelMapper modelMapper = new ModelMapper(); - + @Autowired private EligibleCoupleRegisterRepo eligibleCoupleRegisterRepo; - + @Autowired private EligibleCoupleTrackingRepo eligibleCoupleTrackingRepo; @@ -40,12 +49,90 @@ public class CoupleServiceImpl implements CoupleService { @Autowired private IncentiveRecordRepo recordRepo; - + @Autowired private BeneficiaryRepo beneficiaryRepo; private final Logger logger = LoggerFactory.getLogger(CoupleServiceImpl.class); + + @Override + public String registerEligibleCouple(List eligibleCoupleDTOs, MultipartFile kitPhoto1, MultipartFile kitPhoto2) { + try { + List ecrList = new ArrayList<>(); + List recordList = new ArrayList<>(); + eligibleCoupleDTOs.forEach(it -> { + EligibleCoupleRegister existingECR = +// eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenIdAndCreatedDate(it.getBenId(), it.getCreatedDate()); + eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); + if (kitPhoto1 != null) { + String kitPhoto1base64Image = null; + try { + kitPhoto1base64Image = Base64.getEncoder().encodeToString(kitPhoto1.getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + existingECR.setKitPhoto1(String.valueOf(kitPhoto1base64Image)); + + } + + + if (kitPhoto2 != null) { + String kitPhoto2base64Image = null; + try { + kitPhoto2base64Image = Base64.getEncoder().encodeToString(kitPhoto2.getBytes()); + } catch (IOException e) { + throw new RuntimeException(e); + } + existingECR.setKitPhoto2(String.valueOf(kitPhoto2base64Image)); + + } + + if (existingECR != null && null != existingECR.getNumLiveChildren()) { + if (existingECR.getNumLiveChildren() == 0 && it.getNumLiveChildren() >= 1 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 2) { + IncentiveActivity activity1 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()); + createIncentiveRecord(recordList, it, activity1); + } else if (existingECR.getNumLiveChildren() == 1 && it.getNumLiveChildren() >= 2 && it.getFirstAndSecondChildGap() != null && it.getFirstAndSecondChildGap() == 3) { + IncentiveActivity activity2 = + incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); + createIncentiveRecord(recordList, it, activity2); + } + Long id = existingECR.getId(); + + modelMapper.map(it, existingECR); + existingECR.setId(id); + } else { + existingECR = new EligibleCoupleRegister(); + modelMapper.map(it, existingECR); + existingECR.setId(null); + } + if (existingECR.getIsKitHandedOver() && (!existingECR.getKitPhoto1().isEmpty() || !existingECR.getKitPhoto2().isEmpty())) { + IncentiveActivity handoverKitActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); + if (handoverKitActivityAM != null) { + createIncentiveRecord(recordList, it, handoverKitActivityAM); + + } + + + IncentiveActivity handoverKitActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); + if (handoverKitActivityCH != null) { + createIncentiveRecord(recordList, it, handoverKitActivityCH); + + } + } + ecrList.add(existingECR); + }); + eligibleCoupleRegisterRepo.saveAll(ecrList); + recordRepo.saveAll(recordList); + return "no of ecr details saved: " + ecrList.size(); + } catch (Exception e) { + return "error while saving ecr details: " + e.getMessage(); + } + } + @Override public String registerEligibleCouple(List eligibleCoupleDTOs) { try { @@ -57,14 +144,23 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); if (existingECR != null && null != existingECR.getNumLiveChildren()) { - if(existingECR.getNumLiveChildren() == 0 && it.getNumLiveChildren() >= 1 && null != it.getMarriageFirstChildGap() && it.getMarriageFirstChildGap() >= 3) { + if (it.getNumLiveChildren() >= 1 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 2) { IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()) + ; + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(recordList, it, activity1); - } else if (existingECR.getNumLiveChildren() == 1 && it.getNumLiveChildren() >= 2 && null != it.getMarriageFirstChildGap() && it.getMarriageFirstChildGap() >= 2) { + createIncentiveRecord(recordList, it, activityCH); + } else if (it.getNumLiveChildren() >= 2 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 3) { IncentiveActivity activity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(recordList, it, activity2); + createIncentiveRecord(recordList, it, activityCH); } Long id = existingECR.getId(); modelMapper.map(it, existingECR); @@ -74,6 +170,24 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) modelMapper.map(it, existingECR); existingECR.setId(null); } + + + if (existingECR.getIsKitHandedOver()) { + IncentiveActivity handoverKitActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); + if (handoverKitActivityAM != null) { + createIncentiveRecord(recordList, it, handoverKitActivityAM); + + } + + + IncentiveActivity handoverKitActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); + if (handoverKitActivityCH != null) { + createIncentiveRecord(recordList, it, handoverKitActivityCH); + + } + } ecrList.add(existingECR); }); eligibleCoupleRegisterRepo.saveAll(ecrList); @@ -84,6 +198,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) } } + private void createIncentiveRecord(List recordList, EligibleCoupleDTO eligibleCoupleDTO, IncentiveActivity activity) { if (activity != null) { IncentiveActivityRecord record = recordRepo @@ -94,7 +209,6 @@ record = new IncentiveActivityRecord(); record.setActivityId(activity.getId()); record.setCreatedDate(eligibleCoupleDTO.getCreatedDate()); record.setCreatedBy(eligibleCoupleDTO.getCreatedBy()); - record.setName(activity.getName()); record.setStartDate(eligibleCoupleDTO.getCreatedDate()); record.setEndDate(eligibleCoupleDTO.getCreatedDate()); record.setUpdatedDate(eligibleCoupleDTO.getCreatedDate()); @@ -138,53 +252,143 @@ public String registerEligibleCoupleTracking(List eli private void checkAndAddAntaraIncentive(List recordList, EligibleCoupleTracking ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); - List couplesHadAntara = eligibleCoupleTrackingRepo.findCouplesHadAntara(ect.getBenId()); - Integer numAntaraDosage = 0; - if(couplesHadAntara != null && couplesHadAntara.size() > 0) { - numAntaraDosage = couplesHadAntara.size(); - } + logger.info("Antra" + ect.getMethodOfContraception()); + logger.info("Antra" + ect.getAntraDose()); + if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().contains("ANTRA Injection")) { + // for CG incentive + IncentiveActivity antaraActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", GroupName.ACTIVITY.getDisplayName()); + if (antaraActivityCH != null) { + String dose = ect.getAntraDose(); - if(ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("ANTRA Injection")) { - if (numAntaraDosage == 0) { + List validDoses = Arrays.asList("Dose-1", "Dose-2", "Dose-3", "Dose-4"); + + boolean isDose = validDoses.stream().anyMatch(dose::contains); + + if (isDose) { + addIncenticeRecord(recordList, ect, userId, antaraActivityCH); + + } + } + if (ect.getAntraDose().contains("Dose-1")) { IncentiveActivity antaraActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANTARA_PROG_1", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", "FAMILY PLANNING"); if (antaraActivity != null) { addIncenticeRecord(recordList, ect, userId, antaraActivity); } - } else if (numAntaraDosage == 1) { + } else if (ect.getAntraDose().contains("Dose-2")) { IncentiveActivity antaraActivity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANTARA_PROG_2", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA2", "FAMILY PLANNING"); if (antaraActivity2 != null) { addIncenticeRecord(recordList, ect, userId, antaraActivity2); } - } else if (numAntaraDosage == 2) { + } else if (ect.getAntraDose().contains("Dose-3")) { IncentiveActivity antaraActivity3 = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANTARA_PROG_3", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA3", "FAMILY PLANNING"); if (antaraActivity3 != null) { addIncenticeRecord(recordList, ect, userId, antaraActivity3); } - } else if (numAntaraDosage == 3) { + } else if (ect.getAntraDose().contains("Dose-4")) { IncentiveActivity antaraActivity4 = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANTARA_PROG_4", "FAMILY PLANNING"); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA4", "FAMILY PLANNING"); + if (antaraActivity4 != null) { + addIncenticeRecord(recordList, ect, userId, antaraActivity4); + } + + + } else if (ect.getAntraDose().contains("Dose-5")) { + IncentiveActivity antaraActivity4 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA5", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity antaraActivity4CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", GroupName.ACTIVITY.getDisplayName()); + if (antaraActivity4CH != null) { + addIncenticeRecord(recordList, ect, userId, antaraActivity4CH); + } + if (antaraActivity4 != null) { addIncenticeRecord(recordList, ect, userId, antaraActivity4); } } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("MALE STERILIZATION")) { + + IncentiveActivity maleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", "FAMILY PLANNING"); + + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); + if (maleSterilizationActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityAM); + } + + if (maleSterilizationActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityCH); + } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("FEMALE STERILIZATION")) { + + IncentiveActivity femaleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); + if (femaleSterilizationActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityAM); + } + + if (femaleSterilizationActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityCH); + } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("MiniLap")) { + + IncentiveActivity miniLapActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", "FAMILY PLANNING"); + if (miniLapActivity != null) { + addIncenticeRecord(recordList, ect, userId, miniLapActivity); + } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("Condom")) { + + IncentiveActivity comdomActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", "FAMILY PLANNING"); + if (comdomActivity != null) { + addIncenticeRecord(recordList, ect, userId, comdomActivity); + } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("Copper T (IUCD)")) { + + IncentiveActivity copperTActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", "FAMILY PLANNING"); + if (copperTActivity != null) { + addIncenticeRecord(recordList, ect, userId, copperTActivity); + } + } + if (ect.getMethodOfContraception() != null && (ect.getMethodOfContraception().contains("POST PARTUM STERILIZATION (PPS WITHIN 7 DAYS OF DELIVERY)") || ect.getMethodOfContraception().contains("MiniLap") || ect.getMethodOfContraception().contains("MALE STERILIZATION") || ect.getMethodOfContraception().contains("FEMALE STERILIZATION"))) { + IncentiveActivity limitiing2ChildActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_LIMIT_2CHILD", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity limitiing2ChildActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_LIMIT_2CHILD", GroupName.ACTIVITY.getDisplayName()); + if (limitiing2ChildActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, limitiing2ChildActivityAM); + } + + if (limitiing2ChildActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, limitiing2ChildActivityCH); + } } } private void addIncenticeRecord(List recordList, EligibleCoupleTracking ect, Integer userId, IncentiveActivity antaraActivity) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); + // get bene details + if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(antaraActivity.getId()); - record.setCreatedDate(ect.getCreatedDate()); + record.setCreatedDate(ect.getVisitDate()); record.setCreatedBy(ect.getCreatedBy()); - record.setName(antaraActivity.getName()); - record.setStartDate(ect.getCreatedDate()); - record.setEndDate(ect.getCreatedDate()); - record.setUpdatedDate(ect.getCreatedDate()); + record.setStartDate(ect.getVisitDate()); + record.setEndDate(ect.getVisitDate()); + record.setUpdatedDate(ect.getVisitDate()); record.setUpdatedBy(ect.getCreatedBy()); record.setBenId(ect.getBenId()); record.setAshaId(userId); @@ -202,7 +406,9 @@ public String getEligibleCoupleRegRecords(GetBenRequestHandler dto) { List list = eligibleCoupleRegisterList.stream() .map(eligibleCoupleRegister -> mapper.convertValue(eligibleCoupleRegister, EligibleCoupleDTO.class)) .collect(Collectors.toList()); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + Gson gson = new GsonBuilder() + .serializeNulls() + .setDateFormat("MMM dd, yyyy h:mm:ss a").create(); return gson.toJson(list); } catch (Exception e) { logger.error(e.getMessage()); @@ -218,6 +424,7 @@ public List getEligibleCoupleTracking(GetBenRequestHa List eligibleCoupleTrackingList = eligibleCoupleTrackingRepo.getECTrackRecords(user, dto.getFromDate(), dto.getToDate()); + return eligibleCoupleTrackingList.stream() .map(ect -> mapper.convertValue(ect, EligibleCoupleTrackingDTO.class)) .collect(Collectors.toList()); @@ -226,4 +433,6 @@ public List getEligibleCoupleTracking(GetBenRequestHa } return null; } + + } diff --git a/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java new file mode 100644 index 00000000..4c85ae66 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java @@ -0,0 +1,128 @@ +package com.iemr.flw.service.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Paths; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.iemr.flw.dto.crashlogs.CrashLogRequest; +import com.iemr.flw.service.CrashLogService; +import com.iemr.flw.utils.exception.IEMRException; +import org.springframework.beans.factory.annotation.Value; + +@Service +public class CrashLogServiceImpl implements CrashLogService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + // @Value("${crash.logs.base.path}") + private String crashLogsBasePath; + + @Override + public String saveCrashLog(CrashLogRequest request, Integer userId, MultipartFile file) + throws IEMRException { + + try { + // 🛡️ Validate file + if (file.isEmpty()) { + throw new IEMRException("Uploaded file is empty"); + } + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null) { + throw new IEMRException("Invalid filename"); + } + + // Prevent path traversal + String safeOriginalName = Paths.get(originalFilename).getFileName().toString(); + + // Only allow .txt + if (!safeOriginalName.toLowerCase().endsWith(".txt")) { + throw new IEMRException("Only .txt files are allowed"); + } + + // Validate MIME + String contentType = file.getContentType(); + if (contentType == null || + (!contentType.equals("text/plain") && + !contentType.equals("application/octet-stream"))) { + throw new IEMRException("Invalid file type. Only plain text allowed."); + } + + // Block binary content + if (isBinaryFile(file.getBytes())) { + throw new IEMRException("Binary files are not allowed. Upload valid text logs only."); + } + + // 📁 Create date-based folder + LocalDate date = LocalDate.now(); + String dateFolder = date.format(DateTimeFormatter.ISO_LOCAL_DATE); + + File dateDir = new File(crashLogsBasePath, dateFolder); + if (!dateDir.exists() && !dateDir.mkdirs()) { + throw new IEMRException("Failed to create folder: " + dateDir.getAbsolutePath()); + } + + // Use timestamp as sent by frontend (NO conversion) + String rawTimestamp = request.getTimestamp(); // Already "yyyy-MM-dd HH:mm:ss" + + // Make timestamp filename-safe + String safeTimestamp = rawTimestamp + .replace(" ", "_") + .replace(":", "-"); + + // 📝 Final file name + String filename = String.format( + "%d_%s_%s_%s.txt", + userId, + sanitizeFilename(request.getAppVersion()), + sanitizeFilename(request.getDeviceId()), + sanitizeFilename(safeTimestamp)); + + File crashLogFile = new File(dateDir, filename); + + // 💾 Save file + try (FileOutputStream fos = new FileOutputStream(crashLogFile)) { + fos.write(file.getBytes()); + } + + String relativePath = dateFolder + "/" + filename; + logger.info("Crash log saved: " + relativePath); + + return relativePath; + + } catch (IOException e) { + logger.error("Error saving crash log", e); + throw new IEMRException("Error saving crash log: " + e.getMessage(), e); + } + } + + // Detect binary content + private boolean isBinaryFile(byte[] data) { + int len = Math.min(data.length, 2048); + for (int i = 0; i < len; i++) { + byte b = data[i]; + if (b < 0x09) + return true; + if (b > 0x0D && b < 0x20) + return true; + } + return false; + } + + // Sanitize metadata for filename safety + private String sanitizeFilename(String input) { + if (input == null) + return "unknown"; + return input.replaceAll("[^a-zA-Z0-9.-]", "_"); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java index 1c4dabdd..684a03b2 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -1,14 +1,14 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; -import com.iemr.flw.domain.iemr.CDR; -import com.iemr.flw.domain.iemr.MDSR; +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; +import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.CdrDTO; import com.iemr.flw.dto.iemr.MdsrDTO; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; -import com.iemr.flw.repo.iemr.CdrRepo; -import com.iemr.flw.repo.iemr.MdsrRepo; +import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.DeathReportsService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; @@ -34,6 +34,16 @@ public class DeathReportsServiceImpl implements DeathReportsService { ModelMapper modelMapper = new ModelMapper(); + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + + @Override public String registerCDR(List cdrDTOs) { try { @@ -47,6 +57,7 @@ public String registerCDR(List cdrDTOs) { modelMapper.map(it, existingCDR); existingCDR.setId(id); } else { + existingCDR = new CDR(); modelMapper.map(it, existingCDR); existingCDR.setId(null); @@ -54,6 +65,8 @@ public String registerCDR(List cdrDTOs) { cdrList.add(existingCDR); }); cdrRepo.saveAll(cdrList); + checkAndAddIncentives(cdrList); + return "no of cdr details saved: " + cdrDTOs.size(); } catch (Exception e) { return "error while saving cdr details: " + e.getMessage(); @@ -80,6 +93,8 @@ public String registerMDSR(List mdsrDTOs) { mdsrList.add(mdsr); }); mdsrRepo.saveAll(mdsrList); + checkAndAddIncentivesMdsr(mdsrList); + return "no of mdsr details saved: " + mdsrDTOs.size(); } catch (Exception e) { return "error while saving mdsr details: " + e.getMessage(); @@ -117,4 +132,79 @@ public List getMdsrRecords(GetBenRequestHandler dto) { } return null; } + + private void checkAndAddIncentives(List cdrList) { + + cdrList.forEach( cdr -> { + Integer userId = userRepo.getUserIdByName(cdr.getCreatedBy()); + IncentiveActivity immunizationActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); + if(immunizationActivity!=null){ + createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); + + } + }); + } + + + private void checkAndAddIncentivesMdsr(List mdsrList) { + + + mdsrList.forEach( mdsr -> { + Integer userId = userRepo.getUserIdByName(mdsr.getCreatedBy()); + IncentiveActivity immunizationActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("MATERNAL_DEATH_REPORT", GroupName.MATERNAL_HEALTH.getDisplayName()); + if(immunizationActivity!=null){ + createIncentiveRecord(mdsr,mdsr.getBenId(),userId,immunizationActivity); + + } + }); + } + + + + private void createIncentiveRecord(CDR cdr, Long benId, Integer userId, IncentiveActivity immunizationActivity) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), cdr.getCreatedDate(), benId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(cdr.getCreatedDate()); + record.setCreatedBy(cdr.getCreatedBy()); + record.setStartDate(cdr.getCreatedDate()); + record.setEndDate(cdr.getCreatedDate()); + record.setUpdatedDate(cdr.getCreatedDate()); + record.setUpdatedBy(cdr.getCreatedBy()); + record.setBenId(benId); + record.setAshaId(userId); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } + } + + private void createIncentiveRecord(MDSR mdsr, Long benId, Integer userId, IncentiveActivity immunizationActivity) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), mdsr.getCreatedDate(), benId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(mdsr.getCreatedDate()); + record.setCreatedBy(mdsr.getCreatedBy()); + record.setStartDate(mdsr.getCreatedDate()); + record.setEndDate(mdsr.getCreatedDate()); + record.setUpdatedDate(mdsr.getCreatedDate()); + record.setUpdatedBy(mdsr.getCreatedBy()); + record.setBenId(benId); + record.setAshaId(userId); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } + } + + + + + + + } diff --git a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java index 2936b79a..3ccd9973 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -1,20 +1,35 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; import com.iemr.flw.domain.iemr.DeliveryOutcome; +import com.iemr.flw.domain.iemr.HbncVisit; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.DeliveryOutcomeDTO; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.identity.HouseHoldRepo; import com.iemr.flw.repo.iemr.DeliveryOutcomeRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.DeliveryOutcomeService; +import jakarta.annotation.PostConstruct; +import org.apache.commons.lang3.Validate; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.math.BigInteger; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @@ -30,12 +45,31 @@ public class DeliveryOutcomeServiceImpl implements DeliveryOutcomeService { // @Autowired // private EligibleCoupleRegisterRepo ecrRepo; + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + + @Autowired + private HouseHoldRepo houseHoldRepo; + + private boolean isJsyBeneficiary; + + + private Gson gson = new Gson(); + private final Logger logger = LoggerFactory.getLogger(DeliveryOutcomeServiceImpl.class); ObjectMapper mapper = new ObjectMapper(); ModelMapper modelMapper = new ModelMapper(); + boolean institutionalDelivery = false; + @Override public String registerDeliveryOutcome(List deliveryOutcomeDTOS) { @@ -62,23 +96,149 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT delOutList.add(deliveryoutcome); }); deliveryOutcomeRepo.saveAll(delOutList); + + checkAndAddJsyIncentive(delOutList); // ecrRepo.save(ecrList); return "no of delivery outcome details saved: " + delOutList.size(); } catch (Exception e) { return "error while saving delivery outcome details: " + e.getMessage(); } } + @Override public List getDeliveryOutcome(GetBenRequestHandler dto) { - try{ - String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user, dto.getFromDate(), dto.getToDate()); + try { + String user = userRepo.getUserNamedByUserId(dto.getAshaId()); + List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user,dto.getFromDate(),dto.getToDate()); + logger.info("DeliveryOutcome Response{}",deliveryOutcomeList); return deliveryOutcomeList.stream() .map(deliveryOutcome -> mapper.convertValue(deliveryOutcome, DeliveryOutcomeDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error(e.getMessage()); + logger.error("DeliveryOutcome Exception:"+e.getMessage()); } return null; } + + + public void checkAndAddJsyIncentive(List delOutList) { + + delOutList.forEach(deliveryOutcome -> { + + IncentiveActivity institutionalDeliveryActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("MH_MOTIVATE_INST_DEL", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity institutionalDeliveryActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("INST_DELIVERY_ESCORT", GroupName.ACTIVITY.getDisplayName()); + if (deliveryOutcome.getPlaceOfDelivery() != null) { + String placeOfDelivery = deliveryOutcome.getPlaceOfDelivery(); + + if (placeOfDelivery != null && + (!placeOfDelivery.equalsIgnoreCase("home") || + !placeOfDelivery.equalsIgnoreCase("in transit") || + !placeOfDelivery.equalsIgnoreCase("other private hospital"))) { + + // Institutional delivery (eligible case) + if (institutionalDeliveryActivityAM != null) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), institutionalDeliveryActivityAM); + } + + if (institutionalDeliveryActivityCH != null) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), institutionalDeliveryActivityCH); + } + } + } + + if (deliveryOutcome.getIsJSYBenificiary()) { + IncentiveActivity incentiveActivityInstJSY1 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_1ST_DEL_INST_RURAL", GroupName.JSY.getDisplayName()); + IncentiveActivity incentiveActivityInstJSY2 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_2ND_DEL_INST_RURAL", GroupName.JSY.getDisplayName()); + IncentiveActivity incentiveActivityInstJSY3 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_3RD_DEL_INST_RURAL", GroupName.JSY.getDisplayName()); + IncentiveActivity incentiveActivityInstJSY4 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_4TH_DEL_INST_RURAL", GroupName.JSY.getDisplayName()); + + + logger.info("delOutList" + gson.toJson(deliveryOutcome)); + IncentiveActivity incentiveActivityJSY1 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_1ST_DEL_ANC_RURAL", GroupName.JSY.getDisplayName()); + if (incentiveActivityJSY1 != null) { + if (deliveryOutcome.getDeliveryOutcome() == 1) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityJSY1); + if (deliveryOutcome.getPlaceOfDelivery() != null) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityInstJSY1); + } + } + } + + + IncentiveActivity incentiveActivityJSY2 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_2ND_DEL_ANC_RURAL", GroupName.JSY.getDisplayName()); + if (incentiveActivityJSY2 != null) { + if (deliveryOutcome.getDeliveryOutcome() == 2) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityJSY2); + if (deliveryOutcome.getPlaceOfDelivery() != null) { + + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityInstJSY2); + } + } + } + + IncentiveActivity incentiveActivityJSY3 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_3RD_DEL_ANC_RURAL", GroupName.JSY.getDisplayName()); + if (incentiveActivityJSY3 != null) { + if (deliveryOutcome.getDeliveryOutcome() == 3) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityJSY3); + if (deliveryOutcome.getPlaceOfDelivery() != null) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityInstJSY3); + } + } + } + + IncentiveActivity incentiveActivityJSY4 = incentivesRepo.findIncentiveMasterByNameAndGroup("JSY_4TH_DEL_ANC_RURAL", GroupName.JSY.getDisplayName()); + if (incentiveActivityJSY4 != null) { + if (deliveryOutcome.getDeliveryOutcome() == 4) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityJSY4); + if (deliveryOutcome.getPlaceOfDelivery() != null) { + createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityInstJSY4); + + } + } + } + + } + + + }); + +// JSY_ANC_URBAN +// JSY_INST_URBAN + + + } + + private void createIncentiveRecordforJsy(DeliveryOutcome delOutList, Long benId, IncentiveActivity immunizationActivity) { + logger.info("benId" + benId); + + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), delOutList.getCreatedDate(), benId); + + + if (record == null) { + logger.info("setStartDate" + delOutList.getDateOfDelivery()); + logger.info("setCreatedDate" + delOutList.getCreatedDate()); + record = new IncentiveActivityRecord(); + record.setActivityId(immunizationActivity.getId()); + record.setCreatedDate(delOutList.getDateOfDelivery()); + record.setCreatedBy(delOutList.getCreatedBy()); + record.setStartDate(delOutList.getDateOfDelivery()); + record.setEndDate(delOutList.getDateOfDelivery()); + record.setUpdatedDate(delOutList.getCreatedDate()); + record.setUpdatedBy(delOutList.getCreatedBy()); + record.setBenId(benId); + record.setAshaId(userRepo.getUserIdByName(delOutList.getUpdatedBy())); + record.setAmount(Long.valueOf(immunizationActivity.getRate())); + recordRepo.save(record); + } else { + logger.info("benId:" + record.getId()); + + } + } catch (Exception e) { + logger.error("JSY Incentive:", e); + } + + + } } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java new file mode 100644 index 00000000..b005f2d6 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -0,0 +1,1223 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.controller.CoupleController; +import com.iemr.flw.domain.iemr.*; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.DiseaseType; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.DiseaseControlService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; +import org.modelmapper.ModelMapper; + +@Service +public class DiseaseControlServiceImpl implements DiseaseControlService { + + @Autowired + private DiseaseMalariaRepository diseaseMalariaRepository; + + private final ModelMapper modelMapper = new ModelMapper(); + + @Autowired + private DiseaseAESJERepository diseaseAESJERepository; + @Autowired + private DiseaseFilariasisRepository diseaseFilariasisRepository; + @Autowired + private DiseaseKalaAzarRepository diseaseKalaAzarRepository; + + @Autowired + private DiseaseLeprosyRepository diseaseLeprosyRepository; + + @Autowired + private LeprosyFollowUpRepository leprosyFollowUpRepository; + + @Autowired + private IncentiveRecordRepo recordRepo; + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private MosquitoNetRepository mosquitoNetRepository; + + + @Autowired + private ChronicDiseaseVisitRepository chronicDiseaseVisitRepository; + + @Autowired + private JwtUtil jwtUtil; + + + private final Logger logger = LoggerFactory.getLogger(CoupleController.class); + + @Override + public String saveMalaria(MalariaDTO diseaseControlDTO) { + for (DiseaseMalariaDTO diseaseControlData : diseaseControlDTO.getMalariaLists()) { + if (diseaseMalariaRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { + return updateMalariaDisease(diseaseControlData); + } else { + if (diseaseControlDTO.getUserId() != null) { + diseaseControlData.setUserId(diseaseControlDTO.getUserId()); + } + diseaseMalariaRepository.save(saveMalariaDisease(diseaseControlData)); + return "Data add successfully"; + + } + } + return "Fail"; + } + + + @Override + public String saveKalaAzar(KalaAzarDTO diseaseControlDTO) { + logger.info("Save request: "+diseaseControlDTO.toString()); + for (DiseaseKalaAzarDTO diseaseControlData : diseaseControlDTO.getKalaAzarLists()) { + if (diseaseKalaAzarRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { + return updateKalaAzarDisease(diseaseControlData); + } else { + if (diseaseControlDTO.getUserId() != null) { + diseaseControlData.setUserId(diseaseControlDTO.getUserId()); + } + diseaseKalaAzarRepository.save(saveKalaAzarDisease(diseaseControlData)); + return "Data add successfully"; + + } + } + return "Fail"; + + } + + + @Override + public String saveAES(AesJeDTO diseaseControlDTO) { + for (DiseaseAesjeDto diseaseControlData : diseaseControlDTO.getAesJeLists()) { + if (diseaseAESJERepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { + return updateASEDisease(diseaseControlData); + } else { + if (diseaseControlDTO.getUserId() != null) { + diseaseControlData.setUserId(diseaseControlDTO.getUserId()); + } + diseaseAESJERepository.save(saveASEDisease(diseaseControlData)); + return "Data add successfully"; + + } + } + return "Fail"; + } + + @Override + public String saveFilaria(FilariaDTO diseaseControlDTO) { + + for (DiseaseFilariasisDTO diseaseControlData : diseaseControlDTO.getFilariaLists()) { + if (diseaseFilariasisRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { + return updateFilaria(diseaseControlData); + } else { + if (diseaseControlDTO.getUserId() != null) { + diseaseControlData.setUserId(diseaseControlDTO.getUserId()); + } + diseaseFilariasisRepository.save(saveFilariasisData(diseaseControlData)); + return "Data add successfully"; + + } + } + return "Fail"; + } + + private ScreeningAesje saveASEDisease(DiseaseAesjeDto diseaseControlData) { + // Create a new DiseaseAesje entity from the DTO data + ScreeningAesje diseaseAesje = new ScreeningAesje(); + + // Set the fields from DTO to entity + diseaseAesje.setBenId(diseaseControlData.getBenId()); + diseaseAesje.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + diseaseAesje.setVisitDate(diseaseControlData.getVisitDate()); + diseaseAesje.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); + diseaseAesje.setDateOfDeath(diseaseControlData.getDateOfDeath()); + diseaseAesje.setPlaceOfDeath(diseaseControlData.getPlaceOfDeath()); + diseaseAesje.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + diseaseAesje.setOtherPlaceOfDeath(diseaseControlData.getOtherPlaceOfDeath()); + diseaseAesje.setReasonForDeath(diseaseControlData.getReasonForDeath()); + diseaseAesje.setOtherReasonForDeath(diseaseControlData.getOtherReasonForDeath()); + diseaseAesje.setAesJeCaseStatus(diseaseControlData.getAesJeCaseStatus()); + diseaseAesje.setAesJeCaseCount(diseaseControlData.getAesJeCaseCount()); + diseaseAesje.setFollowUpPoint(diseaseControlData.getFollowUpPoint()); + diseaseAesje.setReferredTo(diseaseControlData.getReferredTo()); + diseaseAesje.setOtherReferredFacility(diseaseControlData.getOtherReferredFacility()); + diseaseAesje.setCreatedDate(new Timestamp(System.currentTimeMillis())); // Set current timestamp + diseaseAesje.setCreatedBy(diseaseControlData.getCreatedBy()); + diseaseAesje.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); + diseaseAesje.setReferToName(diseaseControlData.getReferToName()); + diseaseAesje.setUserId(diseaseControlData.getUserId()); + + // Return the new entity to be saved + return diseaseAesje; + } + + private String updateASEDisease(DiseaseAesjeDto diseaseControlData) { + // Fetch the existing record from the database using benId + ScreeningAesje existingDiseaseAesje = diseaseAESJERepository.findByBenId(diseaseControlData.getBenId()) + .orElseThrow(() -> new RuntimeException("AES/JE record not found for benId: " + diseaseControlData.getBenId())); + + // Update the existing entity with new values from the DTO + existingDiseaseAesje.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + existingDiseaseAesje.setVisitDate(diseaseControlData.getVisitDate()); + existingDiseaseAesje.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); + existingDiseaseAesje.setDateOfDeath(diseaseControlData.getDateOfDeath()); + existingDiseaseAesje.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + existingDiseaseAesje.setPlaceOfDeath(diseaseControlData.getPlaceOfDeath()); + existingDiseaseAesje.setOtherPlaceOfDeath(diseaseControlData.getOtherPlaceOfDeath()); + existingDiseaseAesje.setReasonForDeath(diseaseControlData.getReasonForDeath()); + existingDiseaseAesje.setOtherReasonForDeath(diseaseControlData.getOtherReasonForDeath()); + existingDiseaseAesje.setAesJeCaseStatus(diseaseControlData.getAesJeCaseStatus()); + existingDiseaseAesje.setAesJeCaseCount(diseaseControlData.getAesJeCaseCount()); + existingDiseaseAesje.setFollowUpPoint(diseaseControlData.getFollowUpPoint()); + existingDiseaseAesje.setReferredTo(diseaseControlData.getReferredTo()); + existingDiseaseAesje.setOtherReferredFacility(diseaseControlData.getOtherReferredFacility()); + existingDiseaseAesje.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); + existingDiseaseAesje.setReferToName(diseaseControlData.getReferToName()); + + // If the userId is present, update it as well + + + // Save the updated entity + diseaseAESJERepository.save(existingDiseaseAesje); + + return "AES/JE data updated successfully"; + } + + + private ScreeningFilariasis saveFilariasisData(DiseaseFilariasisDTO diseaseControlData) { + // Create a new DiseaseFilariasis entity from the DTO data + ScreeningFilariasis diseaseFilariasis = new ScreeningFilariasis(); + + diseaseFilariasis.setBenId(diseaseControlData.getBenId()); + diseaseFilariasis.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + diseaseFilariasis.setSufferingFromFilariasis(diseaseControlData.getSufferingFromFilariasis()); + diseaseFilariasis.setAffectedBodyPart(diseaseControlData.getAffectedBodyPart()); + diseaseFilariasis.setMdaHomeVisitDate(diseaseControlData.getMdaHomeVisitDate()); + diseaseFilariasis.setDoseStatus(diseaseControlData.getDoseStatus()); + diseaseFilariasis.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + diseaseFilariasis.setFilariasisCaseCount(diseaseControlData.getFilariasisCaseCount()); + diseaseFilariasis.setOtherDoseStatusDetails(diseaseControlData.getOtherDoseStatusDetails()); + diseaseFilariasis.setMedicineSideEffect(diseaseControlData.getMedicineSideEffect()); + diseaseFilariasis.setOtherSideEffectDetails(diseaseControlData.getOtherSideEffectDetails()); + diseaseFilariasis.setCreatedDate(new Timestamp(System.currentTimeMillis())); // Set current timestamp + diseaseFilariasis.setCreatedBy(diseaseControlData.getCreatedBy()); + diseaseFilariasis.setUserId(diseaseControlData.getUserId()); + + // Return the new entity to be saved + return diseaseFilariasis; + } + + + private String updateFilaria(DiseaseFilariasisDTO diseaseControlData) { + // Fetch the existing record from the database using benId + ScreeningFilariasis existingDiseaseFilariasis = diseaseFilariasisRepository.findByBenId(diseaseControlData.getBenId()) + .orElseThrow(() -> new RuntimeException("Filariasis record not found for benId: " + diseaseControlData.getBenId())); + + // Update the existing entity with the new values from the DTO + existingDiseaseFilariasis.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + existingDiseaseFilariasis.setSufferingFromFilariasis(diseaseControlData.getSufferingFromFilariasis()); + existingDiseaseFilariasis.setAffectedBodyPart(diseaseControlData.getAffectedBodyPart()); + existingDiseaseFilariasis.setMdaHomeVisitDate(diseaseControlData.getMdaHomeVisitDate()); + existingDiseaseFilariasis.setDoseStatus(diseaseControlData.getDoseStatus()); + existingDiseaseFilariasis.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + existingDiseaseFilariasis.setFilariasisCaseCount(diseaseControlData.getFilariasisCaseCount()); + existingDiseaseFilariasis.setOtherDoseStatusDetails(diseaseControlData.getOtherDoseStatusDetails()); + existingDiseaseFilariasis.setMedicineSideEffect(diseaseControlData.getMedicineSideEffect()); + existingDiseaseFilariasis.setOtherSideEffectDetails(diseaseControlData.getOtherSideEffectDetails()); + + + // Save the updated entity + diseaseFilariasisRepository.save(existingDiseaseFilariasis); + + return "Filariasis data updated successfully"; + } + + + @Override + public String saveLeprosy(LeprosyDTO diseaseControlDTO) { + for (DiseaseLeprosyDTO diseaseControlData : diseaseControlDTO.getLeprosyLists()) { + if (diseaseLeprosyRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { + return updateLeprosyData(diseaseControlData); + } else { + if (diseaseControlDTO.getUserId() != null) { + diseaseControlData.setUserId(diseaseControlDTO.getUserId()); + } + diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); + return "Data add successfully"; + + } + } + return "Fail"; + } + + private LeprosyFollowUp saveLeprosyFollowUpData(LeprosyFollowUpDTO data) { + LeprosyFollowUp entity = new LeprosyFollowUp(); + + entity.setBenId(data.getBenId()); + entity.setVisitNumber(data.getVisitNumber()); + entity.setFollowUpDate(data.getFollowUpDate()); + entity.setTreatmentStatus(data.getTreatmentStatus()); + entity.setMdtBlisterPackReceived(data.getMdtBlisterPackReceived()); + entity.setTreatmentCompleteDate(data.getTreatmentCompleteDate()); + entity.setRemarks(data.getRemarks()); + entity.setHomeVisitDate(data.getHomeVisitDate()); + entity.setLeprosySymptoms(data.getLeprosySymptoms()); + entity.setTypeOfLeprosy(data.getTypeOfLeprosy()); + entity.setLeprosySymptomsPosition(data.getLeprosySymptomsPosition()); + entity.setVisitLabel(data.getVisitLabel()); + entity.setLeprosyStatus(data.getLeprosyStatus()); + entity.setReferredTo(data.getReferredTo()); + entity.setReferToName(data.getReferToName()); + entity.setTreatmentEndDate(data.getTreatmentEndDate()); + entity.setMdtBlisterPackRecived(data.getMdtBlisterPackRecived()); + entity.setTreatmentStartDate(data.getTreatmentStartDate()); + + // Audit fields + entity.setCreatedBy(data.getCreatedBy()); + entity.setCreatedDate( + data.getCreatedDate() != null ? data.getCreatedDate() : new Timestamp(System.currentTimeMillis())); + entity.setModifiedBy(data.getModifiedBy()); + entity.setLastModDate( + data.getLastModDate() != null ? data.getLastModDate() : new Timestamp(System.currentTimeMillis())); + + return entity; + } + + private String updateLeprosyFollowUpData(LeprosyFollowUpDTO data, LeprosyFollowUp entity) { + entity.setVisitNumber(data.getVisitNumber()); + entity.setFollowUpDate(data.getFollowUpDate()); + entity.setTreatmentStatus(data.getTreatmentStatus()); + entity.setMdtBlisterPackReceived(data.getMdtBlisterPackReceived()); + entity.setTreatmentCompleteDate(data.getTreatmentCompleteDate()); + entity.setRemarks(data.getRemarks()); + entity.setHomeVisitDate(data.getHomeVisitDate()); + entity.setLeprosySymptoms(data.getLeprosySymptoms()); + entity.setTypeOfLeprosy(data.getTypeOfLeprosy()); + entity.setLeprosySymptomsPosition(data.getLeprosySymptomsPosition()); + entity.setVisitLabel(data.getVisitLabel()); + entity.setLeprosyStatus(data.getLeprosyStatus()); + entity.setReferredTo(data.getReferredTo()); + entity.setReferToName(data.getReferToName()); + entity.setTreatmentEndDate(data.getTreatmentEndDate()); + entity.setMdtBlisterPackRecived(data.getMdtBlisterPackRecived()); + entity.setTreatmentStartDate(data.getTreatmentStartDate()); + + // Update audit info + entity.setModifiedBy(data.getModifiedBy()); + entity.setLastModDate( + data.getLastModDate() != null ? data.getLastModDate() : new Timestamp(System.currentTimeMillis())); + + leprosyFollowUpRepository.save(entity); + return "Follow-up data updated successfully"; + } + + @Override + public String saveLeprosyFollowUp(LeprosyFollowUpDTO dto) { + if (dto == null) + return "Invalid data"; + LeprosyFollowUp entity = saveLeprosyFollowUpData(dto); + leprosyFollowUpRepository.save(entity); + return "Follow-up data added successfully"; + + } + + @Override + public List getAllLeprosyData(String createdBy) { + logger.info("Fetching leprosy data for createdBy: " + createdBy); + + List leprosyList = diseaseLeprosyRepository.getByCreatedBy(createdBy); + logger.info("Found " + leprosyList.size() + " leprosy records"); + + List dtos = new ArrayList<>(); + leprosyList.forEach(leprosy -> { + dtos.add(modelMapper.map(leprosy, DiseaseGetLeprosyDTO.class)); + }); + + return dtos; + } + + @Override + public List getAllLeprosyFollowUpData(String createdBy) { + logger.info("Fetching leprosy data for createdBy: " + createdBy); + + List leprosyList = leprosyFollowUpRepository.getByCreatedBy(createdBy); + logger.info("Found " + leprosyList.size() + " leprosy records"); + + List dtos = new ArrayList<>(); + leprosyList.forEach(leprosy -> { + dtos.add(modelMapper.map(leprosy, LeprosyGetFollowUpDTO.class)); + }); + + return dtos; + } + + public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { + ObjectMapper objectMapper = new ObjectMapper(); + + // Fetch and filter malaria disease records + List filteredList = diseaseMalariaRepository.findAll().stream() + .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId())) + .collect(Collectors.toList()); + + // Check if the list is empty + if (filteredList.isEmpty()) { + return Collections.singletonMap("message", "No data found for Malaria."); + } + + // Map to DTOs + List dtoList = filteredList.stream().map(disease -> { + DiseaseMalariaDTO dto = new DiseaseMalariaDTO(); + + // Map fields from DiseaseMalaria to DTO + dto.setId(disease.getId()); + dto.setBenId(disease.getBenId()); + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + dto.setScreeningDate(disease.getScreeningDate()); + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + dto.setDateOfDeath(disease.getDateOfDeath()); + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + dto.setReasonForDeath(disease.getReasonForDeath()); + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + dto.setCaseStatus(disease.getCaseStatus()); + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + dto.setDateOfRdt(disease.getDateOfRdt()); + dto.setSlideTestPf(disease.getSlideTestPf()); + dto.setSlideTestPv(disease.getSlideTestPv()); + dto.setDateOfSlideTest(disease.getDateOfSlideTest()); + dto.setSlideNo(disease.getSlideNo()); + dto.setReferredTo(disease.getReferredTo()); + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + dto.setRemarks(disease.getRemarks()); + dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); + dto.setUserId(disease.getUserId()); + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + // Parse symptoms (if present) + try { + if (disease.getSymptoms() != null && !disease.getSymptoms().isEmpty()) { + MalariaSymptomsDTO symptomsDTO = objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + dto.setFeverMoreThanTwoWeeks(symptomsDTO.isFeverMoreThanTwoWeeks()); + dto.setFluLikeIllness(symptomsDTO.isFluLikeIllness()); + dto.setShakingChills(symptomsDTO.isShakingChills()); + dto.setHeadache(symptomsDTO.isHeadache()); + dto.setMuscleAches(symptomsDTO.isMuscleAches()); + dto.setTiredness(symptomsDTO.isTiredness()); + dto.setNausea(symptomsDTO.isNausea()); + dto.setVomiting(symptomsDTO.isVomiting()); + dto.setDiarrhea(symptomsDTO.isDiarrhea()); + } + } catch (Exception e) { + throw new RuntimeException("Error parsing symptoms JSON for Malaria Disease ID: " + disease.getId(), e); + } + + return dto; + }).collect(Collectors.toList()); + + return dtoList; + } + + @Override + public Object getAllScreeningData(GetDiseaseRequestHandler getDiseaseRequestHandler) { + + + if (getDiseaseRequestHandler.getDiseaseTypeID() == DiseaseType.MALARIA.getId()) { + return getAllMalaria(getDiseaseRequestHandler); + + } else if (getDiseaseRequestHandler.getDiseaseTypeID() == DiseaseType.KALA_AZAR.getId()) { + return getAllKalaAzar(getDiseaseRequestHandler); + + } else if (getDiseaseRequestHandler.getDiseaseTypeID() == DiseaseType.AES_JE.getId()) { + return getAllKalaAES(getDiseaseRequestHandler); + + } else if (getDiseaseRequestHandler.getDiseaseTypeID() == DiseaseType.FILARIA.getId()) { + return getAllFilaria(getDiseaseRequestHandler); + + } else if (getDiseaseRequestHandler.getDiseaseTypeID() == DiseaseType.LEPROSY.getId()) { + return getAllLeprosy(getDiseaseRequestHandler); + + } + return "No data found"; + } + + public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) { + + // Fetch and filter Kala Azar disease records + List filteredList = diseaseKalaAzarRepository.findAll().stream() + .filter(disease -> (Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId()))) + .collect(Collectors.toList()); + + // Check if the list is empty + if (filteredList.isEmpty()) { + return Collections.singletonMap("message", "No data found for Kala Azar."); + } + + // Map to DTOs + List dtoList = filteredList.stream().map(disease -> { + DiseaseKalaAzarDTO dto = new DiseaseKalaAzarDTO(); + dto.setId(disease.getId()); + dto.setBenId(disease.getBenId()); + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + dto.setVisitDate(disease.getVisitDate()); + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + dto.setDateOfDeath(disease.getDateOfDeath()); + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + dto.setReasonForDeath(disease.getReasonForDeath()); + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + dto.setKalaAzarCaseStatus(disease.getKalaAzarCaseStatus()); + dto.setKalaAzarCaseCount(disease.getKalaAzarCaseCount()); + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + dto.setDateOfRdt(disease.getDateOfRdt()); + dto.setFollowUpPoint(disease.getFollowUpPoint()); + dto.setReferredTo(disease.getReferredTo()); + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + dto.setCreatedDate(disease.getCreatedDate()); + dto.setCreatedBy(disease.getCreatedBy()); + dto.setBeneficiaryStatusId(disease.getBeneficiaryStatusId()); + dto.setReferToName(disease.getReferToName()); + dto.setUserId(disease.getUserId()); + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + return dto; + }).collect(Collectors.toList()); + + return dtoList; + } + + + public Object getAllKalaAES(GetDiseaseRequestHandler getDiseaseRequestHandler) { + if (diseaseAESJERepository.findAll().isEmpty()) { + return Collections.singletonMap("message", "No data found for AES."); + } + + return diseaseAESJERepository.findAll().stream().filter(diseaseAesje -> Objects.equals(diseaseAesje.getUserId(), getDiseaseRequestHandler.getAshaId())).collect(Collectors.toList()); + } + + + public Object getAllFilaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { + + // Fetch and filter Filaria disease records + List filteredList = diseaseFilariasisRepository.findAll().stream().filter(screeningFilariasis -> Objects.equals(screeningFilariasis.getUserId(), getDiseaseRequestHandler.getAshaId())).collect(Collectors.toList()); + + // Check if the list is empty + if (filteredList.isEmpty()) { + return Collections.singletonMap("message", "No data found for Filaria."); + } + + // Map to DTOs + List dtoList = filteredList.stream().map(disease -> { + DiseaseFilariasisDTO dto = new DiseaseFilariasisDTO(); + dto.setId(disease.getId()); + dto.setBenId(disease.getBenId()); + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + dto.setSufferingFromFilariasis(disease.getSufferingFromFilariasis()); + dto.setAffectedBodyPart(disease.getAffectedBodyPart()); + dto.setMdaHomeVisitDate(disease.getMdaHomeVisitDate()); + dto.setDoseStatus(disease.getDoseStatus()); + dto.setFilariasisCaseCount(disease.getFilariasisCaseCount()); + dto.setOtherDoseStatusDetails(disease.getOtherDoseStatusDetails()); + dto.setMedicineSideEffect(disease.getMedicineSideEffect()); + dto.setOtherSideEffectDetails(disease.getOtherSideEffectDetails()); + dto.setCreatedDate(disease.getCreatedDate()); + dto.setCreatedBy(disease.getCreatedBy()); + dto.setUserId(disease.getUserId()); + + return dto; + }).collect(Collectors.toList()); + + return dtoList; + } + + + public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { + + // Fetch and filter Leprosy disease records + List filteredList = diseaseLeprosyRepository.findAll().stream() + .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId())) + .collect(Collectors.toList()); + + // Check if the list is empty + if (filteredList.isEmpty()) { + return Collections.singletonMap("message", "No data found for Leprosy."); + } + + // Map to DTOs + List dtoList = filteredList.stream().map(disease -> { + DiseaseLeprosyDTO dto = new DiseaseLeprosyDTO(); + dto.setId(disease.getId()); + dto.setBenId(disease.getBenId()); + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + dto.setHomeVisitDate(disease.getHomeVisitDate()); + dto.setLeprosyStatus(disease.getLeprosyStatus()); + dto.setReferredTo(disease.getReferredTo()); + dto.setOtherReferredTo(disease.getOtherReferredTo()); + dto.setLeprosyStatusDate(disease.getLeprosyStatusDate()); + dto.setTypeOfLeprosy(disease.getTypeOfLeprosy()); + dto.setFollowUpDate(disease.getFollowUpDate()); + dto.setBeneficiaryStatus(disease.getLeprosyStatus()); + dto.setRemark(disease.getRemark()); + dto.setUserId(disease.getUserId()); + + + return dto; + }).collect(Collectors.toList()); + + return dtoList; + } + + + private ScreeningKalaAzar saveKalaAzarDisease(DiseaseKalaAzarDTO dto) { + logger.info("KalaAzarRequest: "+dto); + ScreeningKalaAzar entity = new ScreeningKalaAzar(); + + entity.setBenId(dto.getBenId()); + entity.setHouseHoldDetailsId(dto.getHouseHoldDetailsId()); + entity.setVisitDate(dto.getVisitDate()); + entity.setBeneficiaryStatus(dto.getBeneficiaryStatus()); + entity.setDateOfDeath(dto.getDateOfDeath()); + entity.setPlaceOfDeath(dto.getPlaceOfDeath()); + entity.setOtherPlaceOfDeath(dto.getOtherPlaceOfDeath()); + entity.setReasonForDeath(dto.getReasonForDeath()); + entity.setOtherReasonForDeath(dto.getOtherReasonForDeath()); + entity.setKalaAzarCaseStatus(dto.getKalaAzarCaseStatus()); + entity.setDiseaseTypeId(dto.getDiseaseTypeId()); + entity.setKalaAzarCaseCount(dto.getKalaAzarCaseCount()); + entity.setRapidDiagnosticTest(dto.getRapidDiagnosticTest()); + entity.setDateOfRdt(dto.getDateOfRdt()); + entity.setFollowUpPoint(dto.getFollowUpPoint()); + entity.setReferredTo(dto.getReferredTo()); + entity.setOtherReferredFacility(dto.getOtherReferredFacility()); + entity.setCreatedDate(new Timestamp(System.currentTimeMillis())); // or dto.getCreatedDate() + entity.setCreatedBy(dto.getCreatedBy()); + entity.setBeneficiaryStatusId(dto.getBeneficiaryStatusId()); + entity.setReferToName(dto.getReferToName()); + entity.setUserId(dto.getUserId()); + + + ScreeningKalaAzar saved = diseaseKalaAzarRepository.save(entity); + + return saved; // You can also return a custom response or DTO + } + + + private String updateKalaAzarDisease(DiseaseKalaAzarDTO dto) { + Optional optional = diseaseKalaAzarRepository.findByBenId(dto.getBenId()); + + if (!optional.isPresent()) { + return "Record not found with ID: " + dto.getId(); + } + + ScreeningKalaAzar entity = optional.get(); + + // Update fields + entity.setBenId(dto.getBenId()); + entity.setHouseHoldDetailsId(dto.getHouseHoldDetailsId()); + entity.setVisitDate(dto.getVisitDate()); + entity.setBeneficiaryStatus(dto.getBeneficiaryStatus()); + entity.setDateOfDeath(dto.getDateOfDeath()); + entity.setPlaceOfDeath(dto.getPlaceOfDeath()); + entity.setDiseaseTypeId(dto.getDiseaseTypeId()); + entity.setOtherPlaceOfDeath(dto.getOtherPlaceOfDeath()); + entity.setReasonForDeath(dto.getReasonForDeath()); + entity.setOtherReasonForDeath(dto.getOtherReasonForDeath()); + entity.setKalaAzarCaseStatus(dto.getKalaAzarCaseStatus()); + entity.setKalaAzarCaseCount(dto.getKalaAzarCaseCount()); + entity.setRapidDiagnosticTest(dto.getRapidDiagnosticTest()); + entity.setDateOfRdt(dto.getDateOfRdt()); + entity.setFollowUpPoint(dto.getFollowUpPoint()); + entity.setReferredTo(dto.getReferredTo()); + entity.setOtherReferredFacility(dto.getOtherReferredFacility()); + entity.setCreatedBy(dto.getCreatedBy()); + // You can also update createdDate if required + entity.setCreatedDate(new Timestamp(System.currentTimeMillis())); + entity.setReferToName(dto.getReferToName()); + entity.setBeneficiaryStatusId(dto.getBeneficiaryStatusId()); + entity.setUserId(dto.getUserId()); + + diseaseKalaAzarRepository.save(entity); + + return "Kala Azar record updated successfully!"; + } + + + private ScreeningLeprosy saveLeprosyData(DiseaseLeprosyDTO diseaseControlData) { + ScreeningLeprosy diseaseLeprosy = new ScreeningLeprosy(); + + // Setting the values from the DTO to the entity + diseaseLeprosy.setBenId(diseaseControlData.getBenId()); + diseaseLeprosy.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + diseaseLeprosy.setHomeVisitDate(diseaseControlData.getHomeVisitDate()); + diseaseLeprosy.setLeprosyStatus(diseaseControlData.getLeprosyStatus()); + diseaseLeprosy.setReferredTo(diseaseControlData.getReferredTo()); + diseaseLeprosy.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + diseaseLeprosy.setOtherReferredTo(diseaseControlData.getOtherReferredTo()); + diseaseLeprosy.setLeprosyStatusDate(diseaseControlData.getLeprosyStatusDate()); + diseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + diseaseLeprosy.setFollowUpDate(diseaseControlData.getFollowUpDate()); + diseaseLeprosy.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); + diseaseLeprosy.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); + diseaseLeprosy.setReferToName(diseaseControlData.getReferToName()); + diseaseLeprosy.setPlaceOfDeath(diseaseControlData.getPlaceOfDeath()); + diseaseLeprosy.setDateOfDeath(diseaseControlData.getDateOfDeath()); + diseaseLeprosy.setOtherPlaceOfDeath(diseaseControlData.getOtherPlaceOfDeath()); + diseaseLeprosy.setOtherReasonForDeath(diseaseControlData.getOtherReasonForDeath()); + diseaseLeprosy.setRemark(diseaseControlData.getRemark()); + diseaseLeprosy.setUserId(diseaseControlData.getUserId()); + + diseaseLeprosy.setLeprosySymptoms(diseaseControlData.getLeprosySymptoms()); + diseaseLeprosy.setLeprosySymptomsPosition(diseaseControlData.getLeprosySymptomsPosition()); + diseaseLeprosy.setLerosyStatusPosition(diseaseControlData.getLerosyStatusPosition()); + diseaseLeprosy.setCurrentVisitNumber(diseaseControlData.getCurrentVisitNumber()); + diseaseLeprosy.setVisitLabel(diseaseControlData.getVisitLabel()); + diseaseLeprosy.setVisitNumber(diseaseControlData.getVisitNumber()); + diseaseLeprosy.setIsConfirmed(diseaseControlData.getIsConfirmed()); + diseaseLeprosy.setLeprosyState(diseaseControlData.getLeprosyState()); + diseaseLeprosy.setTreatmentStartDate(diseaseControlData.getTreatmentStartDate()); + diseaseLeprosy.setTotalFollowUpMonthsRequired(diseaseControlData.getTotalFollowUpMonthsRequired()); + diseaseLeprosy.setTreatmentEndDate(diseaseControlData.getTreatmentEndDate()); + diseaseLeprosy.setMdtBlisterPackRecived(diseaseControlData.getMdtBlisterPackRecived()); + diseaseLeprosy.setTreatmentStatus(diseaseControlData.getTreatmentStatus()); + diseaseLeprosy.setCreatedBy(diseaseControlData.getCreatedBy()); + diseaseLeprosy.setCreatedDate(diseaseControlData.getCreatedDate()); + diseaseLeprosy.setModifiedBy(diseaseControlData.getModifiedBy()); + diseaseLeprosy.setLastModDate(diseaseControlData.getLastModDate()); + + diseaseLeprosy.setRecurrentUlcerationId(diseaseControlData.getRecurrentUlcerationId()); + diseaseLeprosy.setRecurrentTinglingId(diseaseControlData.getRecurrentTinglingId()); + diseaseLeprosy.setHypopigmentedPatchId(diseaseControlData.getHypopigmentedPatchId()); + diseaseLeprosy.setThickenedSkinId(diseaseControlData.getThickenedSkinId()); + diseaseLeprosy.setSkinNodulesId(diseaseControlData.getSkinNodulesId()); + diseaseLeprosy.setSkinPatchDiscolorationId(diseaseControlData.getSkinPatchDiscolorationId()); + diseaseLeprosy.setRecurrentNumbnessId(diseaseControlData.getRecurrentNumbnessId()); + diseaseLeprosy.setClawingFingersId(diseaseControlData.getClawingFingersId()); + diseaseLeprosy.setTinglingNumbnessExtremitiesId(diseaseControlData.getTinglingNumbnessExtremitiesId()); + diseaseLeprosy.setInabilityCloseEyelidId(diseaseControlData.getInabilityCloseEyelidId()); + diseaseLeprosy.setDifficultyHoldingObjectsId(diseaseControlData.getDifficultyHoldingObjectsId()); + diseaseLeprosy.setWeaknessFeetId(diseaseControlData.getWeaknessFeetId()); + + diseaseLeprosy.setRecurrentUlceration(diseaseControlData.getRecurrentUlceration()); + diseaseLeprosy.setRecurrentTingling(diseaseControlData.getRecurrentTingling()); + diseaseLeprosy.setHypopigmentedPatch(diseaseControlData.getHypopigmentedPatch()); + diseaseLeprosy.setThickenedSkin(diseaseControlData.getThickenedSkin()); + diseaseLeprosy.setSkinNodules(diseaseControlData.getSkinNodules()); + diseaseLeprosy.setSkinPatchDiscoloration(diseaseControlData.getSkinPatchDiscoloration()); + diseaseLeprosy.setRecurrentNumbness(diseaseControlData.getRecurrentNumbness()); + diseaseLeprosy.setClawingFingers(diseaseControlData.getClawingFingers()); + diseaseLeprosy.setTinglingNumbnessExtremities(diseaseControlData.getTinglingNumbnessExtremities()); + diseaseLeprosy.setInabilityCloseEyelid(diseaseControlData.getInabilityCloseEyelid()); + diseaseLeprosy.setDifficultyHoldingObjects(diseaseControlData.getDifficultyHoldingObjects()); + diseaseLeprosy.setWeaknessFeet(diseaseControlData.getWeaknessFeet()); + + + return diseaseLeprosy; + } + + private String updateLeprosyData(DiseaseLeprosyDTO diseaseControlData) { + // Fetch the existing record from the database using the benId + ScreeningLeprosy existingDiseaseLeprosy = diseaseLeprosyRepository.findByBenId(diseaseControlData.getBenId()) + .orElseThrow(() -> new RuntimeException("Leprosy record not found for benId: " + diseaseControlData.getBenId())); + + // Update the fields from the DTO to the existing entity + existingDiseaseLeprosy.setHouseHoldDetailsId(diseaseControlData.getHouseHoldDetailsId()); + existingDiseaseLeprosy.setHomeVisitDate(diseaseControlData.getHomeVisitDate()); + existingDiseaseLeprosy.setLeprosyStatus(diseaseControlData.getLeprosyStatus()); + existingDiseaseLeprosy.setReferredTo(diseaseControlData.getReferredTo()); + existingDiseaseLeprosy.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); + existingDiseaseLeprosy.setOtherReferredTo(diseaseControlData.getOtherReferredTo()); + existingDiseaseLeprosy.setLeprosyStatusDate(diseaseControlData.getLeprosyStatusDate()); + existingDiseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + existingDiseaseLeprosy.setFollowUpDate(diseaseControlData.getFollowUpDate()); + existingDiseaseLeprosy.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); + existingDiseaseLeprosy.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); + existingDiseaseLeprosy.setReferToName(diseaseControlData.getReferToName()); + existingDiseaseLeprosy.setPlaceOfDeath(diseaseControlData.getPlaceOfDeath()); + existingDiseaseLeprosy.setDateOfDeath(diseaseControlData.getDateOfDeath()); + existingDiseaseLeprosy.setOtherPlaceOfDeath(diseaseControlData.getOtherPlaceOfDeath()); + existingDiseaseLeprosy.setOtherReasonForDeath(diseaseControlData.getOtherReasonForDeath()); + existingDiseaseLeprosy.setRemark(diseaseControlData.getRemark()); + + existingDiseaseLeprosy.setLeprosySymptoms(diseaseControlData.getLeprosySymptoms()); + existingDiseaseLeprosy.setLeprosySymptomsPosition(diseaseControlData.getLeprosySymptomsPosition()); + existingDiseaseLeprosy.setLerosyStatusPosition(diseaseControlData.getLerosyStatusPosition()); + existingDiseaseLeprosy.setCurrentVisitNumber(diseaseControlData.getCurrentVisitNumber()); + existingDiseaseLeprosy.setVisitLabel(diseaseControlData.getVisitLabel()); + existingDiseaseLeprosy.setVisitNumber(diseaseControlData.getVisitNumber()); + existingDiseaseLeprosy.setIsConfirmed(diseaseControlData.getIsConfirmed()); + existingDiseaseLeprosy.setLeprosyState(diseaseControlData.getLeprosyState()); + existingDiseaseLeprosy.setTreatmentStartDate(diseaseControlData.getTreatmentStartDate()); + existingDiseaseLeprosy.setTotalFollowUpMonthsRequired(diseaseControlData.getTotalFollowUpMonthsRequired()); + existingDiseaseLeprosy.setTreatmentEndDate(diseaseControlData.getTreatmentEndDate()); + existingDiseaseLeprosy.setMdtBlisterPackRecived(diseaseControlData.getMdtBlisterPackRecived()); + existingDiseaseLeprosy.setTreatmentStatus(diseaseControlData.getTreatmentStatus()); + + existingDiseaseLeprosy.setModifiedBy(diseaseControlData.getModifiedBy()); + existingDiseaseLeprosy.setLastModDate(diseaseControlData.getLastModDate()); + + existingDiseaseLeprosy.setRecurrentUlcerationId(diseaseControlData.getRecurrentUlcerationId()); + existingDiseaseLeprosy.setRecurrentTinglingId(diseaseControlData.getRecurrentTinglingId()); + existingDiseaseLeprosy.setHypopigmentedPatchId(diseaseControlData.getHypopigmentedPatchId()); + existingDiseaseLeprosy.setThickenedSkinId(diseaseControlData.getThickenedSkinId()); + existingDiseaseLeprosy.setSkinNodulesId(diseaseControlData.getSkinNodulesId()); + existingDiseaseLeprosy.setSkinPatchDiscolorationId(diseaseControlData.getSkinPatchDiscolorationId()); + existingDiseaseLeprosy.setRecurrentNumbnessId(diseaseControlData.getRecurrentNumbnessId()); + existingDiseaseLeprosy.setClawingFingersId(diseaseControlData.getClawingFingersId()); + existingDiseaseLeprosy.setTinglingNumbnessExtremitiesId(diseaseControlData.getTinglingNumbnessExtremitiesId()); + existingDiseaseLeprosy.setInabilityCloseEyelidId(diseaseControlData.getInabilityCloseEyelidId()); + existingDiseaseLeprosy.setDifficultyHoldingObjectsId(diseaseControlData.getDifficultyHoldingObjectsId()); + existingDiseaseLeprosy.setWeaknessFeetId(diseaseControlData.getWeaknessFeetId()); + + existingDiseaseLeprosy.setRecurrentUlceration(diseaseControlData.getRecurrentUlceration()); + existingDiseaseLeprosy.setRecurrentTingling(diseaseControlData.getRecurrentTingling()); + existingDiseaseLeprosy.setHypopigmentedPatch(diseaseControlData.getHypopigmentedPatch()); + existingDiseaseLeprosy.setThickenedSkin(diseaseControlData.getThickenedSkin()); + existingDiseaseLeprosy.setSkinNodules(diseaseControlData.getSkinNodules()); + existingDiseaseLeprosy.setSkinPatchDiscoloration(diseaseControlData.getSkinPatchDiscoloration()); + existingDiseaseLeprosy.setRecurrentNumbness(diseaseControlData.getRecurrentNumbness()); + existingDiseaseLeprosy.setClawingFingers(diseaseControlData.getClawingFingers()); + existingDiseaseLeprosy.setTinglingNumbnessExtremities(diseaseControlData.getTinglingNumbnessExtremities()); + existingDiseaseLeprosy.setInabilityCloseEyelid(diseaseControlData.getInabilityCloseEyelid()); + existingDiseaseLeprosy.setDifficultyHoldingObjects(diseaseControlData.getDifficultyHoldingObjects()); + existingDiseaseLeprosy.setWeaknessFeet(diseaseControlData.getWeaknessFeet()); + + + diseaseLeprosyRepository.save(existingDiseaseLeprosy); + // Return the updated entity + return "Data update successfully"; + } + + // Save Malaria + private ScreeningMalaria saveMalariaDisease(DiseaseMalariaDTO requestData) { + ScreeningMalaria diseaseScreening = new ScreeningMalaria(); + + diseaseScreening.setBenId(requestData.getBenId()); + diseaseScreening.setHouseHoldDetailsId(requestData.getHouseHoldDetailsId()); + diseaseScreening.setScreeningDate(requestData.getScreeningDate()); + diseaseScreening.setBeneficiaryStatus(requestData.getBeneficiaryStatus()); + diseaseScreening.setDateOfDeath(requestData.getDateOfDeath()); + diseaseScreening.setPlaceOfDeath(requestData.getPlaceOfDeath()); + diseaseScreening.setOtherPlaceOfDeath(requestData.getOtherPlaceOfDeath()); + diseaseScreening.setReasonForDeath(requestData.getReasonForDeath()); + diseaseScreening.setOtherReasonForDeath(requestData.getOtherReasonForDeath()); + diseaseScreening.setDiseaseTypeId(requestData.getDiseaseTypeId()); + diseaseScreening.setSymptoms(convertSelecteddiseaseScreeningToJson(requestData)); // Convert specific fields to JSON + diseaseScreening.setUserId(requestData.getUserId()); + diseaseScreening.setCaseStatus(requestData.getCaseStatus()); + diseaseScreening.setRapidDiagnosticTest(requestData.getRapidDiagnosticTest()); + diseaseScreening.setDateOfRdt(requestData.getDateOfRdt()); + diseaseScreening.setSlideTestPf(requestData.getSlideTestPf()); + diseaseScreening.setSlideTestPv(requestData.getSlideTestPv()); + diseaseScreening.setDateOfSlideTest(requestData.getDateOfSlideTest()); + diseaseScreening.setSlideNo(requestData.getSlideNo()); + diseaseScreening.setReferredTo(requestData.getReferredTo()); + diseaseScreening.setOtherReferredFacility(requestData.getOtherReferredFacility()); + diseaseScreening.setRemarks(requestData.getRemarks()); + diseaseScreening.setDateOfVisitBySupervisor(requestData.getDateOfVisitBySupervisor()); + diseaseScreening.setCreatedDate(Timestamp.valueOf(LocalDateTime.now())); + checkAndAddIncentives(diseaseScreening); + + return diseaseMalariaRepository.save(diseaseScreening); + } + + // Update Malaria + private String updateMalariaDisease(DiseaseMalariaDTO requestData) { + return diseaseMalariaRepository.findByBenId(requestData.getBenId()).map(diseaseScreening -> { + diseaseScreening.setBenId(requestData.getBenId()); + diseaseScreening.setHouseHoldDetailsId(requestData.getHouseHoldDetailsId()); + diseaseScreening.setScreeningDate(requestData.getScreeningDate()); + diseaseScreening.setBeneficiaryStatus(requestData.getBeneficiaryStatus()); + diseaseScreening.setDateOfDeath(requestData.getDateOfDeath()); + diseaseScreening.setPlaceOfDeath(requestData.getPlaceOfDeath()); + diseaseScreening.setOtherPlaceOfDeath(requestData.getOtherPlaceOfDeath()); + diseaseScreening.setReasonForDeath(requestData.getReasonForDeath()); + diseaseScreening.setOtherReasonForDeath(requestData.getOtherReasonForDeath()); + diseaseScreening.setDiseaseTypeId(requestData.getDiseaseTypeId()); + diseaseScreening.setSymptoms(convertSelecteddiseaseScreeningToJson(requestData)); // Convert specific fields to JSON + diseaseScreening.setUserId(requestData.getUserId()); + diseaseScreening.setCaseStatus(requestData.getCaseStatus()); + diseaseScreening.setRapidDiagnosticTest(requestData.getRapidDiagnosticTest()); + diseaseScreening.setDateOfRdt(requestData.getDateOfRdt()); + diseaseScreening.setSlideTestPf(requestData.getSlideTestPf()); + diseaseScreening.setSlideTestPv(requestData.getSlideTestPv()); + diseaseScreening.setDateOfSlideTest(requestData.getDateOfSlideTest()); + diseaseScreening.setSlideNo(requestData.getSlideNo()); + diseaseScreening.setReferredTo(requestData.getReferredTo()); + diseaseScreening.setOtherReferredFacility(requestData.getOtherReferredFacility()); + diseaseScreening.setRemarks(requestData.getRemarks()); + diseaseScreening.setCreatedDate(Timestamp.valueOf(LocalDateTime.now())); + diseaseScreening.setDateOfVisitBySupervisor(requestData.getDateOfVisitBySupervisor()); + diseaseScreening.setReferToName(requestData.getReferToName()); + diseaseScreening.setCaseStatusId(requestData.getCaseStatusId()); + diseaseMalariaRepository.save(diseaseScreening); + return "Data update successfully"; + + }).orElseThrow(() -> new RuntimeException("Data not found")); + } + + + private String convertSelecteddiseaseScreeningToJson(DiseaseMalariaDTO requestData) { + try { + ObjectMapper objectMapper = new ObjectMapper(); + Map diseaseScreeningMap = new HashMap<>(); + diseaseScreeningMap.put("nausea", requestData.isNausea()); + diseaseScreeningMap.put("diarrhea", requestData.isDiarrhea()); + diseaseScreeningMap.put("tiredness", requestData.isTiredness()); + diseaseScreeningMap.put("vomiting", requestData.isVomiting()); + diseaseScreeningMap.put("headache", requestData.isHeadache()); + diseaseScreeningMap.put("feverMoreThanTwoWeeks", requestData.isFeverMoreThanTwoWeeks()); + diseaseScreeningMap.put("fluLikeIllness", requestData.isFluLikeIllness()); + diseaseScreeningMap.put("shakingChills", requestData.isShakingChills()); + + return objectMapper.writeValueAsString(diseaseScreeningMap); + } catch (Exception e) { + throw new RuntimeException("Error converting selected diseaseScreening fields to JSON", e); + } + } + + @Override + public List saveMosquitoMobilizationNet(List mosquitoNetDTOList) { + + // DTO → Entity + List entityList = mosquitoNetDTOList.stream().map(dto -> { + + MosquitoNetEntity entity = new MosquitoNetEntity(); + + entity.setBeneficiaryId(dto.getBeneficiaryId()); + entity.setHouseHoldId(dto.getHouseHoldId()); + + // ✅ String → LocalDate conversion + if (dto.getVisitDate() != null && !dto.getVisitDate().isEmpty()) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + entity.setVisitDate(LocalDate.parse(dto.getVisitDate(), formatter)); + } + + + entity.setUserName(dto.getUserName()); + entity.setUserId(userRepo.getUserIdByName(dto.getUserName())); + + // ✅ Safe null handling for fields + if (dto.getFields() != null) { + entity.setIsNetDistributed(dto.getFields().getIs_net_distributed()); + } else { + entity.setIsNetDistributed(null); + } + + return entity; + + }).collect(Collectors.toList()); + + + + // ✅ Save all + List savedEntities = mosquitoNetRepository.saveAll(entityList); + + + + // ✅ Entity → DTO return + return savedEntities.stream().map(entity -> { + + MosquitoNetDTO dto = new MosquitoNetDTO(); + + dto.setBeneficiaryId(entity.getBeneficiaryId()); + dto.setHouseHoldId(entity.getHouseHoldId()); + + // ✅ LocalDate → String (to avoid type mismatch) + + if (entity.getVisitDate() != null) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + dto.setVisitDate(entity.getVisitDate().format(formatter)); + } + dto.setUserName(entity.getUserName()); + + // ✅ Return is_net_distributed inside dto.fields (if needed) + if (dto.getFields() != null) { + dto.getFields().setIs_net_distributed(entity.getIsNetDistributed()); + } + + return dto; + + }).collect(Collectors.toList()); + } + + @Override + public List getAllMosquitoMobilizationNet(Integer userId) { + + List entityList = mosquitoNetRepository.findByUserId(userId); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + return entityList.stream().map(entity -> { + MosquitoNetDTO dto = new MosquitoNetDTO(); + dto.setId(entity.getId()); + dto.setBeneficiaryId(entity.getBeneficiaryId()); + dto.setHouseHoldId(entity.getHouseHoldId()); + + if (entity.getVisitDate() != null) { + dto.setVisitDate(entity.getVisitDate().format(formatter)); + } + + dto.setUserName(entity.getUserName()); + MosquitoNetListDTO mosquitoNetListDTO = new MosquitoNetListDTO(); + mosquitoNetListDTO.setIs_net_distributed(entity.getIsNetDistributed()); + mosquitoNetListDTO.setVisit_date(entity.getVisitDate().format(formatter)); + + dto.setFields(mosquitoNetListDTO); + + return dto; + }).collect(Collectors.toList()); + } + + + + + private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { + IncentiveActivity diseaseScreeningActivity; + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed Case")) { + diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MALARIA_1", "DISEASECONTROL"); + + } else { + diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MALARIA_2", "DISEASECONTROL"); + + } + + + if (diseaseScreeningActivity != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); + if (record == null) { + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed Case")) { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setCreatedBy(diseaseScreening.getCreatedBy()); + record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedBy(diseaseScreening.getCreatedBy()); + record.setBenId(diseaseScreening.getBenId().longValue()); + record.setAshaId(diseaseScreening.getUserId()); + record.setName(diseaseScreeningActivity.getName()); + record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + recordRepo.save(record); + } else { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setCreatedBy(diseaseScreening.getCreatedBy()); + record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedBy(diseaseScreening.getCreatedBy()); + record.setBenId(diseaseScreening.getBenId().longValue()); + record.setName(diseaseScreeningActivity.getName()); + record.setAshaId(diseaseScreening.getUserId()); + record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + recordRepo.save(record); + } + + } + } + } + + + + @Override + public List saveChronicDiseaseVisit( + List requestList,String token) throws IEMRException { + + List responseList = new ArrayList<>(); + + for (ChronicDiseaseVisitDTO dto : requestList) { + + ChronicDiseaseVisitEntity entity = new ChronicDiseaseVisitEntity(); + + entity.setBenId(dto.getBenId()); + entity.setHhId(dto.getHhId()); + entity.setFormId(dto.getFormId()); + entity.setVersion(dto.getVersion()); + entity.setVisitNo(dto.getVisitNo()); + entity.setFollowUpNo(dto.getFollowUpNo()); + if(dto.getFollowUpDate()!=null){ + entity.setFollowUpDate(dto.getFollowUpDate()); + + } + entity.setDiagnosisCodes(dto.getDiagnosisCodes()); + entity.setFormDataJson(dto.getFormDataJson()); + entity.setUserID(jwtUtil.extractUserId(token)); + entity.setCreatedBy(jwtUtil.extractUsername(token)); + entity.setUpdatedBy(jwtUtil.extractUserId(token)); + + + if (dto.getTreatmentStartDate() != null) { + entity.setTreatmentStartDate( + LocalDate.parse(dto.getTreatmentStartDate()) + ); + } + + ChronicDiseaseVisitEntity savedEntity = + chronicDiseaseVisitRepository.save(entity); + + dto.setId(savedEntity.getId()); + responseList.add(dto); + checkIncentive(savedEntity,savedEntity.getUserID()); + + + } + + return responseList; + } + private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity,Integer ashaId){ + String userName = userRepo.getUserNamedByUserId(ashaId); + IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); + logger.info("incentiveActivity:"+ incentiveActivity.getId()); + if(incentiveActivity!=null){ + if (chronicDiseaseVisitEntity.getFollowUpNo() != null + && chronicDiseaseVisitEntity.getCreatedDate() != null + && chronicDiseaseVisitEntity.getDiagnosisCodes() != null) { + + List targetDiseases = Arrays.asList( + "Hypertension (BP)", + "Diabetes (DM)", + "Cancer" + ); + + List diagnosisList = Arrays.asList( + chronicDiseaseVisitEntity.getDiagnosisCodes().split(",") + ); + + boolean matchFound = diagnosisList.stream() + .map(String::trim) + .anyMatch(targetDiseases::contains); + + if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { + LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); + + Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); + + addNCDFolloupIncentiveRecord( + incentiveActivity, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } + } + } + + + + } + + private void addNCDFolloupIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId, + Long benId, Timestamp createdDate, String userName) { + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), createdDate, benId); + + Timestamp now = Timestamp.valueOf(LocalDateTime.now()); + if(record==null){ + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(createdDate); + record.setCreatedBy(userName); + record.setStartDate(createdDate); + record.setEndDate(createdDate); + record.setUpdatedDate(now); + record.setUpdatedBy(userName); + record.setBenId(benId); + record.setAshaId(ashaId); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + record .setIsEligible(true); + recordRepo.save(record); + } + }catch (Exception e){ + logger.error("Fail to save IncentiveActivityRecord " + e.getMessage()); + } + + + } + @Override + public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { + List dtoList = new ArrayList<>(); + + try { + + List entityList = chronicDiseaseVisitRepository.findByUserID(getBenRequestHandler.getAshaId()); + + + for (ChronicDiseaseVisitEntity entity : entityList) { + + ChronicDiseaseVisitDTO dto = new ChronicDiseaseVisitDTO(); + + dto.setId(entity.getId()); + dto.setBenId(entity.getBenId()); + dto.setHhId(entity.getHhId()); + dto.setFormId(entity.getFormId()); + dto.setVersion(entity.getVersion()); + dto.setVisitNo(entity.getVisitNo()); + dto.setFollowUpNo(entity.getFollowUpNo()); + if(entity.getFollowUpDate()!=null){ + dto.setFollowUpDate(entity.getFollowUpDate()); + + } + dto.setDiagnosisCodes(entity.getDiagnosisCodes()); + dto.setFormDataJson(entity.getFormDataJson()); + + if (entity.getTreatmentStartDate() != null) { + dto.setTreatmentStartDate( + entity.getTreatmentStartDate().toString() + ); + } + checkIncentive(entity,entity.getUserID()); + dtoList.add(dto); + } + }catch (Exception e){ + + } + + return dtoList; + } + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java b/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java new file mode 100644 index 00000000..2f67fc2b --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java @@ -0,0 +1,39 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.repo.iemr.EmployeeMasterRepo; +import com.iemr.flw.service.EmployeeMasterInter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class EmployeeMasterImpl implements EmployeeMasterInter { + @Autowired + EmployeeMasterRepo employeeMasterRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + + @Override + public M_User getUserDetails(Integer userID) { + logger.debug("Fetching user details for userID: {}", userID); + try { + if (userID == null) { + throw new IllegalArgumentException("UserID cannot be null"); + } + return employeeMasterRepo.findByUserID(userID); + } catch (Exception e) { + logger.error("Error fetching user details for userID: {}", userID, e); + throw e; + } + } + + @Override + public List getAllUsers() { + return employeeMasterRepo.findAll(); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/GeneralOpdServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/GeneralOpdServiceImpl.java new file mode 100644 index 00000000..898aa9c6 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/GeneralOpdServiceImpl.java @@ -0,0 +1,94 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* @@ -0,0 +1,212 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.identity.*; +import com.iemr.flw.domain.iemr.GeneralOpdData; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.BenReferDetailsRepo; +import com.iemr.flw.repo.iemr.GeneralOpdRepo; +import com.iemr.flw.service.GeneralOpdService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class GeneralOpdServiceImpl implements GeneralOpdService { + + private final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); + @Value("${door-to-door-page-size}") + private String door_to_door_page_size; + @Autowired + private BeneficiaryRepo beneficiaryRepo; + + @Autowired + private GeneralOpdRepo generalOpdRepo; + + @Autowired + private BenReferDetailsRepo benReferDetailsRepo; + + + + @Override + public Page getOutreachData(Integer villageId,String userName) { + int page = 0; // always start from 0 + int pageSize = 20; + Page result; + + do { + Pageable pageable = PageRequest.of(page, pageSize); + result = generalOpdRepo.findFilteredOutreachData(villageId, pageable,userName); + result.forEach(generalOpdData->{ + if(benReferDetailsRepo.findInstituteNameByBeneficiaryRegID(generalOpdData.getBeneficiaryRegID())!=null){ + generalOpdData.setVisitCategory(benReferDetailsRepo.findInstituteNameByBeneficiaryRegID(generalOpdData.getBeneficiaryRegID())); + + }else { + generalOpdData.setVisitCategory(""); + + } + if(benReferDetailsRepo.findReasonByBeneficiaryRegID(generalOpdData.getBeneficiaryRegID())!=null){ + generalOpdData.setVisitReason(benReferDetailsRepo.findReasonByBeneficiaryRegID(generalOpdData.getBeneficiaryRegID())); + + }else { + generalOpdData.setVisitReason(""); + + } + }); + + page++; + } while (result.isEmpty() && page < 50); // 50 = safety limit to avoid infinite loop + + return result; + } + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java new file mode 100644 index 00000000..e4771229 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -0,0 +1,142 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.IFAFormSubmissionData; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.IFAFormFieldsDTO; +import com.iemr.flw.dto.iemr.IFAFormSubmissionRequest; +import com.iemr.flw.dto.iemr.IFAFormSubmissionResponse; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.IFAFormSubmissionRepository; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.service.IFAFormSubmissionService; +import com.iemr.flw.utils.JwtUtil; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.*; +import java.time.format.DateTimeFormatter; + +@Service +@RequiredArgsConstructor +public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { + @Autowired + private final IFAFormSubmissionRepository repository; + private final ObjectMapper mapper = new ObjectMapper(); + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + @Override + public String saveFormData(List requests) { + try { + List entities = new ArrayList<>(); + for (IFAFormSubmissionRequest req : requests) { + IFAFormSubmissionData data = IFAFormSubmissionData.builder() + .userId(userServiceRoleRepo.getUserIdByName(req.getUserName())) + .beneficiaryId(req.getBeneficiaryId()) + .formId(req.getFormId()) + .houseHoldId(req.getHouseHoldId()) + .userName(req.getUserName()) + .visitDate(req.getVisitDate()) + .ifaProvided(req.getFields().getIfa_provided()) + .ifaQuantity(req.getFields().getIfa_quantity().toString()) + .build(); + entities.add(data); + } + repository.saveAll(entities); + checkIFAIncentive(entities); + return "Form data saved successfully"; + } catch (Exception e) { + e.printStackTrace(); + return "Error while saving form data: " + e.getMessage(); + } + } + + private void checkIFAIncentive(List entities) { + IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); + + if(incentiveActivityAM!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); + + }); + } + + } + + private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + LocalDate ifaVisitDate = LocalDate.parse(ifaFormSubmissionData.getVisitDate(), formatter); + + Timestamp ifaVisitDateTimestamp = Timestamp.valueOf(ifaVisitDate.atStartOfDay()); + + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); + if(incentiveActivityRecord==null){ + incentiveActivityRecord = new IncentiveActivityRecord(); + incentiveActivityRecord.setActivityId(ifaFormSubmissionData.getId()); + incentiveActivityRecord.setCreatedDate(ifaVisitDateTimestamp); + incentiveActivityRecord.setStartDate(ifaVisitDateTimestamp); + incentiveActivityRecord.setEndDate(ifaVisitDateTimestamp); + incentiveActivityRecord.setUpdatedDate(ifaVisitDateTimestamp); + incentiveActivityRecord.setUpdatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setCreatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setBenId(ifaFormSubmissionData.getBeneficiaryId()); + incentiveActivityRecord.setAshaId(userServiceRoleRepo.getUserIdByName(ifaFormSubmissionData.getUserName())); + incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + incentiveRecordRepo.save(incentiveActivityRecord); + } + } + + + @Override + public List getFormData(GetBenRequestHandler getBenRequestHandler) { + List records = repository.findByUserId(getBenRequestHandler.getAshaId()); + List responses = new ArrayList<>(); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + for (IFAFormSubmissionData entity : records) { + try { + // Map domain entity to response DTO + IFAFormFieldsDTO fieldsDTO = IFAFormFieldsDTO.builder() + .visit_date(entity.getVisitDate()) + .ifa_provided(entity.getIfaProvided()) + .ifa_quantity(Double.parseDouble(entity.getIfaQuantity())) + .build(); + + responses.add(IFAFormSubmissionResponse.builder() + .formId(entity.getFormId()) + .houseHoldId(entity.getHouseHoldId()) + .beneficiaryId(entity.getBeneficiaryId()) + .visitDate(entity.getVisitDate()) + .createdBy(entity.getUserName()) + .createdAt(entity.getCreatedAt() != null ? entity.getCreatedAt().format(formatter) : null) + .fields(fieldsDTO) + .build()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + return responses; + } + + +} diff --git a/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java new file mode 100644 index 00000000..26a5c1c7 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java @@ -0,0 +1,38 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.IRSRound; +import com.iemr.flw.dto.iemr.IRSRoundDTO; +import com.iemr.flw.repo.iemr.IRSRoundRepo; +import com.iemr.flw.service.IRSRoundService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class IRSRoundServiceImpl implements IRSRoundService { + @Autowired + private IRSRoundRepo irsRoundRepository; + + @Override + public List addRounds(List dtos,Integer userId,String userName) { + // Validate input DTOs + for (IRSRoundDTO dto : dtos) { + if (dto.getDate() == null || dto.getHouseholdId() == null) { + throw new IllegalArgumentException("Date and household ID are required"); + } + } + return irsRoundRepository.saveAll( + dtos.stream() + .map(dto -> new IRSRound(null, dto.getDate(), dto.getRounds(), dto.getHouseholdId(),userName,userId)) + .collect(Collectors.toList()) + ); + } + + @Override + public List getRounds(Long householdId) { + return irsRoundRepository.findByHouseholdId(householdId); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java index e031ef7c..09523a4b 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -2,33 +2,68 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.iemr.flw.domain.iemr.IncentiveActivity; -import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; +import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; -import com.iemr.flw.repo.iemr.IncentiveRecordRepo; -import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.StateCode; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveService; +import com.iemr.flw.service.MaaMeetingService; +import com.iemr.flw.utils.JwtUtil; import org.modelmapper.ModelMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; -import java.util.ArrayList; -import java.util.List; +import java.math.BigInteger; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; import java.util.stream.Collectors; @Service public class IncentiveServiceImpl implements IncentiveService { + private final Logger logger = LoggerFactory.getLogger(ChildCareServiceImpl.class); - + @Autowired + private BeneficiaryRepo beneficiaryRepo; ModelMapper modelMapper = new ModelMapper(); + @Autowired + private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; + @Autowired IncentivesRepo incentivesRepo; @Autowired IncentiveRecordRepo recordRepo; + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private MaaMeetingService maaMeetingService; + + @Autowired + private BenReferDetailsRepo benReferDetailsRepo; + + @Autowired + private CbacIemrDetailsRepo cbacIemrDetailsRepo; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -48,35 +83,348 @@ public String saveIncentivesMaster(List activityDTOS) { }); String saved = ""; activityDTOS.forEach(dto -> saved.concat(dto.getGroup() + ": " + dto.getName())); - return "saved master data for " + saved ; + return "saved master data for " + saved; } catch (Exception e) { - + } return null; } @Override public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { - try { - List incs = incentivesRepo.findAll(); + Integer stateCode = incentiveRequestDTO.getState(); + String langCode = incentiveRequestDTO.getLangCode(); + + // Integer comparison using intValue() — safe and reliable + boolean isCG = stateCode != null && stateCode.intValue() == StateCode.CG.getStateCode(); + boolean isAM = stateCode != null && stateCode.intValue() == StateCode.AM.getStateCode(); + + // Single filtered DB query instead of findAll() + stream filter + List incs = isCG + ? incentivesRepo.findByGroupAndIsDeleted("ACTIVITY", false) + : incentivesRepo.findByGroupNotAndIsDeleted("ACTIVITY", false); + + if (incs.isEmpty()) { + return new Gson().toJson(Collections.emptyList()); + } + + // Fetch ALL lang mappings in ONE query instead of N queries in loop + List ids = incs.stream() + .map(IncentiveActivity::getId) + .collect(Collectors.toList()); + + Map mappingById = incentiveActivityLangMappingRepo + .findAllByIdIn(ids) + .stream() + .collect(Collectors.toMap( + IncentiveActivityLangMapping::getId, + Function.identity() + )); + + List dtos = incs.stream().map(inc -> { + IncentiveActivityDTO dto = modelMapper.map(inc, IncentiveActivityDTO.class); + IncentiveActivityLangMapping mapping = mappingById.get(inc.getId()); + + if (mapping != null) { + dto.setName(mapping.getName()); + + if (isCG) { + dto.setGroupName(""); + } else if (isAM) { + dto.setGroupName(mapping.getGroup()); + } + + // Set description based on language + if ("as".equals(langCode)) { + dto.setDescription(mapping.getAssameActivityDescription() != null + ? mapping.getAssameActivityDescription() + : mapping.getDescription()); + + } else if ("hi".equals(langCode)) { + dto.setDescription(mapping.getHindiActivityDescription() != null + ? mapping.getHindiActivityDescription() + : mapping.getDescription()); + + } else { + // default "en" + dto.setDescription(inc.getDescription()); + } + + } else { + dto.setGroupName(inc.getGroup()); + } + + return dto; + }).collect(Collectors.toList()); - List dtos = - incs.stream().map(inc -> modelMapper.map(inc, IncentiveActivityDTO.class)).collect(Collectors.toList()); Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); return gson.toJson(dtos); - } catch (Exception e) { + } catch (Exception e) { + logger.error("Error in getIncentiveMaster: ", e); } return null; } @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { - List dtos = new ArrayList<>(); - List entities = recordRepo.findRecordsByAsha(request.getAshaId(), request.getFromDate(), request.getToDate()); - entities.forEach(entry -> dtos.add(modelMapper.map(entry, IncentiveRecordDTO.class))); + try { + if (request.getVillageID() != StateCode.CG.getStateCode()) { + checkMonthlyAshaIncentive(request.getAshaId()); + } + } catch (Exception e) { + logger.error("Error in checkMonthlyAshaIncentive: ", e); + } + + try { + + incentiveOfNcdReferal(request.getAshaId(), request.getVillageID()); + + } catch (Exception e) { + logger.error("Error in incentiveOfNcdReferal: ", e); + } + + Integer villageID = request.getVillageID(); + boolean isCG = villageID != null && villageID.intValue() == StateCode.CG.getStateCode(); + + if (!isCG) { + checkMonthlyAshaIncentive(request.getAshaId()); + } + + // Step 1: Fetch all records for this ASHA + List entities = recordRepo.findRecordsByAsha(request.getAshaId()); + + if (entities.isEmpty()) { + return new Gson().toJson(Collections.emptyList()); + } + + // Step 2: Collect all activityIds — fetch valid ones in ONE query + List activityIds = entities.stream() + .map(IncentiveActivityRecord::getActivityId) + .distinct() + .collect(Collectors.toList()); + + // Single bulk query instead of N individual findIncentiveMasterById() calls + Set validActivityIds = isCG + ? incentivesRepo.findValidActivityIds(activityIds, true) + : incentivesRepo.findValidActivityIds(activityIds, false); + + // Filter entities based on valid activity IDs + entities = entities.stream() + .filter(e -> validActivityIds.contains(e.getActivityId())) + .collect(Collectors.toList()); + + // Step 3: Collect all benIds that need name lookup (name == null and benId > 0) + List benIdsToFetch = entities.stream() + .filter(e -> e.getName() == null && e.getBenId() != null && e.getBenId() > 0) + .map(IncentiveActivityRecord::getBenId) + .distinct() + .collect(Collectors.toList()); + + // Step 4: Bulk fetch all beneficiary names in ONE query instead of 3 queries per record + Map benIdToNameMap = new HashMap<>(); + if (!benIdsToFetch.isEmpty()) { + List benDetails = beneficiaryRepo.findBenNamesByBenIds(benIdsToFetch); + for (Object[] row : benDetails) { + Long benId = ((Number) row[0]).longValue(); + String first = row[1] != null ? (String) row[1] : ""; + String last = row[2] != null ? (String) row[2] : ""; + benIdToNameMap.put(benId, (first + " " + last).trim()); + } + } + + // Step 5: Map entities to DTOs + List dtos = entities.stream().map(entry -> { + if (entry.getName() == null) { + if (entry.getBenId() != null && entry.getBenId() > 0) { + String name = benIdToNameMap.getOrDefault(entry.getBenId(), ""); + entry.setName(name); + if (isCG) { + entry.setIsEligible(true); + } + } else { + entry.setName(""); + } + } + return modelMapper.map(entry, IncentiveRecordDTO.class); + }).collect(Collectors.toList()); + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); return gson.toJson(dtos); } + + + @Override + public String updateIncentive(PendingActivityDTO pendingActivityDTO) { + Optional incentivePendingActivity = incentivePendingActivityRepository.findByUserIdAndModuleNameAndActivityId(pendingActivityDTO.getUserId(), pendingActivityDTO.getModuleName(), pendingActivityDTO.getId()); + + if (incentivePendingActivity.isPresent()) { + IncentivePendingActivity existingIncentivePendingActivity = incentivePendingActivity.get(); + if (existingIncentivePendingActivity.getModuleName().equals("MAA_MEETING")) { + if (pendingActivityDTO.getImages() != null) { + try { + MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); + maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); + maaMeetingService.updateMeeting(maaMeetingRequestDTO); + + } catch (Exception e) { + return e.getMessage(); + } + + } + } + } + return null; + + } + + private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { + try { + String userName = userRepo.getUserNamedByUserId(ashaId); + String groupName = resolveGroupName(stateId); + + Map activityMap = + incentivesRepo.findIncentiveMasterByNameAndGroup( + List.of("NCD_POP_ENUMERATION", "NCD_FOLLOWUP_TREATMENT"), groupName + ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); + + IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); + + CompletableFuture> benReferFuture = + CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); + CompletableFuture> cbacFuture = + CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); + + List cbacDetailsImer = cbacFuture.get(); + + List recordsToSave = new ArrayList<>(); + + + + if (ncdPopEnumeration != null && !cbacDetailsImer.isEmpty()) { + List cbacBenIds = cbacDetailsImer.stream() + .filter(c -> c != null && c.getBeneficiaryRegId() != null) + .map(CbacDetailsImer::getBeneficiaryRegId) + .collect(Collectors.toList()); + + // Batch fetch existing records — 1 query instead of N + Set existingKeys = recordRepo + .findExistingRecords(ncdPopEnumeration.getId(), cbacBenIds, ashaId) + .stream() + .map(r -> r.getActivityId() + "_" + r.getBenId() + "_" + r.getCreatedDate()) + .collect(Collectors.toSet()); + + final IncentiveActivity activity = ncdPopEnumeration; + cbacDetailsImer.stream() + .filter(c -> c != null && c.getBeneficiaryRegId() != null) + .forEach(c -> { + String key = activity.getId() + "_" + c.getBeneficiaryRegId() + "_" + c.getCreatedDate(); + if (!existingKeys.contains(key)) { + recordsToSave.add(addNCDandCBACIncentiveRecord(activity, ashaId, c.getBeneficiaryRegId(), c.getCreatedDate(), userName)); + } + }); + } + + // ---- Single batch insert instead of N individual saves ---- + if (!recordsToSave.isEmpty()) { + recordRepo.saveAll(recordsToSave); + } + + } catch (Exception e) { + logger.error("Error in incentiveOfNcdReferal for ashaId={}, stateId={}", ashaId, stateId, e); + } + } + + // Helper — record banana + private IncentiveActivityRecord addNCDandCBACIncentiveRecord(IncentiveActivity activity, Integer ashaId, + Long benId, Timestamp createdDate, String userName) { + Timestamp now = Timestamp.valueOf(LocalDateTime.now()); + IncentiveActivityRecord record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(createdDate); + record.setCreatedBy(userName); + record.setStartDate(createdDate); + record.setEndDate(createdDate); + record.setUpdatedDate(now); + record.setUpdatedBy(userName); + record.setBenId(benId); + record.setAshaId(ashaId); + record.setAmount(Long.valueOf(activity.getRate())); + return record; + } + + private String resolveGroupName(Integer stateId) { + if (stateId.equals(StateCode.CG.getStateCode())) { + logger.info("State id: {}", StateCode.CG.getStateCode()); + return GroupName.ACTIVITY.getDisplayName(); + } + logger.info("State id: {}", stateId); + return GroupName.NCD.getDisplayName(); + } + + private void checkMonthlyAshaIncentive(Integer ashaId) { + try { + String userName = userRepo.getUserNamedByUserId(ashaId); + + IncentiveActivity MOBILEBILLREIMB_ACTIVITY = incentivesRepo.findIncentiveMasterByNameAndGroup("MOBILE_BILL_REIMB", GroupName.OTHER_INCENTIVES.getDisplayName()); + IncentiveActivity ADDITIONAL_ASHA_INCENTIVE = incentivesRepo.findIncentiveMasterByNameAndGroup("ADDITIONAL_ASHA_INCENTIVE", GroupName.ADDITIONAL_INCENTIVE.getDisplayName()); + IncentiveActivity ASHA_MONTHLY_ROUTINE = incentivesRepo.findIncentiveMasterByNameAndGroup("ASHA_MONTHLY_ROUTINE", GroupName.ASHA_MONTHLY_ROUTINE.getDisplayName()); + if (MOBILEBILLREIMB_ACTIVITY != null) { + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId,userName); + } + if (ADDITIONAL_ASHA_INCENTIVE != null) { + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId,userName); + + } + + if (ASHA_MONTHLY_ROUTINE != null) { + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId,userName); + + } + } catch (Exception e) { + logger.error("Error in addMonthlyAshaIncentiveRecord", e); + + } + + } + + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId,String userName) { + try { + Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); + + Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); + Timestamp endOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).atTime(23, 59, 59)); + + IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivity.getId(), + startOfMonth, + endOfMonth, + 0L, + ashaId + ); + + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(timestamp); + record.setCreatedBy(userName); + record.setStartDate(timestamp); + record.setEndDate(timestamp); + record.setUpdatedDate(timestamp); + record.setUpdatedBy(userName); + record.setBenId(0L); + record.setAshaId(ashaId); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } + } catch (Exception e) { + logger.error("Error in addMonthlyAshaIncentiveRecord", e); + + } + + } + + } diff --git a/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java index f25f94eb..03af282a 100644 --- a/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java @@ -1,11 +1,17 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import com.iemr.flw.domain.iemr.InfantRegister; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.InfantRegisterDTO; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; import com.iemr.flw.repo.iemr.InfantRegisterRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.InfantService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -13,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -32,6 +39,15 @@ public class InfantServiceImpl implements InfantService { ModelMapper modelMapper = new ModelMapper(); + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + @Override public String registerInfant(List infantRegisterDTOs) { @@ -52,6 +68,7 @@ public String registerInfant(List infantRegisterDTOs) { infantList.add(infantRegister); }); infantRegisterRepo.saveAll(infantList); + checkAndGenerateIncentive(infantList); return "no of infant register details saved: " + infantList.size(); } catch (Exception e) { logger.info("error while saving infant register details: " + e.getMessage()); @@ -59,6 +76,46 @@ public String registerInfant(List infantRegisterDTOs) { return null; } + private void checkAndGenerateIncentive(List infantList) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); + + infantList.forEach(infantRegister -> { + if(incentiveActivityAM!=null){ + if(infantRegister.getIsSNCU().equals("Yes")){ + addIsSncuIncentive(incentiveActivityAM,infantRegister.getBenId(),infantRegister.getCreatedBy(),infantRegister.getCreatedDate()); + } + + } + + if(incentiveActivityCH!=null){ + if(infantRegister.getIsSNCU().equals("Yes")){ + addIsSncuIncentive(incentiveActivityCH,infantRegister.getBenId(),infantRegister.getCreatedBy(),infantRegister.getCreatedDate()); + + } + } + }); + } + + private void addIsSncuIncentive(IncentiveActivity activity, Long benId, String createdBy, Timestamp createdDate) { + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(activity.getId(),createdDate,benId); + + if(incentiveActivityRecord==null){ + incentiveActivityRecord = new IncentiveActivityRecord(); + incentiveActivityRecord.setActivityId(activity.getId()); + incentiveActivityRecord.setCreatedDate(createdDate); + incentiveActivityRecord.setCreatedBy(createdBy); + incentiveActivityRecord.setStartDate(createdDate); + incentiveActivityRecord.setEndDate(createdDate); + incentiveActivityRecord.setUpdatedDate(createdDate); + incentiveActivityRecord.setUpdatedBy(createdBy); + incentiveActivityRecord.setBenId(benId); + incentiveActivityRecord.setAshaId(userServiceRoleRepo.getUserIdByName(createdBy)); + incentiveActivityRecord.setAmount(Long.valueOf(activity.getRate())); + incentiveRecordRepo.save(incentiveActivityRecord); + } + } + @Override public List getInfantDetails(GetBenRequestHandler dto) { try{ diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java new file mode 100644 index 00000000..3b6779bc --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -0,0 +1,74 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.controller.CoupleController; +import com.iemr.flw.domain.iemr.MalariaFollowUp; +import com.iemr.flw.dto.iemr.MalariaFollowListUpDTO; +import com.iemr.flw.dto.iemr.MalariaFollowUpDTO; +import com.iemr.flw.repo.iemr.MalariaFollowUpRepository; +import com.iemr.flw.service.MalariaFollowUpService; +import com.iemr.flw.utils.JwtUtil; +import io.jsonwebtoken.Jwt; +import org.checkerframework.checker.units.qual.A; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class MalariaFollowUpServiceImpl implements MalariaFollowUpService { + + @Autowired + private MalariaFollowUpRepository repository; + + private final Logger logger = LoggerFactory.getLogger(MalariaFollowUpServiceImpl.class); + + @Autowired + private JwtUtil jwtUtil; + + public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) { + try { + for(MalariaFollowListUpDTO dto : malariaFollowUpDTO.getMalariaFollowListUp()){ + if (dto.getTreatmentStartDate().after(new Date())) { + return false; + } + + if (dto.getTreatmentCompletionDate() != null && + dto.getTreatmentCompletionDate().before(dto.getTreatmentStartDate())) { + return false; + } + + if (dto.getReferralDate() != null && + dto.getReferralDate().before(dto.getTreatmentStartDate())) { + return false; + } + + + dto.setUserId(jwtUtil.extractUserId(token)); + MalariaFollowUp entity = new MalariaFollowUp(); + BeanUtils.copyProperties(dto, entity); + repository.save(entity); + return true; + } + }catch (Exception e){ + logger.error("Exception saveFollowUp: "+ e.getMessage()); + return false; + + } + + return false; + } + + public List getByUserId(Integer userId) { + return repository.findByUserId(userId).stream().map(entity -> { + MalariaFollowListUpDTO dto = new MalariaFollowListUpDTO(); + BeanUtils.copyProperties(entity, dto); + return dto; + }).collect(Collectors.toList()); + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java index b29b45be..8914941f 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -4,20 +4,26 @@ import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.MaternalHealthService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import jakarta.transaction.Transactional; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; import java.util.stream.Collectors; @Service @@ -58,11 +64,22 @@ public class MaternalHealthServiceImpl implements MaternalHealthService { @Autowired private IncentiveRecordRepo recordRepo; + @Autowired + private JwtUtil jwtUtil; + ObjectMapper mapper = new ObjectMapper(); ModelMapper modelMapper = new ModelMapper(); + + @Autowired + private SMSServiceImpl smsServiceImpl; + + @Autowired + private AncCounsellingCareRepo ancCounsellingCareRepo; + + public static final List PNC_PERIODS = Arrays.asList("1st Day", "3rd Day", "7th Day", "14th Day", "21st Day", "28th Day", "42nd Day"); @@ -98,7 +115,7 @@ public String registerPregnantWoman(List pregnantWomanDTOs) { @Override public List getPregnantWoman(GetBenRequestHandler dto) { - try{ + try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List pregnantWomanRegisterList = pregnantWomanRegisterRepo.getPWRWithBen(user, dto.getFromDate(), dto.getToDate()); @@ -165,7 +182,7 @@ public String saveANCVisit(List ancVisitDTOs) { modelMapper.map(it, ancCare); ancCare.setBenVisitId(benVisitDetail.getBenVisitId()); ancCare.setBeneficiaryRegId(benRegId); - if(pwr != null) { + if (pwr != null) { ancCare.setLastMenstrualPeriodLmp(pwr.getLmpDate()); Calendar cal = Calendar.getInstance(); cal.setTime(pwr.getLmpDate()); @@ -180,6 +197,7 @@ public String saveANCVisit(List ancVisitDTOs) { } ancList.add(ancVisit); }); + ancVisitRepo.saveAll(ancList); ancCareRepo.saveAll(ancCareList); checkAndAddIncentives(ancList); @@ -187,6 +205,7 @@ public String saveANCVisit(List ancVisitDTOs) { return "no of anc details saved: " + ancList.size(); } catch (Exception e) { logger.info("Saving ANC visit details failed with error : " + e.getMessage()); + logger.info("Saving ANC visit details failed with error : " + e); } return null; } @@ -225,6 +244,8 @@ public String savePmsmaRecords(List pmsmaDTOs) { }); pmsmaRepo.saveAll(pmsmaList); logger.info("PMSMA details saved"); + checkAndAddHighRisk(pmsmaList); + return "No. of PMSMA records saved: " + pmsmaList.size(); } catch (Exception e) { logger.info("Saving PMSMA details failed with error : " + e.getMessage()); @@ -232,6 +253,52 @@ public String savePmsmaRecords(List pmsmaDTOs) { return null; } + private void checkAndAddHighRisk(List pmsmaList) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.ACTIVITY.getDisplayName()); + if (incentiveActivityAM != null) { + pmsmaList.forEach(pmsma -> { + if (pmsma.getHighRiskPregnant()) { + addIncentiveForHighRisk(incentiveActivityAM, pmsma); + + } + + }); + } + + if (incentiveActivityCH != null) { + pmsmaList.forEach(pmsma -> { + if (pmsma.getHighRiskPregnant()) { + addIncentiveForHighRisk(incentiveActivityCH, pmsma); + + } + + }); + } + + } + + private void addIncentiveForHighRisk(IncentiveActivity incentiveActivity, PMSMA pmsma) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), pmsma.getCreatedDate(), pmsma.getBenId()); + // get bene details + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(pmsma.getVisitDate()); + record.setCreatedBy(pmsma.getCreatedBy()); + record.setStartDate(pmsma.getVisitDate()); + record.setEndDate(pmsma.getVisitDate()); + record.setUpdatedDate(pmsma.getVisitDate()); + record.setUpdatedBy(pmsma.getCreatedBy()); + record.setBenId(pmsma.getBenId()); + record.setAshaId(userRepo.getUserIdByName(pmsma.getCreatedBy())); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } + } + @Override public List getPNCVisits(GetBenRequestHandler dto) { try { @@ -267,7 +334,6 @@ public String savePNCVisit(List pncVisitDTOs) { Long benRegId = beneficiaryRepo.getRegIDFromBenId(it.getBenId()); // Saving data in BenVisitDetails table - PregnantWomanRegister pwr = pregnantWomanRegisterRepo.findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); BenVisitDetail benVisitDetail = new BenVisitDetail(); modelMapper.map(it, benVisitDetail); benVisitDetail.setBeneficiaryRegId(benRegId); @@ -284,16 +350,12 @@ public String savePNCVisit(List pncVisitDTOs) { modelMapper.map(it, pncCare); pncCare.setBenVisitId(benVisitDetail.getBenVisitId()); pncCare.setBeneficiaryRegId(benRegId); -// pncCare.setLastMenstrualPeriodLmp(pwr.getLmpDate()); -// Calendar cal = Calendar.getInstance(); -// cal.setTime(pwr.getLmpDate()); -// cal.add(Calendar.DAY_OF_WEEK, 280); -// pncCare.setExpectedDateofDelivery(new Timestamp(cal.getTime().getTime())); pncCare.setVisitNo((short) PNC_PERIODS.indexOf(it.getPncPeriod())); pncCare.setModifiedBy(it.getUpdatedBy()); pncCare.setLastModDate(it.getUpdatedDate()); pncCare.setProcessed("N"); pncCareList.add(pncCare); + checkAndAddAntaraIncentive(pncList, pncVisit); } pncList.add(pncVisit); }); @@ -307,64 +369,409 @@ public String savePNCVisit(List pncVisitDTOs) { return null; } + @Override + @Transactional + public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + List entities = new ArrayList<>(); + + for (AncCounsellingCareDTO dto : dtos) { + + if (!StringUtils.hasText(dto.getVisitDate())) { + throw new IllegalArgumentException("visitDate is mandatory"); + } + + AncCounsellingCareListDTO fields = dto.getFields(); + if (fields == null) { + throw new IllegalArgumentException("fields object is mandatory"); + } + + LocalDate visitDate; + try { + visitDate = LocalDate.parse(dto.getVisitDate(), formatter); + } catch (DateTimeParseException e) { + throw new IllegalArgumentException("Invalid visitDate format, expected dd-MM-yyyy"); + } + + LocalDate homeVisitDate; + try { + homeVisitDate = StringUtils.hasText(fields.getHomeVisitDate()) + ? LocalDate.parse(fields.getHomeVisitDate(), formatter) + : visitDate; // ✅ fallback + } catch (DateTimeParseException e) { + throw new IllegalArgumentException("Invalid home_visit_date format, expected dd-MM-yyyy"); + } + + AncCounsellingCare entity = new AncCounsellingCare(); + entity.setBeneficiaryId(dto.getBeneficiaryId()); + entity.setAncVisitId(0L); + entity.setVisitDate(visitDate); + entity.setHomeVisitDate(homeVisitDate); + + entity.setSelectAll(yesNoToBoolean(fields.getSelectAll())); + entity.setSwelling(yesNoToBoolean(fields.getSwelling())); + entity.setHighBp(yesNoToBoolean(fields.getHighBp())); + entity.setConvulsions(yesNoToBoolean(fields.getConvulsions())); + entity.setAnemia(yesNoToBoolean(fields.getAnemia())); + entity.setReducedFetalMovement(yesNoToBoolean(fields.getReducedFetalMovement())); + entity.setAgeRisk(yesNoToBoolean(fields.getAgeRisk())); + entity.setChildGap(yesNoToBoolean(fields.getChildGap())); + entity.setShortHeight(yesNoToBoolean(fields.getShortHeight())); + entity.setPrePregWeight(yesNoToBoolean(fields.getPrePregWeight())); + entity.setBleeding(yesNoToBoolean(fields.getBleeding())); + entity.setMiscarriageHistory(yesNoToBoolean(fields.getMiscarriageHistory())); + entity.setFourPlusDelivery(yesNoToBoolean(fields.getFourPlusDelivery())); + entity.setFirstDelivery(yesNoToBoolean(fields.getFirstDelivery())); + entity.setTwinPregnancy(yesNoToBoolean(fields.getTwinPregnancy())); + entity.setCSectionHistory(yesNoToBoolean(fields.getCSectionHistory())); + entity.setPreExistingDisease(yesNoToBoolean(fields.getPreExistingDisease())); + entity.setFeverMalaria(yesNoToBoolean(fields.getFeverMalaria())); + entity.setJaundice(yesNoToBoolean(fields.getJaundice())); + entity.setSickleCell(yesNoToBoolean(fields.getSickleCell())); + entity.setProlongedLabor(yesNoToBoolean(fields.getProlongedLabor())); + entity.setMalpresentation(yesNoToBoolean(fields.getMalpresentation())); + + entity.setUserId(jwtUtil.extractUserId(authorization)); + entity.setCreatedBy(jwtUtil.extractUsername(authorization)); + entity.setUpdatedBy(jwtUtil.extractUsername(authorization)); + + entities.add(entity); + } + + ancCounsellingCareRepo.saveAll(entities); + return "ANC Counselling & Care data saved successfully"; + } + + + @Override + public List getANCCounselling(GetBenRequestHandler requestDTO) { + + List entities = + ancCounsellingCareRepo.findAllByUserId(requestDTO.getAshaId()); + + List responseDTOList = new ArrayList<>(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + for (AncCounsellingCare entity : entities) { + + AncCounsellingCareResponseDTO responseDTO = new AncCounsellingCareResponseDTO(); + responseDTO.setFormId("anc_form_001"); + responseDTO.setBeneficiaryId(entity.getBeneficiaryId()); // Update with actual value + responseDTO.setVisitDate(entity.getVisitDate().format(formatter)); // Format visit.getVisitDate() + + // 🔹 fields map + Map fields = new HashMap<>(); + + fields.put("home_visit_date", + entity.getHomeVisitDate() != null + ? entity.getHomeVisitDate().format(formatter) + : null); + + fields.put("select_all", booleanToYesNo(entity.getSelectAll())); + fields.put("swelling", booleanToYesNo(entity.getSwelling())); + fields.put("high_bp", booleanToYesNo(entity.getHighBp())); + fields.put("convulsions", booleanToYesNo(entity.getConvulsions())); + fields.put("anemia", booleanToYesNo(entity.getAnemia())); + fields.put("reduced_fetal_movement", booleanToYesNo(entity.getReducedFetalMovement())); + fields.put("age_risk", booleanToYesNo(entity.getAgeRisk())); + fields.put("child_gap", booleanToYesNo(entity.getChildGap())); + fields.put("short_height", booleanToYesNo(entity.getShortHeight())); + fields.put("pre_preg_weight", booleanToYesNo(entity.getPrePregWeight())); + fields.put("bleeding", booleanToYesNo(entity.getBleeding())); + fields.put("miscarriage_history", booleanToYesNo(entity.getMiscarriageHistory())); + fields.put("four_plus_delivery", booleanToYesNo(entity.getFourPlusDelivery())); + fields.put("first_delivery", booleanToYesNo(entity.getFirstDelivery())); + fields.put("twin_pregnancy", booleanToYesNo(entity.getTwinPregnancy())); + fields.put("c_section_history", booleanToYesNo(entity.getCSectionHistory())); + fields.put("pre_existing_disease", booleanToYesNo(entity.getPreExistingDisease())); + fields.put("fever_malaria", booleanToYesNo(entity.getFeverMalaria())); + fields.put("jaundice", booleanToYesNo(entity.getJaundice())); + fields.put("sickle_cell", booleanToYesNo(entity.getSickleCell())); + fields.put("prolonged_labor", booleanToYesNo(entity.getProlongedLabor())); + fields.put("malpresentation", booleanToYesNo(entity.getMalpresentation())); + + responseDTO.setFields(fields); + responseDTOList.add(responseDTO); + + + + + } + return responseDTOList; + + } + + private String booleanToYesNo(Boolean value) { + return Boolean.TRUE.equals(value) ? "Yes" : "No"; + } + + + + private Boolean yesNoToBoolean(String value) { + return "Yes".equalsIgnoreCase(value); + } + + + private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { + Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); + logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); + + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { + + IncentiveActivity maleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); + if (maleSterilizationActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityAM); + } + if (maleSterilizationActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityCH); + } + + } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { + + IncentiveActivity femaleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); + if (femaleSterilizationActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityAM); + } + + if (femaleSterilizationActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityCH); + } + } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MiniLap")) { + + IncentiveActivity miniLapActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", GroupName.FAMILY_PLANNING.getDisplayName()); + if (miniLapActivity != null) { + addIncenticeRecord(recordList, ect, userId, miniLapActivity); + } + } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("Condom")) { + + IncentiveActivity comdomActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", GroupName.FAMILY_PLANNING.getDisplayName()); + if (comdomActivity != null) { + addIncenticeRecord(recordList, ect, userId, comdomActivity); + } + } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM IUCD (PPIUCD) WITHIN 48 HRS OF DELIVERY")) { + + IncentiveActivity PPIUCDActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity PPIUCDActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.ACTIVITY.getDisplayName()); + if (PPIUCDActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, PPIUCDActivityAM); + } + + if (PPIUCDActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, PPIUCDActivityCH); + } + } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)")) { + + IncentiveActivity ppsActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity ppsActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); + if (ppsActivityAM != null) { + addIncenticeRecord(recordList, ect, userId, ppsActivityAM); + } + + if (ppsActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, ppsActivityCH); + } + } + + } + + private void addIncenticeRecord(List recordList, PNCVisit ect, Integer userId, IncentiveActivity antaraActivity) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); + // get bene details + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(antaraActivity.getId()); + record.setCreatedDate(ect.getPncDate()); + record.setCreatedBy(ect.getCreatedBy()); + record.setStartDate(ect.getPncDate()); + record.setEndDate(ect.getPncDate()); + record.setUpdatedDate(ect.getPncDate()); + record.setUpdatedBy(ect.getCreatedBy()); + record.setBenId(ect.getBenId()); + record.setAshaId(userId); + record.setAmount(Long.valueOf(antaraActivity.getRate())); + recordRepo.save(record); + } + } + + private void checkAndAddIncentives(List ancList) { + IncentiveActivity anc1Activity = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANC-1", "MATERNAL HEALTH"); - - IncentiveActivity ancFullActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("ANC-FULL", "MATERNAL HEALTH"); - - if (anc1Activity != null) { - ancList.forEach( ancVisit -> { - Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); - if (ancVisit.getAncVisit() == 1) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(anc1Activity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId()); - if (record == null) { - record = new IncentiveActivityRecord(); - record.setActivityId(anc1Activity.getId()); - record.setCreatedDate(ancVisit.getCreatedDate()); - record.setCreatedBy(ancVisit.getCreatedBy()); - record.setStartDate(ancVisit.getCreatedDate()); - record.setEndDate(ancVisit.getCreatedDate()); - record.setUpdatedDate(ancVisit.getCreatedDate()); - record.setUpdatedBy(ancVisit.getCreatedBy()); - record.setBenId(ancVisit.getBenId()); - record.setAshaId(userId); - record.setAmount(Long.valueOf(anc1Activity.getRate())); - recordRepo.save(record); + incentivesRepo.findIncentiveMasterByNameAndGroup("ANC_REGISTRATION_1ST_TRIM", GroupName.MATERNAL_HEALTH.getDisplayName()); + + IncentiveActivity ancFullActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_ANC", GroupName.MATERNAL_HEALTH.getDisplayName()); + + IncentiveActivity ancFullActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("ANC_FOUR_CHECKUPS_SUPPORT", GroupName.ACTIVITY.getDisplayName()); + + IncentiveActivity comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("COMPREHENSIVE_ABORTION_CARE", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("COMPREHENSIVE_ABORTION_CARE", GroupName.ACTIVITY.getDisplayName()); + + IncentiveActivity identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.ACTIVITY.getDisplayName()); + + IncentiveActivity paiucdActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + + IncentiveActivity paiucdActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); + + ancList.forEach(ancVisit -> { + if (paiucdActivityAM != null) { + if (ancVisit.getIsPaiucd()!= null) { + if (ancVisit.getIsPaiucd().equals("Yes")) { + recordAncRelatedIncentive(paiucdActivityAM, ancVisit); + } } - if (ancVisit.getAncVisit() == 4) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(ancFullActivity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId()); - ANCVisit visit1 = ancVisitRepo - .findANCVisitByBenIdAndAncVisitAndIsActive(ancVisit.getBenId(), 1, true); - ANCVisit visit2 = ancVisitRepo - .findANCVisitByBenIdAndAncVisitAndIsActive(ancVisit.getBenId(), 2, true); - ANCVisit visit3 = ancVisitRepo - .findANCVisitByBenIdAndAncVisitAndIsActive(ancVisit.getBenId(), 3, true); - ANCVisit visit4 = ancVisitRepo - .findANCVisitByBenIdAndAncVisitAndIsActive(ancVisit.getBenId(), 4, true); - - if (record == null && (visit1 != null) && (visit2 != null) && (visit3 != null) && (visit4 != null)) { - record = new IncentiveActivityRecord(); - record.setActivityId(ancFullActivity.getId()); - record.setCreatedDate(ancVisit.getCreatedDate()); - record.setCreatedBy(ancVisit.getCreatedBy()); - record.setUpdatedDate(ancVisit.getCreatedDate()); - record.setUpdatedBy(ancVisit.getCreatedBy()); - record.setStartDate(visit1.getCreatedDate()); - record.setEndDate(visit4.getCreatedDate()); - record.setBenId(ancVisit.getBenId()); - record.setAshaId(userId); - record.setAmount(Long.valueOf(ancFullActivity.getRate())); - recordRepo.save(record); + } + + if (paiucdActivityCH != null) { + + if (ancVisit.getIsPaiucd()!= null) { + if (ancVisit.getIsPaiucd().equals("Yes")) { + + recordAncRelatedIncentive(paiucdActivityCH, ancVisit); + } } - }); + + + } + if (anc1Activity != null) { + if (ancVisit.getAncVisit() != null) { + + if (ancVisit.getAncVisit() == 1) { + recordAncRelatedIncentive(anc1Activity, ancVisit); + } + } + } + if (ancFullActivityAM != null) { + if (ancVisit.getAncVisit() == 4 || ancVisit.getAncVisit() == 2 || ancVisit.getAncVisit() == 3) { + recordAncRelatedIncentive(ancFullActivityAM, ancVisit); + } + + } + if (ancFullActivityCH != null) { + if (ancVisit.getAncVisit() != null) { + if (ancVisit.getAncVisit() == 4) { + recordAncRelatedIncentive(ancFullActivityCH, ancVisit); + } + } + + } + if (comprehensiveAbortionActivityAM != null) { + if (ancVisit.getIsAborted() != null) { + if (ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityAM, ancVisit); + } + } + + } + + if (comprehensiveAbortionActivityCH != null) { + if (ancVisit.getIsAborted() != null) { + if (ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityCH, ancVisit); + } + } + + } + if (identifiedHrpActivityAM != null) { + if (ancVisit.getIsHrpConfirmed() != null) { + if (ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityAM, ancVisit); + } + } + + } + + if (identifiedHrpActivityCH != null) { + if (ancVisit.getIsHrpConfirmed() != null) { + if (ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityCH, ancVisit); + } + } + + } + + }); + + + } + + private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { + IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId()); + Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); + + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(ancVisit.getCreatedDate()); + record.setCreatedBy(ancVisit.getCreatedBy()); + record.setUpdatedDate(ancVisit.getCreatedDate()); + record.setUpdatedBy(ancVisit.getCreatedBy()); + record.setStartDate(ancVisit.getCreatedDate()); + record.setEndDate(ancVisit.getCreatedDate()); + record.setBenId(ancVisit.getBenId()); + record.setAshaId(userId); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); } + } + + public void sendAncDueTomorrowNotifications(String ashaId) { + try { + GetBenRequestHandler request = new GetBenRequestHandler(); + request.setAshaId(Integer.valueOf(ashaId)); + request.setFromDate(Timestamp.valueOf(LocalDate.now().plusDays(1).atStartOfDay())); // Tomorrow at 00:00:00 + request.setToDate(Timestamp.valueOf(LocalDate.now().plusDays(1).atTime(LocalTime.MAX))); // Tomorrow at 23:59:59.999999999 + + + List ancList = getANCVisits(request); + + if (ancList != null) { + for (ANCVisitDTO anc : ancList) { + if (anc.getAncDate() != null && anc.getAncDate().toLocalDateTime().toLocalDate().isEqual(LocalDate.now().plusDays(1))) { + String ancType = anc.getAbortionType(); // ANC1, ANC2, etc. + String body = "Reminder: Scheduled ANC check-up (" + ancType + ") is due tomorrow."; + String redirectPath = "/work-plan/anc/" + ancType.toLowerCase(); + String appType = "FLW_APP"; // or "ASHAA_APP", based on user type + String topic = "All"; // or some user/topic identifier + String title = "ANC Reminder"; + + + } + } + } + + } catch (Exception e) { + logger.error("Error in sending ANC reminder notifications: {}", e.getMessage()); + } + } + + } diff --git a/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionService.java b/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionService.java new file mode 100644 index 00000000..071ba4c0 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionService.java @@ -0,0 +1,12 @@ +package com.iemr.flw.service.impl; + +import java.util.List; + +import com.iemr.flw.dto.iemr.MdaFormSubmissionRequest; +import com.iemr.flw.dto.iemr.MdaFormSubmissionResponse; + +public interface MdaFormSubmissionService { + String saveFormData(List requests); + + List getFormDataByUserName(String userName); +} diff --git a/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionServiceImpl.java new file mode 100644 index 00000000..e7b0fe4e --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/MdaFormSubmissionServiceImpl.java @@ -0,0 +1,93 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.MdaDistributionData; +import com.iemr.flw.dto.iemr.MdaFormFieldsDTO; +import com.iemr.flw.dto.iemr.MdaFormSubmissionRequest; +import com.iemr.flw.dto.iemr.MdaFormSubmissionResponse; +import com.iemr.flw.repo.iemr.MdaFormSubmissionRepository; + +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +@Service +@RequiredArgsConstructor +public class MdaFormSubmissionServiceImpl implements MdaFormSubmissionService { + + @Autowired + private final MdaFormSubmissionRepository repository; + + @Override + public String saveFormData(List requests) { + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + List entities = new ArrayList<>(); + for (MdaFormSubmissionRequest req : requests) { + LocalDate visitLocalDate = LocalDate.parse(req.getVisitDate(), formatter); + Timestamp visitDate = Timestamp.valueOf(visitLocalDate.atStartOfDay()); + + LocalDate getMdaDistributionDateLocalDate = LocalDate.parse(req.getFields().getMda_distribution_date(), formatter); + Timestamp getMdaDistributionDate = Timestamp.valueOf(getMdaDistributionDateLocalDate.atStartOfDay()); + MdaDistributionData data = MdaDistributionData.builder() + .beneficiaryId(req.getBeneficiaryId()) + .formId(req.getFormId()) + .houseHoldId(req.getHouseHoldId()) + .userName(req.getUserName()) + .visitDate(visitDate) + .mdaDistributionDate(getMdaDistributionDate) + .isMedicineDistributed(req.getFields().getIs_medicine_distributed()) + .createdBy(req.getUserName()) + .modifiedBy(req.getUserName()) + .build(); + entities.add(data); + } + repository.saveAll(entities); + return "MDA form data saved successfully"; + } catch (Exception e) { + e.printStackTrace(); + return "Error while saving form data: " + e.getMessage(); + } + } + + @Override + public List getFormDataByUserName(String userName) { + List records = repository.findByUserName(userName); + + List responses = new ArrayList<>(); + + for (MdaDistributionData entity : records) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + String mdaformattedDate = sdf.format(entity.getMdaDistributionDate()); + String visitformattedDate = sdf.format(entity.getVisitDate()); + + MdaFormFieldsDTO fieldsDTO = MdaFormFieldsDTO.builder() + .mda_distribution_date(mdaformattedDate) + .is_medicine_distributed(entity.getIsMedicineDistributed()) + .build(); + + responses.add(MdaFormSubmissionResponse.builder() + .formId(entity.getFormId()) + .houseHoldId(entity.getHouseHoldId()) + .beneficiaryId(entity.getBeneficiaryId()) + .visitDate(visitformattedDate) + .createdBy(entity.getCreatedBy()) + .createdAt(entity.getCreatedDate()) + .fields(fieldsDTO) + .build()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + return responses; + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java new file mode 100644 index 00000000..1c9130a0 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/MicroBirthPlanServiceImpl.java @@ -0,0 +1,73 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.MicroBirthPlan; +import com.iemr.flw.dto.iemr.MicroBirthPlanDTO; +import com.iemr.flw.repo.iemr.MicroBirthPlanRepository; +import com.iemr.flw.service.MicroBirthPlanService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +@Service +public class MicroBirthPlanServiceImpl implements MicroBirthPlanService { + @Autowired + private MicroBirthPlanRepository microBirthPlanRepository; + + + @Override + public MicroBirthPlan createMicroBirthPlan(MicroBirthPlanDTO birthPlan) { + MicroBirthPlan lastProcessedPlan = new MicroBirthPlan(); + + for (MicroBirthPlan entry : birthPlan.getEntries()) { + // Check if the entry already exists in the database + Optional existingEntry = microBirthPlanRepository.findByBenId(entry.getBenId()); + + if (existingEntry.isPresent()) { + lastProcessedPlan= updateMicroBirthPlan(entry.getBenId(),entry); + continue; + } + + // Set user ID and prepare for saving + entry.setUserId(birthPlan.getUserId()); + lastProcessedPlan = microBirthPlanRepository.save(entry); + } + + return lastProcessedPlan; + } + + + @Override + public List getAllMicroBirthPlans(Integer userId) { + return microBirthPlanRepository.findByUserId(userId); + + } + + private MicroBirthPlan updateMicroBirthPlan(Long id, MicroBirthPlan updatedPlan){ + return microBirthPlanRepository.findByBenId(id).map(existingPlan -> { + existingPlan.setContactNumber1(updatedPlan.getContactNumber1()); + existingPlan.setContactNumber2(updatedPlan.getContactNumber2()); + existingPlan.setScHosp(updatedPlan.getScHosp()); + existingPlan.setBlock(updatedPlan.getBlock()); + existingPlan.setNearestSc(updatedPlan.getNearestSc()); + existingPlan.setNearestPhc(updatedPlan.getNearestPhc()); + existingPlan.setNearestFru(updatedPlan.getNearestFru()); + existingPlan.setUsg(updatedPlan.getUsg()); + existingPlan.setBloodGroup(updatedPlan.getBloodGroup()); + existingPlan.setBloodDonors2(updatedPlan.getBloodDonors2()); + existingPlan.setBirthCompanion(updatedPlan.getBirthCompanion()); + existingPlan.setCareTaker(updatedPlan.getCareTaker()); + existingPlan.setCommunityMember(updatedPlan.getCommunityMember()); + existingPlan.setCommunityMemberContact(updatedPlan.getCommunityMemberContact()); + existingPlan.setModeOfTransportation(updatedPlan.getModeOfTransportation()); + existingPlan.setBenId(updatedPlan.getBenId()); + return microBirthPlanRepository.save(existingPlan); + }).orElseThrow(() -> new RuntimeException("Micro Birth Plan not found")); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java b/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java new file mode 100644 index 00000000..a5b6dd77 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java @@ -0,0 +1,71 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.service.EmployeeMasterInter; +import com.iemr.flw.service.impl.ChildCareServiceImpl; +import com.iemr.flw.service.impl.MaternalHealthServiceImpl; +import com.iemr.flw.utils.CookieUtil; +import jakarta.annotation.PostConstruct; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +@Service +public class NotificationSchedulerService { + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + + @Autowired + private NotificationService notificationService; + @Autowired + EmployeeMasterInter employeeMasterInter; + + @Autowired + private ChildCareServiceImpl childCareService; + @Autowired + private CookieUtil cookieUtil; + + @Scheduled(cron = "0 0 9 * * *") // every day at 9 AM + public void triggerAncRemindersForAllAsha() { + +// HttpServletRequest requestHeader = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) +// .getRequest(); +// String jwtTokenFromCookie = cookieUtil.getJwtTokenFromCookie(requestHeader); +// for(M_User m_user: employeeMasterInter.getAllUsers()){ +// maternalHealthService.sendAncDueTomorrowNotifications(String.valueOf(m_user.getUserID())); +// +// } + logger.info("triggerAncRemindersForAllAsha Service start"); + String ancType = "ANC!"; // ANC1, ANC2, etc. + String body = "Reminder: Scheduled ANC check-up (" + ancType + ") is due tomorrow."; + String redirectPath = "/work-plan/anc/" + ancType.toLowerCase(); + String appType = "FLW_APP"; // or "ASHAA_APP", based on user type +// String topic = "ANC"+963; // or some user/topic identifier + String topic = "All"; // or some user/topic identifier + String title = "ANC Reminder"; + + notificationService.sendNotification( + appType, + topic, + title, + body, + redirectPath + ); + + } + + @Scheduled(cron = "0 0 9 * * *") + public void trigerTomorrowImmunizationReminders() { + for(M_User m_user: employeeMasterInter.getAllUsers()){ + childCareService.getTomorrowImmunizationReminders(m_user.getUserID()); + + } + } + + +} diff --git a/src/main/java/com/iemr/flw/service/impl/NotificationService.java b/src/main/java/com/iemr/flw/service/impl/NotificationService.java new file mode 100644 index 00000000..838ff3ac --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/NotificationService.java @@ -0,0 +1,81 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.HashMap; +import java.util.Map; + +@Service +public class NotificationService { + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + + private String NOTIFICATION_URL = "https://uatamrit.piramalswasthya.org/common-api/firebaseNotification/sendNotification"; + + public String sendNotification(String appType, String topic, String title, String body, String redirect) { + String authHeader = null; + String jwtToken = null; + + // Check if we have HTTP request context + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes != null) { + HttpServletRequest httpServletRequest = attributes.getRequest(); + + authHeader = httpServletRequest.getHeader("Authorization"); + + if (httpServletRequest.getCookies() != null) { + for (Cookie cookie : httpServletRequest.getCookies()) { + if ("Jwttoken".equals(cookie.getName())) { + jwtToken = cookie.getValue(); + } + } + } + } + + // If no request context, set default (for scheduler/startup use) + if (authHeader == null) { + authHeader = "Bearer DEFAULT_TOKEN_IF_REQUIRED"; // or leave null if API allows + } + if (jwtToken == null) { + jwtToken = "DEFAULT_JWT_IF_REQUIRED"; + } + + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", "application/json"); +// headers.add("AUTHORIZATION", authHeader); +// headers.add("Cookie", "Jwttoken=" + jwtToken); + + Map requestBody = new HashMap<>(); + requestBody.put("appType", appType); + requestBody.put("token", topic); + requestBody.put("title", title); + requestBody.put("body", body); + + Map dataMap = new HashMap<>(); + dataMap.put("NotificationTypeId", redirect); + requestBody.put("data", dataMap); + + String jsonRequest = new Gson().toJson(requestBody); + + HttpEntity request = new HttpEntity<>(jsonRequest, headers); + + ResponseEntity response = restTemplate.exchange(NOTIFICATION_URL, HttpMethod.POST, request, String.class); + + return response.getBody(); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/SMSServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SMSServiceImpl.java new file mode 100644 index 00000000..670970be --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/SMSServiceImpl.java @@ -0,0 +1,101 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import com.iemr.flw.domain.iemr.SMSTemplate; +import com.iemr.flw.repo.iemr.SMSTemplateRepository; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.*; +import org.springframework.stereotype.Service; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.time.LocalDate; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +@Service +public class SMSServiceImpl { + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + @Autowired + SMSTemplateRepository smsTemplateRepository; + @Value("${sms-username}") + private String smsUserName; + private String smsTemplate; + + @Value("${sms-password}") + private String smsPassword; + + @Value("${sms-entityid}") + private String smsEntityId; + + @Value("${source-address}") + private String smsSourceAddress; + + @Value("${send-message-url}") + private String SMS_GATEWAY_URL; + + private String smsTemplateName = "reminder_sms"; + + + + public String sendReminderSMS(String mobileNo, String serviceName, LocalDate date) { + final RestTemplate restTemplate = new RestTemplate(); + + + Optional smsTemplateData = smsTemplateRepository.findBySmsTemplateName(smsTemplateName); + if (smsTemplateData.isPresent()) { + smsTemplate = smsTemplateRepository.findBySmsTemplateID(smsTemplateData.get().getSmsTemplateID()).getSmsTemplate(); + + } + + try { + + String message = smsTemplate.replace("$$serviceName$$",serviceName).replace("$$date$$",date.toString()); + Map payload = new HashMap<>(); + payload.put("customerId",smsUserName); + payload.put("destinationAddress", mobileNo); + payload.put("message", message); + payload.put("sourceAddress", smsSourceAddress); + payload.put("messageType", "SERVICE_IMPLICIT"); + payload.put("dltTemplateId", smsTemplateData.get().getDltTemplateId()); + payload.put("entityId",smsEntityId); + // Set headers + HttpHeaders headers = new HttpHeaders(); + logger.info("userName:"+smsUserName+":"+smsPassword+":"+SMS_GATEWAY_URL); + + String auth = smsUserName + ":" + smsPassword; + headers.add("Authorization", + "Basic " + Base64.getEncoder().encodeToString(auth.getBytes())); + + headers.setContentType(MediaType.APPLICATION_JSON); + logger.info("payload: "+payload); + logger.info("header: "+headers); + HttpEntity> request = new HttpEntity<>(payload, headers); + + // Call API + ResponseEntity response = restTemplate.postForEntity(SMS_GATEWAY_URL, request, String.class); + logger.info("sms-response:"+response.getBody()); + logger.info("sms-response status:"+response.getStatusCode().value()); + if(response.getStatusCode().value()==200){ + return serviceName+" Reminder sent successfully on register mobile number"; + }else { + return "Fail"; + + } + + } catch (Exception e) { + return "Error sending SMS: " + e.getMessage(); + } + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java new file mode 100644 index 00000000..53497981 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java @@ -0,0 +1,175 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.iemr.SammelanAttachment; +import com.iemr.flw.domain.iemr.SammelanRecord; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.SammelanService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.ZoneId; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class SammelanServiceImpl implements SammelanService { + private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + + @Autowired + private SammelanRecordRepository recordRepo; + @Autowired + private SammelanAttachmentRepository attachmentRepo; + + private SammelanRecord record; + + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + @Autowired + private ObjectMapper objectMapper; + + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + + + @Override + public SammelanResponseDTO submitSammelan(SammelanRequestDTO sammelanRequestDTO) { + SammelanResponseDTO response = new SammelanResponseDTO(); + + try { + + // Save Sammelan record + record = new SammelanRecord(); + record.setAshaId(sammelanRequestDTO.getAshaId()); + logger.info("Meeting Date:"+sammelanRequestDTO.getDate()); + Timestamp timestamp = new Timestamp(sammelanRequestDTO.getDate()); + record.setMeetingDate(timestamp); + record.setPlace(sammelanRequestDTO.getPlace()); + record.setParticipants(sammelanRequestDTO.getParticipants()); + + + if (sammelanRequestDTO.getSammelanImages() != null && sammelanRequestDTO.getSammelanImages().length > 0) { + List base64Images = Arrays.stream(sammelanRequestDTO.getSammelanImages()) + .filter(file -> !file.isEmpty()) + .map(file -> { + try { + return Base64.getEncoder().encodeToString(file.getBytes()); + } catch (IOException e) { + throw new RuntimeException("Error converting image to Base64", e); + } + }) + .collect(Collectors.toList()); + + String imagesJson = objectMapper.writeValueAsString(base64Images); + record .setAttachments(imagesJson); + } + + if(record!=null){ + record = recordRepo.save(record); + checkIncentive(record); + + + } + // Prepare Response DTO + response.setId(record.getId()); + response.setAshaId(record.getAshaId()); + Timestamp ts = Timestamp.valueOf(record.getMeetingDate().toLocalDateTime()); + long millis = ts.getTime(); + response.setDate(millis); + response.setPlace(record.getPlace()); + response.setParticipants(record.getParticipants()); + + + } catch (Exception e) { + + logger.info("SammelanRecord Exception: "+e.getMessage()); + } + return response; + + + } + + private void checkIncentive(SammelanRecord record) { + IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_SAAS_BAHU", GroupName.FAMILY_PLANNING.getDisplayName()); + logger.info("SammelanRecord: "+incentiveActivity.getRate()); + if(incentiveActivity!=null){ + addSammelanIncentive(incentiveActivity,record); + } + } + + private void addSammelanIncentive(IncentiveActivity incentiveActivity, SammelanRecord record) { + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), record.getMeetingDate(), 0L,record.getAshaId()); + try { + if (incentiveActivityRecord == null) { + incentiveActivityRecord = new IncentiveActivityRecord(); + incentiveActivityRecord.setActivityId(incentiveActivity.getId()); + incentiveActivityRecord.setCreatedDate(record.getMeetingDate()); + incentiveActivityRecord.setCreatedBy(userRepo.getUserNamedByUserId(record.getAshaId())); + incentiveActivityRecord.setStartDate(record.getMeetingDate()); + incentiveActivityRecord.setEndDate(record.getMeetingDate()); + incentiveActivityRecord.setUpdatedDate(record.getMeetingDate()); + incentiveActivityRecord.setUpdatedBy(userRepo.getUserNamedByUserId(record.getAshaId())); + incentiveActivityRecord.setBenId(0L); + incentiveActivityRecord.setAshaId(record.getAshaId()); + incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivity.getRate())); + incentiveRecordRepo.save(incentiveActivityRecord); + } + }catch (Exception e){ + logger.info("SammelanRecord save Record: ",e); + + } + + } + + + @Override + public List getSammelanHistory(Integer ashaId) { + List records = recordRepo.findByAshaId(ashaId); + return records.stream().map(record -> { + SammelanResponseDTO dto = new SammelanResponseDTO(); + dto.setId(record.getId()); + dto.setAshaId(record.getAshaId()); + Timestamp ts = Timestamp.valueOf(record.getMeetingDate().toLocalDateTime()); + long millis = ts.getTime(); + dto.setDate(millis); + dto.setPlace(record.getPlace()); + dto.setParticipants(record.getParticipants()); + try { + if (record.getAttachments() != null) { + List images = objectMapper.readValue( + record.getAttachments(), + new TypeReference>() { + } + ); + dto.setImagePaths(images); + } + } catch (Exception e) { + dto.setImagePaths(List.of()); + } + + return dto; + }).collect(Collectors.toList()); + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java b/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java new file mode 100644 index 00000000..637d011a --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java @@ -0,0 +1,104 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; +import com.iemr.flw.domain.iemr.ANCVisit; +import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.dto.iemr.ANCVisitDTO; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.ANCVisitRepo; +import com.iemr.flw.service.EmployeeMasterInter; +import com.iemr.flw.utils.CookieUtil; +import jakarta.annotation.PostConstruct; +import jakarta.servlet.http.HttpServletRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.math.BigInteger; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +@Service +public class SmsSchedulerService { + final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private SMSServiceImpl smsServiceImpl; + + @Autowired + private BeneficiaryRepo beneficiaryRepo; + @Autowired + EmployeeMasterInter employeeMasterInter; + + @Autowired + private ANCVisitRepo ancVisitRepo; + + @Autowired + private ChildCareServiceImpl childCareService; + @Autowired + private CookieUtil cookieUtil; + + @Scheduled(cron = "0 0 9 * * *") + public void sendAncReminders() { + try { + + List ancVisitList = ancVisitRepo.findAll(); + logger.info("ANC_SMS service is start"); + ancVisitList.forEach(ancVisit -> { + Timestamp ancDate = ancVisit.getAncDate(); + if (ancDate != null) { + LocalDate visitDate = ancDate.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + + LocalDate tomorrow = LocalDate.now().plusDays(1); + + if (visitDate.equals(tomorrow)) { + logger.info("BenId:"+ancVisit.getBenId()); + + Optional beneficiaryDetailsRmnch = beneficiaryRepo.findById(ancVisit.getBenId()); + if (beneficiaryDetailsRmnch.isPresent()) { + RMNCHBeneficiaryDetailsRmnch beneficiary = beneficiaryDetailsRmnch.get(); + + BigInteger vanSerialNo = beneficiaryRepo.getBenIdFromRegID(beneficiary.getBenRegId()); + logger.info("vanSerialNo:"+vanSerialNo); + + if(beneficiaryRepo.getContactById(vanSerialNo)!=null){ + + smsServiceImpl.sendReminderSMS(beneficiaryRepo.getContactById(vanSerialNo).getContact_number(),"ANC",tomorrow); + + } + } + + } + + + } + }); + + } catch (Exception e) { + logger.error(e.getMessage()); + } + } + + + + @Scheduled(cron = "0 0 9 * * *") + public void trigerTomorrowImmunizationReminders() { + for (M_User m_user : employeeMasterInter.getAllUsers()) { + childCareService.getTomorrowImmunizationReminders(m_user.getUserID()); + + } + } + + +} diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java new file mode 100644 index 00000000..39b12177 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -0,0 +1,147 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; +import com.iemr.flw.domain.iemr.TBConfirmedCase; +import com.iemr.flw.dto.iemr.TBConfirmedCasesResponseDTO; +import com.iemr.flw.repo.iemr.TBConfirmedTreatmentRepository; +import com.iemr.flw.service.TBConfirmedCaseService; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.LocalDateAdapter; +import com.iemr.flw.utils.response.OutputResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class TBConfirmedCaseServiceImpl implements TBConfirmedCaseService { + + private static final Logger logger = LoggerFactory.getLogger(TBConfirmedCaseServiceImpl.class); + + private final TBConfirmedTreatmentRepository repository; + + @Autowired + private JwtUtil jwtUtil; + public TBConfirmedCaseServiceImpl(TBConfirmedTreatmentRepository repository) { + this.repository = repository; + } + + @Override + public String save(List request, String authorisation) throws Exception { + OutputResponse response = new OutputResponse(); + + try { + if (request != null) { + logger.info("Saving TB confirmed case: " + request); + + TBConfirmedCase entity = new TBConfirmedCase(); + for(TBConfirmedCaseDTO dto:request){ + entity.setBenId(dto.getBenId()); + entity.setUserId(jwtUtil.extractUserId(authorisation)); + entity.setRegimenType(dto.getRegimenType()); + entity.setTreatmentStartDate(dto.getTreatmentStartDate()); + entity.setExpectedTreatmentCompletionDate(dto.getExpectedTreatmentCompletionDate()); + entity.setFollowUpDate(dto.getFollowUpDate()); + entity.setMonthlyFollowUpDone(dto.getMonthlyFollowUpDone()); + entity.setAdherenceToMedicines(dto.getAdherenceToMedicines()); + entity.setAnyDiscomfort(dto.getAnyDiscomfort()); + entity.setTreatmentCompleted(dto.getTreatmentCompleted()); + entity.setActualTreatmentCompletionDate(dto.getActualTreatmentCompletionDate()); + entity.setTreatmentOutcome(dto.getTreatmentOutcome()); + entity.setDateOfDeath(dto.getDateOfDeath()); + entity.setPlaceOfDeath(dto.getPlaceOfDeath()); + entity.setReasonForDeath(dto.getReasonForDeath()); + entity.setReasonForNotCompleting(dto.getReasonForNotCompleting()); + if(entity!=null){ + repository.save(entity); + + } + } + + + + + response.setResponse("TB Confirmed case saved successfully"); + + } else { + response.setError(500, "Invalid/NULL request obj"); + } + } catch (Exception e) { + logger.error("Error saving TB confirmed case", e); + response.setError(5000, "Error saving TB confirmed case: " + e.getMessage()); + } + + return response.toString(); + } + + @Override + public String getByBenId(Long benId, String authorisation) throws Exception { + OutputResponse response = new OutputResponse(); + + try { + List list = repository.findByBenId(benId); + + if (list != null && !list.isEmpty()) { + List dtoList = list.stream() + .map(this::toDTO) + .collect(Collectors.toList()); + + response.setResponse(dtoList.toString()); + } else { + response.setError(404, "No record found for benId: " + benId); + } + + } catch (Exception e) { + logger.error("Error getting TB confirmed case by benId", e); + response.setError(5000, "Error getting TB confirmed case: " + e.getMessage()); + } + + return response.toString(); + } + + @Override + public String getByUserId(String authorisation) throws Exception { + TBConfirmedCasesResponseDTO tbConfirmedCasesResponseDTO = new TBConfirmedCasesResponseDTO(); + Integer userId = jwtUtil.extractUserId(authorisation); + List list = repository.findByUserId(userId); + tbConfirmedCasesResponseDTO.setUserId(userId); + tbConfirmedCasesResponseDTO.setTbConfirmedCases(list); + Gson gson = new GsonBuilder() + .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) + .create(); + + return gson.toJson(tbConfirmedCasesResponseDTO); + } + + // Utility: convert entity -> DTO + private TBConfirmedCaseDTO toDTO(TBConfirmedCase entity) { + TBConfirmedCaseDTO dto = new TBConfirmedCaseDTO(); + + dto.setBenId(entity.getBenId()); + dto.setUserId(entity.getUserId()); + dto.setRegimenType(entity.getRegimenType()); + dto.setTreatmentStartDate(entity.getTreatmentStartDate()); + dto.setExpectedTreatmentCompletionDate(entity.getExpectedTreatmentCompletionDate()); + dto.setFollowUpDate(entity.getFollowUpDate()); + dto.setMonthlyFollowUpDone(entity.getMonthlyFollowUpDone()); + dto.setAdherenceToMedicines(entity.getAdherenceToMedicines()); + dto.setAnyDiscomfort(entity.getAnyDiscomfort()); + dto.setTreatmentCompleted(entity.getTreatmentCompleted()); + dto.setActualTreatmentCompletionDate(entity.getActualTreatmentCompletionDate()); + dto.setTreatmentOutcome(entity.getTreatmentOutcome()); + dto.setDateOfDeath(entity.getDateOfDeath()); + dto.setPlaceOfDeath(entity.getPlaceOfDeath()); + dto.setReasonForDeath(entity.getReasonForDeath()); + dto.setReasonForNotCompleting(entity.getReasonForNotCompleting()); + + return dto; + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java new file mode 100644 index 00000000..156de1d8 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -0,0 +1,186 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.iemr.UwinSession; +import com.iemr.flw.dto.iemr.UwinSessionRequestDTO; +import com.iemr.flw.dto.iemr.UwinSessionResponseDTO; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.StateCode; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +import com.iemr.flw.repo.iemr.UwinSessionRepository; +import com.iemr.flw.service.UwinSessionService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; + +@Service +@RequiredArgsConstructor +public class UwinSessionServiceImpl implements UwinSessionService { + @Autowired + private UwinSessionRepository repo; + private final ObjectMapper objectMapper = new ObjectMapper(); + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + + + @Override + public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exception { + + // 🧩 Validations + + Timestamp sessionDate = req.getDate(); // Timestamp from request + Timestamp now = Timestamp.from(Instant.now()); + +// 1️⃣ Future date check + if (sessionDate.after(now)) { + throw new RuntimeException("Date cannot be in future"); + } + +// 2️⃣ Backdate beyond 2 months + LocalDateTime twoMonthsAgo = LocalDateTime.now().minusMonths(2); + if (sessionDate.toLocalDateTime().isBefore(twoMonthsAgo)) { + throw new RuntimeException("Backdate not allowed beyond 2 months"); + } + +// 3️⃣ Participants check + if (req.getParticipants() == null || req.getParticipants() < 0 || req.getParticipants() > 999) { + throw new RuntimeException("Participants count must be between 0–999"); + } + + + + // 🧩 Save record + UwinSession session = new UwinSession(); + session.setAshaId(req.getAshaId()); + session.setDate(req.getDate()); + session.setPlace(req.getPlace()); + session.setSessionDate(req.getDate()); + session.setParticipants(req.getParticipants()); + session.setCreatedBy(req.getCreatedBy()); + if (req.getAttachments() != null && req.getAttachments().length > 0) { + List base64Images = Arrays.stream(req.getAttachments()) + .filter(file -> !file.isEmpty()) + .map(file -> { + try { + return Base64.getEncoder().encodeToString(file.getBytes()); + } catch (IOException e) { + throw new RuntimeException("Error converting image to Base64", e); + } + }) + .collect(Collectors.toList()); + + String imagesJson = objectMapper.writeValueAsString(base64Images); + session.setAttachmentsJson(imagesJson); + } + + repo.save(session); + checkAndAddIncentive(session); + + // 🎯 Prepare response + UwinSessionResponseDTO dto = new UwinSessionResponseDTO(); + dto.setId(session.getId()); + dto.setAshaId(session.getAshaId()); + dto.setDate(session.getDate()); + dto.setPlace(session.getPlace()); + dto.setParticipants(session.getParticipants()); + dto.setAttachments(Collections.singletonList(session.getAttachmentsJson())); + + return dto; + } + + @Override + public List getSessionsByAsha(Integer ashaId) throws Exception { + List sessions = repo.findByAshaId(ashaId); + return sessions.stream().map(s -> { + UwinSessionResponseDTO dto = new UwinSessionResponseDTO(); + dto.setId(s.getId()); + dto.setAshaId(s.getAshaId()); + dto.setDate(s.getDate()); + dto.setPlace(s.getPlace()); + dto.setParticipants(s.getParticipants()); + try { + List att = objectMapper.readValue(s.getAttachmentsJson(), new TypeReference>() { + }); + dto.setAttachments(att); + } catch (Exception e) { + dto.setAttachments(List.of()); + } + + return dto; + }).collect(Collectors.toList()); + } + + private void checkAndAddIncentive(UwinSession session) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_MOBILIZATION_SESSIONS", GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_MOBILIZATION_SESSIONS", GroupName.ACTIVITY.getDisplayName()); + Integer stateId = userRepo.getUserRole(session.getAshaId()).get(0).getStateId(); + + if(incentiveActivityAM!=null && stateId!=null && stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(), session.getDate(), 0L,session.getAshaId()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivityAM.getId()); + record.setCreatedDate(session.getDate()); + record.setCreatedBy(session.getCreatedBy()); + record.setStartDate(session.getDate()); + record.setEndDate(session.getDate()); + record.setUpdatedDate(session.getDate()); + record.setUpdatedBy(session.getCreatedBy()); + record.setBenId(0L); + record.setAshaId(session.getAshaId()); + record.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + if(session.getAttachmentsJson()!=null){ + record.setIsEligible(true); + recordRepo.save(record); + + }else { + record.setIsEligible(false); + + } + + } + } + + if(incentiveActivityCH!=null && stateId!=null && stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(incentiveActivityCH.getId(), session.getDate(), 0L,session.getAshaId()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivityCH.getId()); + record.setCreatedDate(session.getDate()); + record.setCreatedBy(session.getCreatedBy()); + record.setStartDate(session.getDate()); + record.setEndDate(session.getDate()); + record.setUpdatedDate(session.getDate()); + record.setUpdatedBy(session.getCreatedBy()); + record.setBenId(0L); + record.setAshaId(session.getAshaId()); + record.setAmount(Long.valueOf(incentiveActivityCH.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + } + } + + + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java new file mode 100644 index 00000000..c64654d3 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -0,0 +1,326 @@ +/* +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution +* +* Copyright (C) "Piramal Swasthya Management and Research Institute" +* +* This file is part of AMRIT. +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see https://www.gnu.org/licenses/. +* +/* +* AMRIT – Accessible Medical Records via Integrated Technology +*/ +package com.iemr.flw.service.impl; + +import com.iemr.flw.controller.CoupleController; +import com.iemr.flw.domain.iemr.*; +import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.VillageLevelFormService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +@Service +public class VillageLevelFormServiceImpl implements VillageLevelFormService { + private final Logger logger = LoggerFactory.getLogger(VillageLevelFormServiceImpl.class); + + @Autowired + private IncentiveRecordRepo recordRepo; + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private PHCReviewFormRepo phcReviewFormRepo; + + @Autowired + private DewormingFormRepo dewormingFormRepo; + + @Autowired + private VhndRepo vhndRepo; + + @Autowired + private VhncFormRepo vhncFormRepo; + + @Autowired + private AHDFormRepo ahdFormRepo; + + + @Override + public Boolean saveForm(VhndDto dto) { + if (dto == null || dto.getEntries() == null) { + return false; + } + for (VHNDFormDTO vhndFormDTO : dto.getEntries()) { + saveVhndFormData(vhndFormDTO, dto.getUserId()); + + } + return true; + } + + @Override + public Boolean saveVhncForm(VhncDto dto) { + if (dto == null || dto.getEntries() == null) { + return false; + } + for (VhncFormDTO vhncFormDTO : dto.getEntries()) { + saveVhncFormData(vhncFormDTO, dto.getUserId()); + } + return true; + } + + + @Override + public Boolean savePhcForm(PhcReviewMeetingDTO dto) { + if (dto == null || dto.getEntries() == null) { + return false; + } + for (PhcReviewMeetingFormDTO phcReviewMeetingDTO : dto.getEntries()) { + savePhcForm(phcReviewMeetingDTO, dto.getUserId()); + } + return true; + } + + @Override + public Boolean saveAhdForm(AhdMeetingDto dto) { + if (dto == null || dto.getEntries() == null) { + return false; + } + for (AhDMeetingFormDTO ahDMeetingFormDTO : dto.getEntries()) { + saveAhdForm(ahDMeetingFormDTO, dto.getUserId()); + } + return true; + } + + @Override + public Boolean saveDewormingForm(DewormingDto dto) { + for (DewormingFormDTO dewormingFormDTO : dto.getEntries()) { + saveDewormingForm(dewormingFormDTO, dto.getUserId()); + } + return true; + } + + private Boolean saveVhncFormData(VhncFormDTO vhncFormDTO, Integer userID) { + VhncForm vhncForm = new VhncForm(); + vhncForm.setUserId(Long.valueOf(userID)); + vhncForm.setVhncDate(vhncFormDTO.getVhncDate()); + vhncForm.setImage2(vhncFormDTO.getImage2()); + vhncForm.setImage1(vhncFormDTO.getImage1()); + vhncForm.setPlace(vhncFormDTO.getPlace()); + vhncForm.setVillageName(vhncFormDTO.getVillageName()); + vhncForm.setAnm(vhncFormDTO.getAnm()); + vhncForm.setAww(vhncFormDTO.getAww()); + vhncForm.setNoOfPragnentWoment(vhncFormDTO.getNoOfPragnentWoment()); + vhncForm.setNoOfLactingMother(vhncFormDTO.getNoOfLactingMother()); + vhncForm.setNoOfCommittee(vhncFormDTO.getNoOfCommittee()); + vhncForm.setFollowupPrevius(vhncFormDTO.getFollowupPrevius()); + + vhncForm.setNoOfBeneficiariesAttended(vhncFormDTO.getNoOfBeneficiariesAttended()); + + vhncForm.setFormType("VHNC"); + vhncFormRepo.save(vhncForm); + checkAndAddIncentives(vhncForm.getVhncDate(), Math.toIntExact(vhncForm.getUserId()), "VHSNC_MEETING", vhncForm.getCreatedBy()); + + return true; + } + + + private Boolean savePhcForm(PhcReviewMeetingFormDTO dto, Integer userID) { + PHCReviewForm phcReviewForm = new PHCReviewForm(); + phcReviewForm.setUserId(Long.valueOf(userID)); + phcReviewForm.setPhcReviewDate(dto.getPhcReviewDate()); + phcReviewForm.setPlace(dto.getPlace()); + phcReviewForm.setNoOfBeneficiariesAttended(dto.getNoOfBeneficiariesAttended()); + phcReviewForm.setImage1(dto.getImage1()); + phcReviewForm.setVillageName(dto.getVillageName()); + phcReviewForm.setMitaninActivityCheckList(dto.getMitaninActivityCheckList()); + phcReviewForm.setPlaceId(dto.getPlaceId()); + phcReviewForm.setMitaninHistory(dto.getMitaninHistory()); + phcReviewForm.setImage2(dto.getImage2()); + phcReviewForm.setFormType("PHC"); + phcReviewFormRepo.save(phcReviewForm); + checkAndAddIncentives(phcReviewForm.getPhcReviewDate(), Math.toIntExact(phcReviewForm.getUserId()), "CLUSTER_MEETING", phcReviewForm.getCreatedBy()); + + return true; + } + + private Boolean saveAhdForm(AhDMeetingFormDTO dto, Integer userID) { + AHDForm ahdForm = new AHDForm(); + ahdForm.setUserId(Long.valueOf(userID)); + ahdForm.setMobilizedForAHD(dto.getMobilizedForAHD()); + ahdForm.setAhdPlace(dto.getAhdPlace()); + ahdForm.setAhdDate(dto.getAhdDate()); + ahdForm.setImage1(dto.getImage1()); + ahdForm.setImage2(dto.getImage2()); + ahdForm.setFormType("AHD"); + ahdFormRepo.save(ahdForm); + if (Objects.equals(dto.getMobilizedForAHD(), "Yes")) { + checkAndAddIncentives(ahdForm.getAhdDate(), Math.toIntExact(ahdForm.getUserId()), "AH_MOBILIZE", ahdForm.getCreatedBy()); + + } + + return true; + } + + private Boolean saveDewormingForm(DewormingFormDTO dto, Integer userID) { + DewormingForm dewormingForm = new DewormingForm(); + dewormingForm.setUserId(Long.valueOf(userID)); + dewormingForm.setDewormingDone(dto.getDewormingDone()); + dewormingForm.setDewormingDate(dto.getDewormingDate()); + dewormingForm.setDewormingLocation(dto.getDewormingLocation()); + dewormingForm.setAgeGroup(dto.getAgeGroup()); + dewormingForm.setImage1(dto.getImage1()); + dewormingForm.setImage2(dto.getImage2()); + dewormingForm.setFormType("Deworming"); + dewormingFormRepo.save(dewormingForm); + if (Objects.equals(dewormingForm.getDewormingDone(), "Yes")) { + checkAndAddIncentives(dewormingForm.getDewormingDate(), Math.toIntExact(dewormingForm.getUserId()), "NATIONAL_DEWORMING_DAY", dewormingForm.getCreatedBy()); + + } + return true; + } + + + private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { + VHNDForm vhndForm = new VHNDForm(); + vhndForm.setUserId(userID); + vhndForm.setVhndDate(vhndFormDTO.getVhndDate()); + vhndForm.setImage2(vhndFormDTO.getImage2()); + vhndForm.setImage1(vhndFormDTO.getImage1()); + vhndForm.setPlace(vhndFormDTO.getPlace()); + vhndForm.setNoOfBeneficiariesAttended(vhndFormDTO.getNoOfBeneficiariesAttended()); + vhndForm.setPregnantWomenAnc(vhndFormDTO.getPregnantWomenAnc()); + vhndForm.setLactatingMothersPnc(vhndFormDTO.getLactatingMothersPnc()); + vhndForm.setChildrenImmunization(vhndFormDTO.getChildrenImmunization()); + vhndForm.setSelectAllEducation(vhndFormDTO.getSelectAllEducation()); + vhndForm.setKnowledgeBalancedDiet(vhndFormDTO.getKnowledgeBalancedDiet()); + vhndForm.setCareDuringPregnancy(vhndFormDTO.getCareDuringPregnancy()); + vhndForm.setImportanceBreastfeeding(vhndFormDTO.getImportanceBreastfeeding()); + vhndForm.setComplementaryFeeding(vhndFormDTO.getComplementaryFeeding()); + vhndForm.setHygieneSanitation(vhndFormDTO.getHygieneSanitation()); + vhndForm.setFamilyPlanningHealthcare(vhndFormDTO.getFamilyPlanningHealthcare()); + vhndForm.setFormType("VHND"); + vhndRepo.save(vhndForm); + checkAndAddIncentives(vhndForm.getVhndDate(), vhndForm.getUserId(), "VHND_PARTICIPATION", vhndForm.getCreatedBy()); + return true; + + + } + + + @Override + public List getAll(GetVillageLevelRequestHandler getVillageLevelRequestHandler) { + if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "VHND")) { + return vhndRepo.findAll().stream() + .filter(vhndForm -> Objects.equals(vhndForm.getUserId().toString(), getVillageLevelRequestHandler.getUserId().toString())) + .collect(Collectors.toList()); + + } else if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "VHNC")) { + return vhncFormRepo.findAll().stream() + .filter(vhncForm -> Objects.equals(vhncForm.getUserId().toString(), getVillageLevelRequestHandler.getUserId().toString())) + .collect(Collectors.toList()); + + } else if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "PHC")) { + return phcReviewFormRepo.findAll().stream() + .filter(phcReviewForm -> Objects.equals(phcReviewForm.getUserId().toString(), getVillageLevelRequestHandler.getUserId().toString())) + .collect(Collectors.toList()); + + } else if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "Deworming")) { + return dewormingFormRepo.findAll().stream() + .filter(dewormingForm -> Objects.equals(dewormingForm.getUserId().toString(), getVillageLevelRequestHandler.getUserId().toString())) + .collect(Collectors.toList()); + + } else if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "AHD")) { + return ahdFormRepo.findAll().stream() + .filter(ahdForm -> Objects.equals(ahdForm.getUserId().toString(), getVillageLevelRequestHandler.getUserId().toString())) + .collect(Collectors.toList()); + } + + return Collections.emptyList(); // In case no condition matches + + } + + + private void checkAndAddIncentives(String date, Integer userID, String formType, String createdBY) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + // Parse to LocalDate + LocalDate localDate = LocalDate.parse(date, formatter); + + // Convert to Timestamp at start of day (00:00:00) + Timestamp timestamp = Timestamp.valueOf(localDate.atStartOfDay()); + logger.info("timestamp" + timestamp); + + IncentiveActivity villageFormEntryActivityAM; + IncentiveActivity villageFormEntryActivityCH; + villageFormEntryActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup(formType, GroupName.CHILD_HEALTH.getDisplayName()); + villageFormEntryActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup(formType, GroupName.ACTIVITY.getDisplayName()); + + if (villageFormEntryActivityAM != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(villageFormEntryActivityAM.getId(), timestamp, 0L,userID); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(villageFormEntryActivityAM.getId()); + record.setCreatedDate(timestamp); + record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setStartDate(timestamp); + record.setEndDate(timestamp); + record.setUpdatedDate(timestamp); + record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setAshaId(userID); + record.setBenId(0L); + record.setAmount(Long.valueOf(villageFormEntryActivityAM.getRate())); + recordRepo.save(record); + + } + } + + if (villageFormEntryActivityCH != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(villageFormEntryActivityCH.getId(), timestamp, 0L,userID); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(villageFormEntryActivityCH.getId()); + record.setCreatedDate(timestamp); + record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setStartDate(timestamp); + record.setEndDate(timestamp); + record.setBenId(0L); + record.setUpdatedDate(timestamp); + record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setAshaId(userID); + record.setAmount(Long.valueOf(villageFormEntryActivityCH.getRate())); + recordRepo.save(record); + + } + } + } + + +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/utils/CommonMain.java b/src/main/java/com/iemr/flw/utils/CommonMain.java index 3690fa14..bc03f097 100644 --- a/src/main/java/com/iemr/flw/utils/CommonMain.java +++ b/src/main/java/com/iemr/flw/utils/CommonMain.java @@ -23,4 +23,5 @@ public RedisHttpSessionConfiguration redisSession() { public RedisStorage redisStorage() { return new RedisStorage(); } + } diff --git a/src/main/java/com/iemr/flw/utils/CookieUtil.java b/src/main/java/com/iemr/flw/utils/CookieUtil.java index 937755dc..991f78b2 100644 --- a/src/main/java/com/iemr/flw/utils/CookieUtil.java +++ b/src/main/java/com/iemr/flw/utils/CookieUtil.java @@ -40,4 +40,4 @@ public static String getJwtTokenFromCookie(HttpServletRequest request) { return Arrays.stream(request.getCookies()).filter(cookie -> "Jwttoken".equals(cookie.getName())) .map(Cookie::getValue).findFirst().orElse(null); } -} +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/utils/DateUtil.java b/src/main/java/com/iemr/flw/utils/DateUtil.java new file mode 100644 index 00000000..ff095511 --- /dev/null +++ b/src/main/java/com/iemr/flw/utils/DateUtil.java @@ -0,0 +1,31 @@ +package com.iemr.flw.utils; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +public class DateUtil { + private static final DateTimeFormatter INPUT_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + private static final DateTimeFormatter OUTPUT_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + public static Timestamp convertToTimestamp(String inputDate) { + try { + if (inputDate == null || inputDate.isEmpty()) return null; + + // Parse "14-10-2025" → LocalDate + LocalDate localDate = LocalDate.parse(inputDate, INPUT_FORMAT); + + // Convert to LocalDateTime (midnight) + LocalDateTime localDateTime = localDate.atStartOfDay(); + + // Convert to SQL Timestamp + return Timestamp.valueOf(localDateTime); + } catch (Exception e) { + System.err.println("❌ Date parsing failed for: " + inputDate + " | " + e.getMessage()); + return null; + } + } +} + diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 944c82a0..ae3f1985 100644 --- a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java @@ -87,7 +87,7 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { return true; // Valid userId and JWT token } catch (Exception e) { logger.error("Validation failed: " + e.getMessage(), e); - throw new IEMRException("Validation error: " + e.getMessage(), e); + throw new IEMRException("Validation error: Authentication failed", e); } } @@ -129,4 +129,4 @@ private M_User fetchUserFromDB(String userId) { return null; } -} +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index 7cc17200..9cf022f0 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -89,7 +89,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo if (jwtToken != null) { logger.info("Validating JWT token from cookie"); - if (jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtFromCookie)) { + if (jwtAuthenticationUtil.validateUserIdAndJwtToken(jwtToken)) { AuthorizationHeaderRequestWrapper authorizationHeaderRequestWrapper = new AuthorizationHeaderRequestWrapper( request, ""); @@ -116,7 +116,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } catch (Exception e) { logger.error("Authorization error: ", e); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: " + e.getMessage()); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization error: Authentication failed"); } } @@ -152,7 +152,9 @@ private boolean shouldSkipPath(String path, String contextPath) { return path.equals(contextPath + "/user/userAuthenticate") || path.equalsIgnoreCase(contextPath + "/user/logOutUserFromConcurrentSession") || path.startsWith(contextPath + "/swagger-ui") || path.startsWith(contextPath + "/v3/api-docs") - || path.startsWith(contextPath + "/public"); + || path.startsWith(contextPath + "/public") + || path.equals(contextPath + "/health") + || path.equals(contextPath + "/version"); } private String getJwtTokenFromCookies(HttpServletRequest request) { diff --git a/src/main/java/com/iemr/flw/utils/JwtUtil.java b/src/main/java/com/iemr/flw/utils/JwtUtil.java index 0e0a9345..7107d738 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtUtil.java @@ -4,6 +4,7 @@ import java.util.function.Function; import javax.crypto.SecretKey; +import com.google.gson.JsonElement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -19,10 +20,10 @@ public class JwtUtil { @Value("${jwt.secret}") private String SECRET_KEY; - + private String userName; + @Autowired private TokenDenylist tokenDenylist; - // Generate a key using the secret private SecretKey getSigningKey() { if (SECRET_KEY == null || SECRET_KEY.isEmpty()) { @@ -39,14 +40,14 @@ public Claims validateToken(String token) { .build() .parseSignedClaims(token) .getPayload(); - + String jti = claims.getId(); - + // Check if token is denylisted (only if jti exists) if (jti != null && tokenDenylist.isTokenDenylisted(jti)) { return null; } - + return claims; } catch (Exception e) { return null; // Handle token parsing/validation errors @@ -86,5 +87,16 @@ private Claims extractAllClaims(String token) { .verifyWith(getSigningKey()) .build() .parseSignedClaims(token) - .getPayload(); } + .getPayload(); + } + + public String getUserNameFromStorage() { + return userName; + + } + + public void setUserNameFromStorage(String loginUserName) { + this.userName = loginUserName; + + } } diff --git a/src/main/java/com/iemr/flw/utils/LocalDateAdapter.java b/src/main/java/com/iemr/flw/utils/LocalDateAdapter.java new file mode 100644 index 00000000..d0081c29 --- /dev/null +++ b/src/main/java/com/iemr/flw/utils/LocalDateAdapter.java @@ -0,0 +1,20 @@ +package com.iemr.flw.utils; + +import com.google.gson.*; +import java.lang.reflect.Type; +import java.time.LocalDate; + +public class LocalDateAdapter + implements JsonSerializer, JsonDeserializer { + + @Override + public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.toString()); // yyyy-MM-dd + } + + @Override + public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return LocalDate.parse(json.getAsString()); + } +} diff --git a/src/main/java/com/iemr/flw/utils/PathTraversalFilter.java b/src/main/java/com/iemr/flw/utils/PathTraversalFilter.java new file mode 100644 index 00000000..e63012bc --- /dev/null +++ b/src/main/java/com/iemr/flw/utils/PathTraversalFilter.java @@ -0,0 +1,56 @@ +package com.iemr.flw.utils; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; + +@Component +@Order(1) +public class PathTraversalFilter implements Filter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) + throws IOException, ServletException { + + HttpServletRequest request = (HttpServletRequest) servletRequest; + HttpServletResponse response = (HttpServletResponse) servletResponse; + + String uri = request.getRequestURI(); + + // Decode once to catch %2e%2e and similar encoded variants + String decodedUri = URLDecoder.decode(uri, StandardCharsets.UTF_8); + + if (containsTraversalPattern(uri) || containsTraversalPattern(decodedUri)) { + logger.warn("Path traversal attempt blocked: {}", uri); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request path"); + return; + } + + chain.doFilter(servletRequest, servletResponse); + } + + private boolean containsTraversalPattern(String path) { + if (path == null) return false; + String normalized = path.toLowerCase(); + return normalized.contains("../") + || normalized.contains("..\\") + || normalized.contains("..;") + || normalized.contains("%2e%2e") + || normalized.contains("%252e") // double-encoded + || normalized.endsWith(".."); + } +} diff --git a/src/main/java/com/iemr/flw/utils/PaymentParam.java b/src/main/java/com/iemr/flw/utils/PaymentParam.java index f8da0057..914f764a 100644 --- a/src/main/java/com/iemr/flw/utils/PaymentParam.java +++ b/src/main/java/com/iemr/flw/utils/PaymentParam.java @@ -3,8 +3,13 @@ public enum PaymentParam { PER_MONTH, PER_CASE, + PER_CHILD, + PER_MEETING, FIRST_DOSE_PER_ASHA, SECOND_DOSE_PER_ASHA, THIRD_DOSE_PER_ASHA, FOURTH_DOSE_PER_ASHA, + PER_NET, + PER_VISIT, + PER_YEAR, } diff --git a/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java b/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java index f847c2e1..884d9905 100644 --- a/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java +++ b/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java @@ -25,6 +25,7 @@ import com.iemr.flw.utils.sessionobject.SessionObject; import com.iemr.flw.utils.validator.Validator; +import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -36,6 +37,7 @@ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; +import java.nio.charset.StandardCharsets; import javax.ws.rs.core.MediaType; @@ -91,17 +93,34 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons if (remoteAddress == null || remoteAddress.trim().length() == 0) { remoteAddress = request.getRemoteAddr(); } - validator.checkKeyExists(authorization, remoteAddress); +// validator.checkKeyExists(authorization, remoteAddress); break; } } catch (Exception e) { - OutputResponse output = new OutputResponse(); - output.setError(e); - response.setContentType(MediaType.APPLICATION_JSON); + logger.error("Authorization failed: {}", e.getMessage(), e); - response.setContentLength(output.toString().length()); - response.setHeader("Access-Control-Allow-Origin", "*"); - response.getOutputStream().print(output.toString()); + String errorMessage = e.getMessage(); + if (errorMessage == null || errorMessage.trim().isEmpty()) { + errorMessage = "Unauthorized access or session expired."; + } + + String jsonErrorResponse = "{" + + "\"status\": \"Unauthorized\"," + + "\"statusCode\": 401," + + "\"errorMessage\": \"" + errorMessage.replace("\"", "\\\"") + "\"" + + "}"; + + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 + response.setContentType(MediaType.APPLICATION_JSON); + response.setHeader("Access-Control-Allow-Origin", "*"); + + // Better to use getBytes().length for accurate byte size + byte[] responseBytes = jsonErrorResponse.getBytes(StandardCharsets.UTF_8); + response.setContentLength(responseBytes.length); + + ServletOutputStream out = response.getOutputStream(); + out.write(responseBytes); + out.flush(); status = false; } } diff --git a/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java b/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java index 873a6fc9..0a279319 100644 --- a/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java +++ b/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java @@ -4,13 +4,25 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import com.iemr.flw.domain.iemr.M_User; @Configuration public class RedisConfig { @Bean - public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(connectionFactory); - return template; - } + public RedisTemplate redisTemplate(RedisConnectionFactory factory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(factory); + + // Use StringRedisSerializer for keys (userId) + template.setKeySerializer(new StringRedisSerializer()); + + // Use Jackson2JsonRedisSerializer for values (Users objects) + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(M_User.class); + template.setValueSerializer(serializer); + + return template; + } } diff --git a/src/main/java/com/iemr/flw/utils/redis/RedisStorage.java b/src/main/java/com/iemr/flw/utils/redis/RedisStorage.java index 5995b7cc..8495bb8f 100644 --- a/src/main/java/com/iemr/flw/utils/redis/RedisStorage.java +++ b/src/main/java/com/iemr/flw/utils/redis/RedisStorage.java @@ -1,8 +1,8 @@ /* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution * -* Copyright (C) "Piramal Swasthya Management and Research Institute" +* Copyright (C) "Piramal Swasthya Management and Research Institute" * * This file is part of AMRIT. * diff --git a/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java b/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java index 9c8e4a03..d84a1684 100644 --- a/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java +++ b/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java @@ -24,9 +24,12 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.config.ConfigProperties; import com.iemr.flw.utils.redis.RedisSessionException; import com.iemr.flw.utils.redis.RedisStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -34,6 +37,8 @@ public class SessionObject { private RedisStorage objectStore; + @Autowired + private JwtUtil jwtUtil; @Autowired public void setObjectStore(RedisStorage objectStore) { this.objectStore = objectStore; @@ -47,6 +52,8 @@ public SessionObject() { private boolean extendExpirationTime; private int sessionExpiryTime; + Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName()); + public String getSessionObject(String key) throws RedisSessionException { Boolean extendExpirationTime = ConfigProperties.getExtendExpiryTime(); Integer sessionExpiryTime = ConfigProperties.getSessionExpiryTime(); @@ -74,6 +81,7 @@ private void updateConcurrentSessionObject(String key, String value, Boolean ext JsonElement jsnElmnt = jsnParser.parse(value); jsnOBJ = jsnElmnt.getAsJsonObject(); if (jsnOBJ.has("userName") && jsnOBJ.get("userName") != null) { + jwtUtil.setUserNameFromStorage(jsnOBJ.get("userName").getAsString()); objectStore.updateObject(jsnOBJ.get("userName").getAsString().trim().toLowerCase(), key, extendExpirationTime, sessionExpiryTime); } diff --git a/src/main/java/com/iemr/flw/utils/validator/Validator.java b/src/main/java/com/iemr/flw/utils/validator/Validator.java index e021eff1..1068c3f4 100644 --- a/src/main/java/com/iemr/flw/utils/validator/Validator.java +++ b/src/main/java/com/iemr/flw/utils/validator/Validator.java @@ -1,8 +1,8 @@ /* -* AMRIT – Accessible Medical Records via Integrated Technology -* Integrated EHR (Electronic Health Records) Solution +* AMRIT – Accessible Medical Records via Integrated Technology +* Integrated EHR (Electronic Health Records) Solution * -* Copyright (C) "Piramal Swasthya Management and Research Institute" +* Copyright (C) "Piramal Swasthya Management and Research Institute" * * This file is part of AMRIT. * diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 5b7f08cf..034fbcc4 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,9 @@ spring.main.banner-mode=off spring.data.jpa.repositories.enabled=true -#spring.jpa.hibernate.ddl-auto=none +spring.jpa.hibernate.ddl-auto=create + +# TM Config # Naming strategies spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl @@ -11,9 +13,6 @@ spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect #Below lines are added for security reasons -spring.session.store-type=redis -spring.redis.password= -spring.redis.port=6379 ## Below values are needed for extending the expiry time and extend expiry time. iemr.extend.expiry.time=true @@ -44,10 +43,32 @@ get-HRP-Status=ANC/getHRPStatus #Get Beneficiary ABHA getHealthID=healthID/getBenhealthID +### SMS Gateway URL details +sms-message-type=SERVICE_EXPLICIT +sms-entityid=1201161708885589464 +# FHIR Config +#fhir-url=/fhirapi-v1.0 +#server.port=8082 +# TM Config +#tm-url=/tmapi-v1.0 +sms-sender-number = +sms-gateway-url= +jakarta.persistence.schema-generation.database.action=create +spring.jpa.defer-datasource-initialization=true +# FHIR Config +fhir-url= +# TM Config +tm-url= +springdoc.api-docs.enabled=true +springdoc.swagger-ui.enabled=true +spring.redis.host=localhost +spring.main.allow-bean-definition-overriding=true +spring.redis.password= +spring.redis.port=6379 - +notificationurl=https://uatamrit.piramalswasthya.org/common-api/firebaseNotification/sendNotification