From 085e4a701b43ee1a2988f615ab90cafd270df8ad Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 17:05:41 +0530 Subject: [PATCH 001/450] update CI properties --- src/main/environment/common_docker.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index cb3a613ab..85b7fe01f 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -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=true -springdoc.swagger-ui.enabled=true +springdoc.api-docs.enabled= ${SWAGGER_UI_ENABLED} +springdoc.swagger-ui.enabled= ${SWAGGER_UI_ENABLED} #ELK logging file name logging.path=logs/ From 01b45d331876abec75660bf4ef4fdae83c5abb37 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 17:19:28 +0530 Subject: [PATCH 002/450] update version in pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 512a160bb..d87cbdecc 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.10.0 + 3.7.0 war FLW-API From 92f5e2a7f781916547475a2f351325ad4628f2ff Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 18:44:41 +0530 Subject: [PATCH 003/450] update docker file --- src/main/environment/common_docker.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 85b7fe01f..149a25cef 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -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= ${SWAGGER_UI_ENABLED} -springdoc.swagger-ui.enabled= ${SWAGGER_UI_ENABLED} +springdoc.api-docs.enabled=${SWAGGER_UI_ENABLED} +springdoc.swagger-ui.enabled=${SWAGGER_UI_ENABLED} #ELK logging file name logging.path=logs/ From d2297b4d69113029581d3456e4d92d91d84a4037 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 19:01:49 +0530 Subject: [PATCH 004/450] update properties file file --- src/main/environment/common_ci.properties | 2 -- src/main/environment/common_docker.properties | 3 +-- src/main/resources/application.properties | 4 ++-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index ba6a855d2..44ef75ec8 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -16,8 +16,6 @@ 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_UI_ENABLED@ -springdoc.swagger-ui.enabled=@env.SWAGGER_UI_ENABLED@ #ELK logging file name logging.path=logs/ diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 149a25cef..313e1fb23 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -15,8 +15,7 @@ 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=${SWAGGER_UI_ENABLED} -springdoc.swagger-ui.enabled=${SWAGGER_UI_ENABLED} + #ELK logging file name logging.path=logs/ diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8546550db..3b106344b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -63,8 +63,8 @@ fhir-url= # TM Config tm-url= -springdoc.api-docs.enabled=true -springdoc.swagger-ui.enabled=true +springdoc.api-docs.enabled=false +springdoc.swagger-ui.enabled=false spring.redis.host=localhost spring.main.allow-bean-definition-overriding=true spring.redis.password= From c86370147514b0877a44e3503b9874391ace8545 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 19:03:31 +0530 Subject: [PATCH 005/450] update properties file file --- src/main/environment/common_ci.properties | 1 + src/main/environment/common_docker.properties | 1 + src/main/resources/application.properties | 1 + 3 files changed, 3 insertions(+) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 44ef75ec8..b1ceae562 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -17,6 +17,7 @@ secondary.datasource.url=@env.DATABASE_IDENTITY_URL@ secondary.datasource.driver-class-name=com.mysql.jdbc.Driver + #ELK logging file name logging.path=logs/ logging.file.name=@env.FLW_API_LOGGING_FILE_NAME@ diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 313e1fb23..46022b879 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -17,6 +17,7 @@ secondary.datasource.driver-class-name=com.mysql.jdbc.Driver + #ELK logging file name logging.path=logs/ logging.file.name=${FLW_API_LOGGING_FILE_NAME} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3b106344b..ab7eae2a6 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -65,6 +65,7 @@ fhir-url= tm-url= springdoc.api-docs.enabled=false springdoc.swagger-ui.enabled=false + spring.redis.host=localhost spring.main.allow-bean-definition-overriding=true spring.redis.password= From 09ad4162cba43d35bc14f0251d04ae829f887054 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Dec 2025 21:55:30 +0530 Subject: [PATCH 006/450] Update incentive for missing supporting documents --- .../flw/controller/IncentiveController.java | 45 +++++-- .../flw/controller/MaaMeetingController.java | 48 +++++++- .../domain/iemr/IncentiveActivityRecord.java | 6 + .../domain/iemr/IncentivePendingActivity.java | 39 ++++++ .../flw/dto/iemr/MaaMeetingRequestDTO.java | 1 + .../iemr/flw/dto/iemr/PendingActivityDTO.java | 14 +++ .../IncentivePendingActivityRepository.java | 14 +++ .../iemr/flw/service/IncentiveService.java | 3 + .../iemr/flw/service/MaaMeetingService.java | 111 ++++++++++++++++-- .../service/impl/IncentiveServiceImpl.java | 39 +++++- 10 files changed, 292 insertions(+), 28 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index 670d611be..c76d26ae0 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.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 com.iemr.flw.service.IncentiveService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; @@ -29,8 +30,8 @@ public class IncentiveController { 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, HttpServletRequest request) { + @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"); @@ -50,9 +51,9 @@ 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 { @@ -61,7 +62,7 @@ public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentive // add logic for different state or district if (incentiveRequestDTO != null) { String s = incentiveService.getIncentiveMaster(incentiveRequestDTO); - logger.info("All incentives"+s); + logger.info("All incentives" + s); if (s != null) response.setResponse(s); @@ -77,13 +78,10 @@ public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentive } - - - @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 { @@ -91,7 +89,30 @@ 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); + 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(); + } + + @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 @@ -103,6 +124,8 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request 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 index d9bcdb1b2..0c73d46e5 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -49,8 +49,54 @@ public ResponseEntity saveMeeting( dto.setAshaId(Integer.parseInt(ashaId)); dto.setCreatedBY(createdBy); dto.setMeetingImages(meetingImages != null ? meetingImages.toArray(new MultipartFile[0]) : null); + if (dto != null) { + service.saveMeeting(dto); - service.saveMeeting(dto); + } + return ResponseEntity.ok("Saved Successfully"); + } catch (Exception e) { + 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()); 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 5b921bb47..f4adf8df3 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 000000000..870a48f53 --- /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/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java index c08c8d64e..9d4c19b1d 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -8,6 +8,7 @@ @Data public class MaaMeetingRequestDTO { + private Long id; private LocalDate meetingDate; private String place; private Integer participants; 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 000000000..4d8dbd99e --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -0,0 +1,14 @@ +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; +} 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 000000000..bb53cb5ba --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java @@ -0,0 +1,14 @@ +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 findByUserIdAndModuleNameActivityId(Integer userId, String moduleName,Long activityId); + +} diff --git a/src/main/java/com/iemr/flw/service/IncentiveService.java b/src/main/java/com/iemr/flw/service/IncentiveService.java index ab49a0cd4..d6bb55507 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 index d5f4c5bdf..2c48df267 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -3,28 +3,20 @@ 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.MaaMeeting; -import com.iemr.flw.domain.iemr.UwinSession; +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.IncentiveRecordRepo; -import com.iemr.flw.repo.iemr.IncentivesRepo; -import com.iemr.flw.repo.iemr.MaaMeetingRepository; -import com.iemr.flw.repo.iemr.UserServiceRoleRepo; +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.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; @Service @@ -40,6 +32,9 @@ public class MaaMeetingService { private final MaaMeetingRepository repository; private final ObjectMapper objectMapper; + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + public MaaMeetingService(MaaMeetingRepository repository, ObjectMapper objectMapper) { this.repository = repository; this.objectMapper = objectMapper; @@ -69,12 +64,61 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { 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 { @@ -107,6 +151,29 @@ public List getAllMeetings(GetBenRequestHandler getBenReq 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()); @@ -135,10 +202,30 @@ record = new IncentiveActivityRecord(); 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/impl/IncentiveServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java index 6a42b76d9..9d5ede87b 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -6,22 +6,22 @@ import com.iemr.flw.domain.iemr.IncentiveActivity; import com.iemr.flw.domain.iemr.IncentiveActivityLangMapping; import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.iemr.IncentivePendingActivity; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; 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.IncentiveActivityLangMappingRepo; -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.*; 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.math.BigInteger; import java.sql.Timestamp; @@ -50,9 +50,15 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private JwtUtil jwtUtil; + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + @Autowired private UserServiceRoleRepo userRepo; + @Autowired + private MaaMeetingService maaMeetingService; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -187,6 +193,31 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { 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.findByUserIdAndModuleNameActivityId(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 checkMonthlyAshaIncentive(Integer 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()); From f383508c6dfdf6f5b2f0351e10615f60aac4c420 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Dec 2025 17:39:44 +0530 Subject: [PATCH 007/450] fix jpa query issue --- .../flw/repo/iemr/IncentivePendingActivityRepository.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java index bb53cb5ba..9bac8d219 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java @@ -8,7 +8,11 @@ @Repository public interface IncentivePendingActivityRepository extends JpaRepository { - - Optional findByUserIdAndModuleNameActivityId(Integer userId, String moduleName,Long activityId); + Optional + findByUserIdAndModuleNameAndActivityId( + Integer userId, + String moduleName, + Long activityId + ); } From 1306881c8c9aa12de25bb246feb9a0d9c5698723 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Dec 2025 18:39:38 +0530 Subject: [PATCH 008/450] fix jpa query issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9d5ede87b..5580e8964 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -196,7 +196,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { - Optional incentivePendingActivity = incentivePendingActivityRepository.findByUserIdAndModuleNameActivityId(pendingActivityDTO.getUserId(),pendingActivityDTO.getModuleName(),pendingActivityDTO.getId()); + Optional incentivePendingActivity = incentivePendingActivityRepository.findByUserIdAndModuleNameAndActivityId(pendingActivityDTO.getUserId(),pendingActivityDTO.getModuleName(),pendingActivityDTO.getId()); if(incentivePendingActivity.isPresent()){ IncentivePendingActivity existingIncentivePendingActivity = incentivePendingActivity.get(); From 17d872d198579554f16997c8b7812350711080d6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 15 Dec 2025 18:44:13 +0530 Subject: [PATCH 009/450] Update common_ci.properties --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 6dd8fd043..c24982b77 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -36,4 +36,4 @@ 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@ +//crash.logs.base.path=@env.CRASH_LOGS_PATH@ From 603e2e3ea1d2b88838bb81dfe7c476edebe38dc8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 15 Dec 2025 18:44:26 +0530 Subject: [PATCH 010/450] Reformat common_docker.properties for consistency --- src/main/environment/common_docker.properties | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 2351a47ee..95012c976 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -35,4 +35,5 @@ sms-password=${SMS_PASSWORD} send-message-url=${SMS_MESSAGE_URL} -crash.logs.base.path=${CRASH_LOGS_PATH} +//crash.logs.base.path=${CRASH_LOGS_PATH} + From 2cdff4a64006e8c24f6e1046b473a28277346e7b Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 15 Dec 2025 18:44:55 +0530 Subject: [PATCH 011/450] Reformat common_docker.properties for consistency --- src/main/environment/common_docker.properties | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 95012c976..b6650a5d5 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -35,5 +35,6 @@ sms-password=${SMS_PASSWORD} send-message-url=${SMS_MESSAGE_URL} -//crash.logs.base.path=${CRASH_LOGS_PATH} +#crash.logs.base.path=${CRASH_LOGS_PATH} + From aa49f97cd5890a57cee57708ea1260e1beda0698 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 15 Dec 2025 18:45:09 +0530 Subject: [PATCH 012/450] Update common_ci.properties --- src/main/environment/common_ci.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index c24982b77..b5aa3f029 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -36,4 +36,4 @@ 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@ +#crash.logs.base.path=@env.CRASH_LOGS_PATH@ From 2b74a485f5e7b523a1cc69e79729b793ad7cc1f2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 15 Dec 2025 18:47:52 +0530 Subject: [PATCH 013/450] Update CrashLogServiceImpl.java --- .../java/com/iemr/flw/service/impl/CrashLogServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java index da2fbaa02..4c85ae66c 100644 --- a/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CrashLogServiceImpl.java @@ -24,7 +24,7 @@ public class CrashLogServiceImpl implements CrashLogService { private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - @Value("${crash.logs.base.path}") + // @Value("${crash.logs.base.path}") private String crashLogsBasePath; @Override From edd3046f386b52b00e1c15bd3e36a1641b852599 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Dec 2025 16:34:51 +0530 Subject: [PATCH 014/450] add new column in anc visit (Amm-2039) --- src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java | 6 ++++++ src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java | 2 ++ 2 files changed, 8 insertions(+) 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 c5240d1c3..4128f0826 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ANCVisit.java @@ -167,6 +167,12 @@ public class ANCVisit { @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/dto/iemr/ANCVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java index f028655fb..b4cf0033a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/ANCVisitDTO.java @@ -63,6 +63,8 @@ public class ANCVisitDTO { private Timestamp visitDate; private Timestamp dateSterilisation; private Boolean isYesOrNo; + private String placeOfAnc; + private Integer placeOfAncId; } From 1d65ac9d2e64ad4270b2d07fefe43151a800fef8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 23 Dec 2025 14:03:57 +0530 Subject: [PATCH 015/450] Household Soft-delete Option functionality --- .../com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java | 4 ++++ 1 file changed, 4 insertions(+) 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 9ab4f822b..1a53e8d13 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 String isDeactivate; + } From 128578bf0ed5019e957db40f15bcfa792a8191e1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 23 Dec 2025 17:58:32 +0530 Subject: [PATCH 016/450] change data type of isDeactivate --- .../com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1a53e8d13..3a3ccec86 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java @@ -327,6 +327,6 @@ public class RMNCHHouseHoldDetails { @Expose @Column(name = "isDeactivate") - private String isDeactivate; + private Boolean isDeactivate; } From da327ecb13123d169a125f4c6912c9658f4812c8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Tue, 23 Dec 2025 18:02:17 +0530 Subject: [PATCH 017/450] Change isDeactivate type from String to Boolean --- .../com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1a53e8d13..3a3ccec86 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java @@ -327,6 +327,6 @@ public class RMNCHHouseHoldDetails { @Expose @Column(name = "isDeactivate") - private String isDeactivate; + private Boolean isDeactivate; } From 4ee69e32057912e8c24efcdf30c42ce2cf771861 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Dec 2025 10:51:42 +0530 Subject: [PATCH 018/450] feature of Anc Counselling question --- .../controller/MaternalHealthController.java | 50 ++++++- .../flw/domain/iemr/AncCounsellingCare.java | 128 ++++++++++++++++++ .../flw/dto/iemr/AncCounsellingCareDTO.java | 16 +++ .../dto/iemr/AncCounsellingCareListDTO.java | 79 +++++++++++ .../flw/repo/iemr/AncCounsellingCareRepo.java | 10 ++ .../flw/service/MaternalHealthService.java | 2 + .../impl/MaternalHealthServiceImpl.java | 69 ++++++++++ 7 files changed, 353 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/AncCounsellingCare.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index e23cc8ed4..3c601bb12 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -15,7 +15,6 @@ import io.swagger.v3.oas.annotations.Operation; import jakarta.servlet.http.HttpServletRequest; -import org.checkerframework.checker.units.qual.A; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -141,6 +140,55 @@ public String getANCVisitDetails(@RequestBody GetBenRequestHandler requestDTO, return response.toString(); } + @Operation(summary = "save anc visit question") + @RequestMapping(value = { "/ancVisit/question/saveAll" }, method = { RequestMethod.POST }) + public String saveANCVisitQuestion(@RequestBody List ancVisitQuestionsDTOS, + @RequestHeader(value = "Authorization") 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/questions/getAll" }, method = { RequestMethod.POST }) + public String getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, + @RequestHeader(value = "Authorization") String Authorization) { + OutputResponse response = new OutputResponse(); + try { + if (requestDTO != null) { + logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + + requestDTO); + List result = maternalHealthService.getANCVisits(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"); + } catch (Exception e) { + logger.error("Error in Anc visit get data : " + e); + response.setError(5000, "Error in Anc visit get data : " + e); + } + return response.toString(); + } + @Operation(summary = "save Delivery Outcome details") @RequestMapping(value = { "/deliveryOutcome/saveAll" }, method = { RequestMethod.POST }) public String saveDeliveryOutcome(@RequestBody List deliveryOutcomeDTOS, 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 000000000..46737f12a --- /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/dto/iemr/AncCounsellingCareDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java new file mode 100644 index 000000000..046933225 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AncCounsellingCareDTO { + private String formId; + private Long ancVisitId; + 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 000000000..f73443d76 --- /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/repo/iemr/AncCounsellingCareRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java new file mode 100644 index 000000000..6d9349b1e --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java @@ -0,0 +1,10 @@ +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; + +@Repository +public interface AncCounsellingCareRepo extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/service/MaternalHealthService.java b/src/main/java/com/iemr/flw/service/MaternalHealthService.java index c4af27685..e50813039 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,5 @@ public interface MaternalHealthService { String savePNCVisit(List pncVisitDTOs); + String saveANCVisitQuestions(List ancVisitQuestionsDTOS, String authorization) throws IEMRException; } 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 53ba1d28d..9ba33c024 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -8,6 +8,8 @@ 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 org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,6 +19,7 @@ import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; @@ -58,6 +61,9 @@ public class MaternalHealthServiceImpl implements MaternalHealthService { @Autowired private IncentiveRecordRepo recordRepo; + @Autowired + private JwtUtil jwtUtil; + ObjectMapper mapper = new ObjectMapper(); @@ -67,6 +73,9 @@ public class MaternalHealthServiceImpl implements MaternalHealthService { @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"); @@ -357,6 +366,66 @@ public String savePNCVisit(List pncVisitDTOs) { return null; } + @Override + public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { + + List entities = new ArrayList<>(); + + for (AncCounsellingCareDTO dto : dtos) { + + AncCounsellingCare entity = new AncCounsellingCare(); + + entity.setBeneficiaryId(dto.getBeneficiaryId()); + entity.setAncVisitId(dto.getAncVisitId()); + + entity.setHomeVisitDate( + LocalDate.parse(dto.getVisitDate(), DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ); + AncCounsellingCareListDTO fields = dto.getFields(); + + entity.setHomeVisitDate( + LocalDate.parse(fields.getHomeVisitDate(), DateTimeFormatter.ofPattern("dd-MM-yyyy")) + ); + + 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.setUserId(jwtUtil.extractUserId(authorization)); + entity.setCreatedBy(jwtUtil.extractUsername(authorization)); + entity.setUpdatedBy(jwtUtil.extractUsername(authorization)); + 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())); + + entities.add(entity); + } + + ancCounsellingCareRepo.saveAll(entities); + + return "ANC Counselling & Care data saved successfully"; + } + 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()); From 8a5174dbebf1580429b0e2158a54815f3e2b1be7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Dec 2025 11:48:36 +0530 Subject: [PATCH 019/450] feature of Anc Counselling getAll api --- .../controller/MaternalHealthController.java | 6 +- .../flw/repo/iemr/AncCounsellingCareRepo.java | 3 + .../flw/service/MaternalHealthService.java | 2 + .../impl/MaternalHealthServiceImpl.java | 57 +++++++++++++++++++ 4 files changed, 65 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 3c601bb12..f08598902 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -141,7 +141,7 @@ public String getANCVisitDetails(@RequestBody GetBenRequestHandler requestDTO, } @Operation(summary = "save anc visit question") - @RequestMapping(value = { "/ancVisit/question/saveAll" }, method = { RequestMethod.POST }) + @RequestMapping(value = { "/ancVisit/counselling/saveAll" }, method = { RequestMethod.POST }) public String saveANCVisitQuestion(@RequestBody List ancVisitQuestionsDTOS, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -165,7 +165,7 @@ public String saveANCVisitQuestion(@RequestBody List ancV } @Operation(summary = "get anc visit questions") - @RequestMapping(value = { "/ancVisit/questions/getAll" }, method = { RequestMethod.POST }) + @RequestMapping(value = { "/ancVisit/counselling/getAll" }, method = { RequestMethod.POST }) public String getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, @RequestHeader(value = "Authorization") String Authorization) { OutputResponse response = new OutputResponse(); @@ -173,7 +173,7 @@ public String getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, if (requestDTO != null) { logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); - List result = maternalHealthService.getANCVisits(requestDTO); + List result = maternalHealthService.getANCCounselling(requestDTO); Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); String s = gson.toJson(result); if (s != null) diff --git a/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java index 6d9349b1e..714dae596 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AncCounsellingCareRepo.java @@ -5,6 +5,9 @@ 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/service/MaternalHealthService.java b/src/main/java/com/iemr/flw/service/MaternalHealthService.java index e50813039..dae0e4eb6 100644 --- a/src/main/java/com/iemr/flw/service/MaternalHealthService.java +++ b/src/main/java/com/iemr/flw/service/MaternalHealthService.java @@ -27,4 +27,6 @@ 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/impl/MaternalHealthServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java index 9ba33c024..b9375b6b1 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -421,6 +421,63 @@ public String saveANCVisitQuestions(List dtos, String aut return "ANC Counselling & Care data saved successfully"; } + + @Override + public List getANCCounselling(GetBenRequestHandler requestDTO) { + + List entities = + ancCounsellingCareRepo.findAllByUserId(requestDTO.getUserId()); + + List response = new ArrayList<>(); + + for (AncCounsellingCare entity : entities) { + + AncCounsellingCareListDTO fields = new AncCounsellingCareListDTO(); + + fields.setHomeVisitDate(entity.getHomeVisitDate().toString()); + fields.setSelectAll(booleanToYesNo(entity.getSelectAll())); + fields.setSwelling(booleanToYesNo(entity.getSwelling())); + fields.setHighBp(booleanToYesNo(entity.getHighBp())); + fields.setConvulsions(booleanToYesNo(entity.getConvulsions())); + fields.setAnemia(booleanToYesNo(entity.getAnemia())); + fields.setReducedFetalMovement(booleanToYesNo(entity.getReducedFetalMovement())); + fields.setAgeRisk(booleanToYesNo(entity.getAgeRisk())); + fields.setChildGap(booleanToYesNo(entity.getChildGap())); + + fields.setShortHeight(booleanToYesNo(entity.getShortHeight())); + fields.setPrePregWeight(booleanToYesNo(entity.getPrePregWeight())); + fields.setBleeding(booleanToYesNo(entity.getBleeding())); + fields.setMiscarriageHistory(booleanToYesNo(entity.getMiscarriageHistory())); + fields.setFourPlusDelivery(booleanToYesNo(entity.getFourPlusDelivery())); + fields.setFirstDelivery(booleanToYesNo(entity.getFirstDelivery())); + fields.setTwinPregnancy(booleanToYesNo(entity.getTwinPregnancy())); + fields.setCSectionHistory(booleanToYesNo(entity.getCSectionHistory())); + fields.setPreExistingDisease(booleanToYesNo(entity.getPreExistingDisease())); + fields.setFeverMalaria(booleanToYesNo(entity.getFeverMalaria())); + fields.setJaundice(booleanToYesNo(entity.getJaundice())); + fields.setSickleCell(booleanToYesNo(entity.getSickleCell())); + fields.setProlongedLabor(booleanToYesNo(entity.getProlongedLabor())); + fields.setMalpresentation(booleanToYesNo(entity.getMalpresentation())); + + AncCounsellingCareDTO dto = new AncCounsellingCareDTO(); + dto.setFormId("anc_form_001"); + dto.setAncVisitId(entity.getAncVisitId()); + dto.setBeneficiaryId(entity.getBeneficiaryId()); + dto.setVisitDate(entity.getVisitDate() != null ? entity.getVisitDate().toString() : null); + dto.setFields(fields); + + response.add(dto); + } + + return response; + } + + private String booleanToYesNo(Boolean value) { + return Boolean.TRUE.equals(value) ? "Yes" : "No"; + } + + + private Boolean yesNoToBoolean(String value) { return "Yes".equalsIgnoreCase(value); } From 8aea9eaf471f23398f37d081804f94aa2a2732ac Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Dec 2025 11:51:34 +0530 Subject: [PATCH 020/450] fix error code --- .../com/iemr/flw/controller/MaternalHealthController.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index f08598902..c87595fb1 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -179,12 +179,12 @@ public String getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, 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 Anc visit get data : " + e); - response.setError(5000, "Error in Anc visit get data : " + e); + response.setError(500, "Error in Anc visit get data : " + e); } return response.toString(); } From c220538b6bbdd042c6850bb3d727bb5483f3d5a8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Dec 2025 14:04:44 +0530 Subject: [PATCH 021/450] add soft delete key --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 7 +++++++ 1 file changed, 7 insertions(+) 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 510d4b536..759edfb47 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -405,6 +405,13 @@ private String getMappingsForAddressIDs(List addressLi resultMap.put("isMarried", benDetailsRMNCH_OBJ.getIsMarried()); resultMap.put("doYouHavechildren", benDetailsRMNCH_OBJ.getDoYouHavechildren()); resultMap.put("noofAlivechildren ",benDetailsRMNCH_OBJ.getNoofAlivechildren()); + if(houseHoldRepo.getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId())!=null){ + resultMap.put("isDeactivate",true); + + }else { + resultMap.put("isDeactivate",false); + + } From af518c863fe1a0fbc74793f103391962598cf33b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 16:24:24 +0530 Subject: [PATCH 022/450] remove anc visit id --- src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java | 1 - .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java index 046933225..76aff81da 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareDTO.java @@ -5,7 +5,6 @@ @Data public class AncCounsellingCareDTO { private String formId; - private Long ancVisitId; private Long beneficiaryId; private String visitDate; private AncCounsellingCareListDTO fields; 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 b9375b6b1..87e3d4467 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -376,7 +376,7 @@ public String saveANCVisitQuestions(List dtos, String aut AncCounsellingCare entity = new AncCounsellingCare(); entity.setBeneficiaryId(dto.getBeneficiaryId()); - entity.setAncVisitId(dto.getAncVisitId()); + entity.setAncVisitId(0L); entity.setHomeVisitDate( LocalDate.parse(dto.getVisitDate(), DateTimeFormatter.ofPattern("dd-MM-yyyy")) @@ -461,7 +461,6 @@ public List getANCCounselling(GetBenRequestHandler reques AncCounsellingCareDTO dto = new AncCounsellingCareDTO(); dto.setFormId("anc_form_001"); - dto.setAncVisitId(entity.getAncVisitId()); dto.setBeneficiaryId(entity.getBeneficiaryId()); dto.setVisitDate(entity.getVisitDate() != null ? entity.getVisitDate().toString() : null); dto.setFields(fields); From 86665e632c5639fa089ffe0b8e9b54207190f778 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 16:50:31 +0530 Subject: [PATCH 023/450] add jwt token in header --- .../java/com/iemr/flw/controller/MaternalHealthController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index c87595fb1..114201fb2 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -143,7 +143,7 @@ public String getANCVisitDetails(@RequestBody GetBenRequestHandler requestDTO, @Operation(summary = "save anc visit question") @RequestMapping(value = { "/ancVisit/counselling/saveAll" }, method = { RequestMethod.POST }) public String saveANCVisitQuestion(@RequestBody List ancVisitQuestionsDTOS, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "JwtToken") String Authorization) { OutputResponse response = new OutputResponse(); try { if (ancVisitQuestionsDTOS.size() != 0) { From a6bca15135b3d298283aca890c3dfad3c64e3d0e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 17:00:39 +0530 Subject: [PATCH 024/450] fix null pomiter issue --- .../impl/MaternalHealthServiceImpl.java | 37 +++++++++++++------ 1 file changed, 26 insertions(+), 11 deletions(-) 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 87e3d4467..95eea2e45 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -15,6 +15,7 @@ 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.time.LocalDate; @@ -369,6 +370,8 @@ public String savePNCVisit(List pncVisitDTOs) { @Override public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + List entities = new ArrayList<>(); for (AncCounsellingCareDTO dto : dtos) { @@ -378,17 +381,28 @@ public String saveANCVisitQuestions(List dtos, String aut entity.setBeneficiaryId(dto.getBeneficiaryId()); entity.setAncVisitId(0L); - entity.setHomeVisitDate( - LocalDate.parse(dto.getVisitDate(), DateTimeFormatter.ofPattern("dd-MM-yyyy")) - ); + // ✅ visitDate (DTO level) + if (StringUtils.hasText(dto.getVisitDate())) { + entity.setVisitDate( + LocalDate.parse(dto.getVisitDate(), formatter) + ); + } else { + throw new IllegalArgumentException("visitDate is mandatory"); + } + AncCounsellingCareListDTO fields = dto.getFields(); + if (fields == null) { + throw new IllegalArgumentException("fields object is missing"); + } - entity.setHomeVisitDate( - LocalDate.parse(fields.getHomeVisitDate(), DateTimeFormatter.ofPattern("dd-MM-yyyy")) - ); + // ✅ homeVisitDate (fields level) + if (StringUtils.hasText(fields.getHomeVisitDate())) { + entity.setHomeVisitDate( + LocalDate.parse(fields.getHomeVisitDate(), formatter) + ); + } entity.setSelectAll(yesNoToBoolean(fields.getSelectAll())); - entity.setSwelling(yesNoToBoolean(fields.getSwelling())); entity.setHighBp(yesNoToBoolean(fields.getHighBp())); entity.setConvulsions(yesNoToBoolean(fields.getConvulsions())); @@ -396,9 +410,6 @@ public String saveANCVisitQuestions(List dtos, String aut entity.setReducedFetalMovement(yesNoToBoolean(fields.getReducedFetalMovement())); entity.setAgeRisk(yesNoToBoolean(fields.getAgeRisk())); entity.setChildGap(yesNoToBoolean(fields.getChildGap())); - entity.setUserId(jwtUtil.extractUserId(authorization)); - entity.setCreatedBy(jwtUtil.extractUsername(authorization)); - entity.setUpdatedBy(jwtUtil.extractUsername(authorization)); entity.setShortHeight(yesNoToBoolean(fields.getShortHeight())); entity.setPrePregWeight(yesNoToBoolean(fields.getPrePregWeight())); entity.setBleeding(yesNoToBoolean(fields.getBleeding())); @@ -414,12 +425,16 @@ public String saveANCVisitQuestions(List dtos, String aut 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 From 23fac7ed0d2ed0770e483d3c73e01e1d10dbc4a6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 17:31:36 +0530 Subject: [PATCH 025/450] fix null pomiter issue --- .../impl/MaternalHealthServiceImpl.java | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) 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 95eea2e45..d8c78e08a 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -10,6 +10,7 @@ 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; @@ -21,6 +22,7 @@ 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; @@ -368,40 +370,45 @@ public String savePNCVisit(List pncVisitDTOs) { } @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) { - AncCounsellingCare entity = new AncCounsellingCare(); - - entity.setBeneficiaryId(dto.getBeneficiaryId()); - entity.setAncVisitId(0L); - - // ✅ visitDate (DTO level) - if (StringUtils.hasText(dto.getVisitDate())) { - entity.setVisitDate( - LocalDate.parse(dto.getVisitDate(), formatter) - ); - } else { + if (!StringUtils.hasText(dto.getVisitDate())) { throw new IllegalArgumentException("visitDate is mandatory"); } AncCounsellingCareListDTO fields = dto.getFields(); if (fields == null) { - throw new IllegalArgumentException("fields object is missing"); + 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"); } - // ✅ homeVisitDate (fields level) - if (StringUtils.hasText(fields.getHomeVisitDate())) { - entity.setHomeVisitDate( - LocalDate.parse(fields.getHomeVisitDate(), formatter) - ); + 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())); @@ -434,9 +441,9 @@ public String saveANCVisitQuestions(List dtos, String aut ancCounsellingCareRepo.saveAll(entities); return "ANC Counselling & Care data saved successfully"; - } + @Override public List getANCCounselling(GetBenRequestHandler requestDTO) { From dd418de4aafb454a3455f5a2696e34dbe0b0b18d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 18:17:39 +0530 Subject: [PATCH 026/450] fix response issue --- .../controller/MaternalHealthController.java | 48 ++++++++++++------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 114201fb2..5b74b572d 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -18,6 +18,8 @@ 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; @@ -90,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") @@ -166,27 +169,39 @@ public String saveANCVisitQuestion(@RequestBody List ancV @Operation(summary = "get anc visit questions") @RequestMapping(value = { "/ancVisit/counselling/getAll" }, method = { RequestMethod.POST }) - public String getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, - @RequestHeader(value = "Authorization") String Authorization) { - OutputResponse response = new OutputResponse(); + public ResponseEntity>> getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, + @RequestHeader(value = "JwtToken") String Authorization) { + StandardResponse> response = new StandardResponse<>(); + try { if (requestDTO != null) { - logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " - + requestDTO); + logger.info("Request: " + requestDTO); + List result = maternalHealthService.getANCCounselling(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(500, "No record found"); - } else - response.setError(500, "Invalid/NULL request obj"); + + 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("Error in Anc visit get data : " + e); - response.setError(500, "Error in Anc 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 Delivery Outcome details") @@ -211,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") From 9f67b3f3b376155237edb53d178382d1c7dc84db Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 30 Dec 2025 18:20:28 +0530 Subject: [PATCH 027/450] fix response issue --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 d8c78e08a..ad5775723 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -448,7 +448,7 @@ public String saveANCVisitQuestions(List dtos, String aut public List getANCCounselling(GetBenRequestHandler requestDTO) { List entities = - ancCounsellingCareRepo.findAllByUserId(requestDTO.getUserId()); + ancCounsellingCareRepo.findAllByUserId(requestDTO.getAshaId()); List response = new ArrayList<>(); From 552ce35bca0d55d34f56300ce784bbc7734cc6d1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 31 Dec 2025 08:20:10 +0530 Subject: [PATCH 028/450] fix response of get api --- .../controller/MaternalHealthController.java | 6 +- .../dto/iemr/AncCounsellingCareListDTO.java | 92 +++++++++---------- .../iemr/AncCounsellingCareResponseDTO.java | 17 ++++ .../flw/service/MaternalHealthService.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 83 +++++++++-------- 5 files changed, 113 insertions(+), 87 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareResponseDTO.java diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 5b74b572d..e65eacda6 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -169,15 +169,15 @@ public String saveANCVisitQuestion(@RequestBody List ancV @Operation(summary = "get anc visit questions") @RequestMapping(value = { "/ancVisit/counselling/getAll" }, method = { RequestMethod.POST }) - public ResponseEntity>> getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, + public ResponseEntity>> getANCVisitQuestion(@RequestBody GetBenRequestHandler requestDTO, @RequestHeader(value = "JwtToken") String Authorization) { - StandardResponse> response = new StandardResponse<>(); + StandardResponse> response = new StandardResponse<>(); try { if (requestDTO != null) { logger.info("Request: " + requestDTO); - List result = maternalHealthService.getANCCounselling(requestDTO); + List result = maternalHealthService.getANCCounselling(requestDTO); response.setStatusCode(200); response.setStatus("Success"); diff --git a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java index f73443d76..981e34e2b 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AncCounsellingCareListDTO.java @@ -6,74 +6,74 @@ @Data public class AncCounsellingCareListDTO { - @SerializedName("home_visit_date") - private String homeVisitDate; + @SerializedName("home_visit_date") + private String homeVisitDate; - @SerializedName("select_all") - private String selectAll; + @SerializedName("select_all") + private String selectAll; - @SerializedName("swelling") - private String swelling; + @SerializedName("swelling") + private String swelling; - @SerializedName("high_bp") - private String highBp; + @SerializedName("high_bp") + private String highBp; - @SerializedName("convulsions") - private String convulsions; + @SerializedName("convulsions") + private String convulsions; - @SerializedName("anemia") - private String anemia; + @SerializedName("anemia") + private String anemia; - @SerializedName("reduced_fetal_movement") - private String reducedFetalMovement; + @SerializedName("reduced_fetal_movement") + private String reducedFetalMovement; - @SerializedName("age_risk") - private String ageRisk; + @SerializedName("age_risk") + private String ageRisk; - @SerializedName("child_gap") - private String childGap; + @SerializedName("child_gap") + private String childGap; - @SerializedName("short_height") - private String shortHeight; + @SerializedName("short_height") + private String shortHeight; - @SerializedName("pre_preg_weight") - private String prePregWeight; + @SerializedName("pre_preg_weight") + private String prePregWeight; - @SerializedName("bleeding") - private String bleeding; + @SerializedName("bleeding") + private String bleeding; - @SerializedName("miscarriage_history") - private String miscarriageHistory; + @SerializedName("miscarriage_history") + private String miscarriageHistory; - @SerializedName("four_plus_delivery") - private String fourPlusDelivery; + @SerializedName("four_plus_delivery") + private String fourPlusDelivery; - @SerializedName("first_delivery") - private String firstDelivery; + @SerializedName("first_delivery") + private String firstDelivery; - @SerializedName("twin_pregnancy") - private String twinPregnancy; + @SerializedName("twin_pregnancy") + private String twinPregnancy; - @SerializedName("c_section_history") - private String cSectionHistory; + @SerializedName("c_section_history") + private String cSectionHistory; - @SerializedName("pre_existing_disease") - private String preExistingDisease; + @SerializedName("pre_existing_disease") + private String preExistingDisease; - @SerializedName("fever_malaria") - private String feverMalaria; + @SerializedName("fever_malaria") + private String feverMalaria; - @SerializedName("jaundice") - private String jaundice; + @SerializedName("jaundice") + private String jaundice; - @SerializedName("sickle_cell") - private String sickleCell; + @SerializedName("sickle_cell") + private String sickleCell; - @SerializedName("prolonged_labor") - private String prolongedLabor; + @SerializedName("prolonged_labor") + private String prolongedLabor; - @SerializedName("malpresentation") - private String malpresentation; + @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 000000000..2e0195582 --- /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/service/MaternalHealthService.java b/src/main/java/com/iemr/flw/service/MaternalHealthService.java index dae0e4eb6..33de9bc93 100644 --- a/src/main/java/com/iemr/flw/service/MaternalHealthService.java +++ b/src/main/java/com/iemr/flw/service/MaternalHealthService.java @@ -28,5 +28,5 @@ public interface MaternalHealthService { String saveANCVisitQuestions(List ancVisitQuestionsDTOS, String authorization) throws IEMRException; - List getANCCounselling(GetBenRequestHandler requestDTO); + List getANCCounselling(GetBenRequestHandler requestDTO); } 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 ad5775723..8914941f1 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -445,52 +445,61 @@ public String saveANCVisitQuestions(List dtos, String aut @Override - public List getANCCounselling(GetBenRequestHandler requestDTO) { + public List getANCCounselling(GetBenRequestHandler requestDTO) { List entities = ancCounsellingCareRepo.findAllByUserId(requestDTO.getAshaId()); - List response = new ArrayList<>(); + List responseDTOList = new ArrayList<>(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); for (AncCounsellingCare entity : entities) { - AncCounsellingCareListDTO fields = new AncCounsellingCareListDTO(); - - fields.setHomeVisitDate(entity.getHomeVisitDate().toString()); - fields.setSelectAll(booleanToYesNo(entity.getSelectAll())); - fields.setSwelling(booleanToYesNo(entity.getSwelling())); - fields.setHighBp(booleanToYesNo(entity.getHighBp())); - fields.setConvulsions(booleanToYesNo(entity.getConvulsions())); - fields.setAnemia(booleanToYesNo(entity.getAnemia())); - fields.setReducedFetalMovement(booleanToYesNo(entity.getReducedFetalMovement())); - fields.setAgeRisk(booleanToYesNo(entity.getAgeRisk())); - fields.setChildGap(booleanToYesNo(entity.getChildGap())); - - fields.setShortHeight(booleanToYesNo(entity.getShortHeight())); - fields.setPrePregWeight(booleanToYesNo(entity.getPrePregWeight())); - fields.setBleeding(booleanToYesNo(entity.getBleeding())); - fields.setMiscarriageHistory(booleanToYesNo(entity.getMiscarriageHistory())); - fields.setFourPlusDelivery(booleanToYesNo(entity.getFourPlusDelivery())); - fields.setFirstDelivery(booleanToYesNo(entity.getFirstDelivery())); - fields.setTwinPregnancy(booleanToYesNo(entity.getTwinPregnancy())); - fields.setCSectionHistory(booleanToYesNo(entity.getCSectionHistory())); - fields.setPreExistingDisease(booleanToYesNo(entity.getPreExistingDisease())); - fields.setFeverMalaria(booleanToYesNo(entity.getFeverMalaria())); - fields.setJaundice(booleanToYesNo(entity.getJaundice())); - fields.setSickleCell(booleanToYesNo(entity.getSickleCell())); - fields.setProlongedLabor(booleanToYesNo(entity.getProlongedLabor())); - fields.setMalpresentation(booleanToYesNo(entity.getMalpresentation())); - - AncCounsellingCareDTO dto = new AncCounsellingCareDTO(); - dto.setFormId("anc_form_001"); - dto.setBeneficiaryId(entity.getBeneficiaryId()); - dto.setVisitDate(entity.getVisitDate() != null ? entity.getVisitDate().toString() : null); - dto.setFields(fields); - - response.add(dto); + 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; - return response; } private String booleanToYesNo(Boolean value) { From 52de84cb4d49f7ba301e9d0765a39747df211009 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 5 Jan 2026 15:14:01 +0530 Subject: [PATCH 029/450] Beneficiary Soft-delete. --- .../identity/RMNCHBeneficiaryDetailsRmnch.java | 3 +++ .../flw/service/impl/BeneficiaryServiceImpl.java | 13 ++----------- 2 files changed, 5 insertions(+), 11 deletions(-) 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 ac336da13..297694b7c 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java @@ -386,6 +386,9 @@ public class RMNCHBeneficiaryDetailsRmnch { @Expose private Integer noofAlivechildren; + @Expose + private Boolean isDeactivate; + @Expose @Transient private Integer servicePointID; 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 759edfb47..f5a757854 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -404,17 +404,8 @@ private String getMappingsForAddressIDs(List addressLi resultMap.put("noOfchildren", benDetailsRMNCH_OBJ.getNoOfchildren()); resultMap.put("isMarried", benDetailsRMNCH_OBJ.getIsMarried()); resultMap.put("doYouHavechildren", benDetailsRMNCH_OBJ.getDoYouHavechildren()); - resultMap.put("noofAlivechildren ",benDetailsRMNCH_OBJ.getNoofAlivechildren()); - if(houseHoldRepo.getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId())!=null){ - resultMap.put("isDeactivate",true); - - }else { - resultMap.put("isDeactivate",false); - - } - - - + resultMap.put("noofAlivechildren",benDetailsRMNCH_OBJ.getNoofAlivechildren()); + resultMap.put("isDeactivate",benDetailsRMNCH_OBJ.getIsDeactivate()); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id From bb2f1fe1b8a046e600cdb7963ccc9c5957af04ab Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 6 Jan 2026 15:22:02 +0530 Subject: [PATCH 030/450] cdtf_visit_details AMM-2046 and AMM-2045 --- .../controller/DiseaseControlController.java | 37 ++++++++-- .../iemr/ChronicDiseaseVisitEntity.java | 72 +++++++++++++++++++ .../flw/dto/iemr/ChronicDiseaseVisitDTO.java | 38 ++++++++++ .../iemr/ChronicDiseaseVisitRepository.java | 10 +++ .../flw/service/DiseaseControlService.java | 2 + .../impl/DiseaseControlServiceImpl.java | 46 ++++++++++++ 6 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 2f5d42644..0c225e233 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -34,11 +34,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; -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.web.bind.annotation.*; import java.util.HashMap; import java.util.LinkedHashMap; @@ -314,5 +310,36 @@ public ResponseEntity> getAllMobilizationMosquitoNet(@Reques 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); + } + } + + } \ No newline at end of file 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 000000000..c236ffa73 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java @@ -0,0 +1,72 @@ +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 = "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/dto/iemr/ChronicDiseaseVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java new file mode 100644 index 000000000..7ec119c47 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java @@ -0,0 +1,38 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@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; + + @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/repo/iemr/ChronicDiseaseVisitRepository.java b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java new file mode 100644 index 000000000..dc422710b --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java @@ -0,0 +1,10 @@ +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; + +@Repository +public interface ChronicDiseaseVisitRepository + extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/service/DiseaseControlService.java b/src/main/java/com/iemr/flw/service/DiseaseControlService.java index 92accf4aa..08ad10137 100644 --- a/src/main/java/com/iemr/flw/service/DiseaseControlService.java +++ b/src/main/java/com/iemr/flw/service/DiseaseControlService.java @@ -25,6 +25,7 @@ package com.iemr.flw.service; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.utils.exception.IEMRException; import java.util.List; @@ -44,4 +45,5 @@ public interface DiseaseControlService { public String saveLeprosyFollowUp(LeprosyFollowUpDTO leprosyDTO); List getAllLeprosyFollowUpData(String createdBy); + List saveChronicDiseaseVisit(List requestList,String token) throws IEMRException; } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index bc7800385..377f50b63 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -31,6 +31,8 @@ import com.iemr.flw.masterEnum.DiseaseType; 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; @@ -77,7 +79,11 @@ public class DiseaseControlServiceImpl implements DiseaseControlService { private MosquitoNetRepository mosquitoNetRepository; + @Autowired + private ChronicDiseaseVisitRepository chronicDiseaseVisitRepository; + @Autowired + private JwtUtil jwtUtil; private final Logger logger = LoggerFactory.getLogger(CoupleController.class); @@ -998,4 +1004,44 @@ record = new IncentiveActivityRecord(); } } + + + @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()); + entity.setDiagnosisCodes(dto.getDiagnosisCodes()); + entity.setFormDataJson(dto.getFormDataJson()); + entity.setUserID(jwtUtil.extractUserId(token)); + entity.setCreatedBy(jwtUtil.extractUsername(token)); + + + if (dto.getTreatmentStartDate() != null) { + entity.setTreatmentStartDate( + LocalDate.parse(dto.getTreatmentStartDate()) + ); + } + + ChronicDiseaseVisitEntity savedEntity = + chronicDiseaseVisitRepository.save(entity); + + dto.setId(savedEntity.getId()); + responseList.add(dto); + } + + return responseList; + } + } \ No newline at end of file From dd63a8946539e2e64cc74aef4054c7712b8862a7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 6 Jan 2026 15:45:59 +0530 Subject: [PATCH 031/450] cdtf_visit_details get api AMM-2046 and AMM-2045 --- .../controller/DiseaseControlController.java | 27 +++++++++++++++ .../iemr/ChronicDiseaseVisitRepository.java | 4 +++ .../flw/service/DiseaseControlService.java | 3 ++ .../impl/DiseaseControlServiceImpl.java | 34 +++++++++++++++++++ 4 files changed, 68 insertions(+) diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 0c225e233..e89a53067 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -340,6 +340,33 @@ public ResponseEntity> saveVisit( } } + @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/repo/iemr/ChronicDiseaseVisitRepository.java b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java index dc422710b..e63835a96 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChronicDiseaseVisitRepository.java @@ -4,7 +4,11 @@ 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/service/DiseaseControlService.java b/src/main/java/com/iemr/flw/service/DiseaseControlService.java index 08ad10137..65e315dce 100644 --- a/src/main/java/com/iemr/flw/service/DiseaseControlService.java +++ b/src/main/java/com/iemr/flw/service/DiseaseControlService.java @@ -24,6 +24,7 @@ */ 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; @@ -46,4 +47,6 @@ public interface DiseaseControlService { 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/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 377f50b63..e26ef5aff 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -27,6 +27,7 @@ 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.repo.iemr.*; @@ -1044,4 +1045,37 @@ public List saveChronicDiseaseVisit( return responseList; } + @Override + public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { + + List entityList = chronicDiseaseVisitRepository.findByUserID(getBenRequestHandler.getAshaId()); + + List dtoList = new ArrayList<>(); + + 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()); + dto.setDiagnosisCodes(entity.getDiagnosisCodes()); + dto.setFormDataJson(entity.getFormDataJson()); + + if (entity.getTreatmentStartDate() != null) { + dto.setTreatmentStartDate( + entity.getTreatmentStartDate().toString() + ); + } + + dtoList.add(dto); + } + + return dtoList; + } + } \ No newline at end of file From b723320b47b8c43f999c0d937ec1ee8639d26567 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 6 Jan 2026 16:50:41 +0530 Subject: [PATCH 032/450] Add new parameters in leprosy suspected API AMM-2071 --- .../flw/domain/iemr/ScreeningLeprosy.java | 72 +++++++++++++++++++ .../iemr/flw/dto/iemr/DiseaseLeprosyDTO.java | 24 +++++++ .../impl/DiseaseControlServiceImpl.java | 54 ++++++++++++++ 3 files changed, 150 insertions(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java index 225a1dfc9..4efc6dccb 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java @@ -143,6 +143,78 @@ public class ScreeningLeprosy { @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", length = 10) + private String recurrentUlceration; + + @Column(name = "recurrent_tingling", length = 10) + private String recurrentTingling; + + @Column(name = "hypopigmented_patch", length = 50) + private String hypopigmentedPatch; + + @Column(name = "thickened_skin", length = 10) + private String thickenedSkin; + + @Column(name = "skin_nodules", length = 10) + private String skinNodules; + + @Column(name = "skin_patch_discoloration", length = 50) + private String skinPatchDiscoloration; + + @Column(name = "recurrent_numbness", length = 10) + private String recurrentNumbness; + + @Column(name = "clawing_fingers", length = 10) + private String clawingFingers; + + @Column(name = "tingling_numbness_extremities", length = 50) + private String tinglingNumbnessExtremities; + + @Column(name = "inability_close_eyelid", length = 10) + private String inabilityCloseEyelid; + + @Column(name = "difficulty_holding_objects", length = 50) + private String difficultyHoldingObjects; + + @Column(name = "weakness_feet", length = 10) + private String weaknessFeet; + @Column(name = "CreatedBy", length = 100) private String createdBy; diff --git a/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java index c0acbe716..47489c54e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DiseaseLeprosyDTO.java @@ -72,4 +72,28 @@ public class DiseaseLeprosyDTO { 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/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index e26ef5aff..3ba522dac 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -724,6 +724,33 @@ private ScreeningLeprosy saveLeprosyData(DiseaseLeprosyDTO diseaseControlData) { 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; } @@ -768,6 +795,33 @@ private String updateLeprosyData(DiseaseLeprosyDTO diseaseControlData) { 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"; From 42384974a298d120662059c5898e1da7e52d029e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 6 Jan 2026 16:59:47 +0530 Subject: [PATCH 033/450] add new column --- .../com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java | 5 ++++- .../java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java | 6 ++++++ .../iemr/flw/service/impl/DiseaseControlServiceImpl.java | 3 +++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java b/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java index c236ffa73..10689cff3 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ChronicDiseaseVisitEntity.java @@ -23,7 +23,7 @@ public class ChronicDiseaseVisitEntity { @Column(name = "form_id") private String formId; - @Column(name = "version") + @Column(name = "version") private Integer version; @Column(name = "visit_no") @@ -38,6 +38,9 @@ public class ChronicDiseaseVisitEntity { @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; diff --git a/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java index 7ec119c47..2a2790ad7 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/ChronicDiseaseVisitDTO.java @@ -1,8 +1,11 @@ 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 { @@ -27,6 +30,9 @@ public class ChronicDiseaseVisitDTO { @JsonProperty("followUpNo") private Integer followUpNo; + @Column(name = "followUpDate") + private LocalDate followUpDate; + @JsonProperty("diagnosisCodes") private String diagnosisCodes; diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 3ba522dac..d5f009eaf 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1077,10 +1077,12 @@ public List saveChronicDiseaseVisit( entity.setVersion(dto.getVersion()); entity.setVisitNo(dto.getVisitNo()); entity.setFollowUpNo(dto.getFollowUpNo()); + 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) { @@ -1117,6 +1119,7 @@ public List getCdtfVisits(GetBenRequestHandler getBenReq dto.setVersion(entity.getVersion()); dto.setVisitNo(entity.getVisitNo()); dto.setFollowUpNo(entity.getFollowUpNo()); + dto.setFollowUpDate(entity.getFollowUpDate()); dto.setDiagnosisCodes(entity.getDiagnosisCodes()); dto.setFormDataJson(entity.getFormDataJson()); From b85db376633e4671fd367cf9bdb88e0287e981b5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 7 Jan 2026 10:43:31 +0530 Subject: [PATCH 034/450] change release version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d87cbdecc..fe37dd00c 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.7.0 + 3.6.2 war FLW-API From bd5071911a053c560d3916ffa0cae41b2a6838e9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 8 Jan 2026 14:32:13 +0530 Subject: [PATCH 035/450] AMM-2079 --- .../com/iemr/flw/domain/iemr/VhncForm.java | 23 +++++++++++++++++++ .../com/iemr/flw/dto/iemr/VhncFormDTO.java | 8 +++++++ .../impl/VillageLevelFormServiceImpl.java | 8 +++++++ 3 files changed, 39 insertions(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java b/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java index 5b53b27ed..858554daf 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java +++ b/src/main/java/com/iemr/flw/domain/iemr/VhncForm.java @@ -1,6 +1,7 @@ package com.iemr.flw.domain.iemr; import jakarta.persistence.*; +import jakarta.xml.bind.annotation.XmlAccessorOrder; import lombok.Data; import org.hibernate.annotations.CreationTimestamp; @@ -43,4 +44,26 @@ public class VhncForm { @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/iemr/VhncFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java index 8a12be966..a2515b421 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/VhncFormDTO.java @@ -34,4 +34,12 @@ public class VhncFormDTO { 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/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 71bbdbad8..8630d444a 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -132,6 +132,14 @@ private Boolean saveVhncFormData(VhncFormDTO vhncFormDTO, Integer userID) { vhncForm.setImage2(vhncFormDTO.getImage2()); vhncForm.setImage1(vhncFormDTO.getImage1()); vhncForm.setPlace(vhncFormDTO.getPlace()); + vhncForm.setVillageName(vhncForm.getVillageName()); + vhncForm.setAnm(vhncForm.getAnm()); + vhncForm.setAww(vhncForm.getAww()); + vhncForm.setNoOfPragnentWoment(vhncForm.getNoOfPragnentWoment()); + vhncForm.setNoOfLactingMother(vhncForm.getNoOfLactingMother()); + vhncForm.setNoOfCommittee(vhncForm.getNoOfCommittee()); + vhncForm.setFollowupPrevius(vhncForm.getFollowupPrevius()); + vhncForm.setNoOfBeneficiariesAttended(vhncFormDTO.getNoOfBeneficiariesAttended()); vhncForm.setFormType("VHNC"); From fa30de33c8879f6af1a579752975f8e9d3df7f8a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 9 Jan 2026 16:23:50 +0530 Subject: [PATCH 036/450] AMM-2079 --- .../service/impl/VillageLevelFormServiceImpl.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 8630d444a..9efd528b1 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -132,13 +132,13 @@ private Boolean saveVhncFormData(VhncFormDTO vhncFormDTO, Integer userID) { vhncForm.setImage2(vhncFormDTO.getImage2()); vhncForm.setImage1(vhncFormDTO.getImage1()); vhncForm.setPlace(vhncFormDTO.getPlace()); - vhncForm.setVillageName(vhncForm.getVillageName()); - vhncForm.setAnm(vhncForm.getAnm()); - vhncForm.setAww(vhncForm.getAww()); - vhncForm.setNoOfPragnentWoment(vhncForm.getNoOfPragnentWoment()); - vhncForm.setNoOfLactingMother(vhncForm.getNoOfLactingMother()); - vhncForm.setNoOfCommittee(vhncForm.getNoOfCommittee()); - vhncForm.setFollowupPrevius(vhncForm.getFollowupPrevius()); + 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()); From 624752175b00dd1488c63b9a9de0e506462e60be Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Fri, 9 Jan 2026 16:31:40 +0530 Subject: [PATCH 037/450] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index fe37dd00c..42245b930 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.6.2 + 3.7.0 war FLW-API @@ -420,4 +420,4 @@ - \ No newline at end of file + From ec9f17bb82568944e11c18cb05ffe2fd28ba7470 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 9 Jan 2026 17:03:04 +0530 Subject: [PATCH 038/450] Amm-2081 --- .../com/iemr/flw/domain/iemr/VHNDForm.java | 33 +++++++++++++++++++ .../com/iemr/flw/dto/iemr/VHNDFormDTO.java | 12 +++++++ .../impl/VillageLevelFormServiceImpl.java | 10 ++++++ 3 files changed, 55 insertions(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java b/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java index 488b33c4e..758cc449a 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java +++ b/src/main/java/com/iemr/flw/domain/iemr/VHNDForm.java @@ -37,6 +37,39 @@ public class VHNDForm { @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; diff --git a/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java index 0dec7976a..bee7f2475 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/VHNDFormDTO.java @@ -24,6 +24,7 @@ */ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; import lombok.Data; @Data @@ -33,6 +34,17 @@ public class VHNDFormDTO { 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/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 9efd528b1..a4df2b7d4 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -210,6 +210,16 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { 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()); From 9f0bfa571a125cbe829e81c0f554de28e31e4c3b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 9 Jan 2026 19:02:26 +0530 Subject: [PATCH 039/450] fix auth --- .../flw/controller/VillageLevelFormController.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java index ddbb7a76b..09df68334 100644 --- a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java +++ b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java @@ -36,13 +36,13 @@ import java.util.Map; @RestController -@RequestMapping(value = "/forms/villageLevel", headers = "Authorization") +@RequestMapping(value = "/forms/villageLevel") public class VillageLevelFormController { @Autowired private VillageLevelFormService villageLevelFormService; - @RequestMapping(value = "vhnd/saveAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "vhnd/saveAll") public ResponseEntity> saveVhndForm(@RequestBody VhndDto dto) { Map response = new HashMap<>(); if (!dto.getEntries().isEmpty()) { @@ -64,7 +64,7 @@ public ResponseEntity> saveVhndForm(@RequestBody VhndDto dto } - @RequestMapping(value = "vhnc/saveAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "vhnc/saveAll", method = RequestMethod.POST) public ResponseEntity> saveVhncForm(@RequestBody VhncDto dto) { Map response = new HashMap<>(); @@ -87,7 +87,7 @@ public ResponseEntity> saveVhncForm(@RequestBody VhncDto dto } - @RequestMapping(value = "phc/saveAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "phc/saveAll", method = RequestMethod.POST) public ResponseEntity> savePhcForm(@RequestBody PhcReviewMeetingDTO dto) { Map response = new HashMap<>(); @@ -109,7 +109,7 @@ public ResponseEntity> savePhcForm(@RequestBody PhcReviewMee } - @RequestMapping(value = "ahd/saveAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "ahd/saveAll", method = RequestMethod.POST) public ResponseEntity> saveAhdForm(@RequestBody AhdMeetingDto dto) { Map response = new HashMap<>(); @@ -129,7 +129,7 @@ public ResponseEntity> saveAhdForm(@RequestBody AhdMeetingDt } - @RequestMapping(value = "deworming/saveAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "deworming/saveAll", method = RequestMethod.POST) public ResponseEntity> saveDewormingForm(@RequestBody DewormingDto dto) { Map response = new HashMap<>(); @@ -150,7 +150,7 @@ public ResponseEntity> saveDewormingForm(@RequestBody Deworm } - @RequestMapping(value = "getAll", method = RequestMethod.POST, headers = "Authorization") + @RequestMapping(value = "getAll", method = RequestMethod.POST) public ResponseEntity> getVillageLevelFormData(@RequestBody GetVillageLevelRequestHandler getVillageLevelRequestHandler) { Map response = new LinkedHashMap<>(); From e8930c696c190ac94c7ccf823fd4c4b56cbecf7f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 9 Jan 2026 19:03:02 +0530 Subject: [PATCH 040/450] fix auth --- .../com/iemr/flw/controller/VillageLevelFormController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java index 09df68334..884f794d1 100644 --- a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java +++ b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java @@ -42,7 +42,7 @@ public class VillageLevelFormController { @Autowired private VillageLevelFormService villageLevelFormService; - @RequestMapping(value = "vhnd/saveAll") + @RequestMapping(value = "vhnd/saveAll",method = RequestMethod.POST) public ResponseEntity> saveVhndForm(@RequestBody VhndDto dto) { Map response = new HashMap<>(); if (!dto.getEntries().isEmpty()) { From 4bda32abd241f5856a7f830baadd441bef9108ce Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 11:21:51 +0530 Subject: [PATCH 041/450] enhancement in mam meeting api add new column AMM-2102 --- .../flw/controller/MaaMeetingController.java | 9 +++ .../com/iemr/flw/domain/iemr/MaaMeeting.java | 13 ++++ .../flw/dto/iemr/MaaMeetingRequestDTO.java | 6 ++ .../flw/dto/iemr/MaaMeetingResponseDTO.java | 5 ++ .../iemr/flw/service/MaaMeetingService.java | 70 ++++++++++++------- 5 files changed, 79 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 0c73d46e5..1ed1bb014 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -35,6 +35,10 @@ public MaaMeetingController(MaaMeetingService service) { @PostMapping(value = "/saveAll", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity saveMeeting( + @RequestPart("villageName") String villageName, + @RequestPart("noOfPragnentWoment") String noOfPragnentWomen, + @RequestPart("noOfLactingMother") String noOfLactingMother, + @RequestPart("mitaninActivityCheckList") List mitaninActivityCheckList, @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, @RequestPart("participants") String participants, @@ -48,6 +52,11 @@ public ResponseEntity saveMeeting( dto.setParticipants(Integer.parseInt(participants)); dto.setAshaId(Integer.parseInt(ashaId)); dto.setCreatedBY(createdBy); + dto.setVillageName(villageName); + dto.setNoOfLactingMother(Integer.parseInt(noOfLactingMother)); + dto.setNoOfPragnentWomen(Integer.parseInt(noOfPragnentWomen)); + dto.setMitaninActivityCheckList(mitaninActivityCheckList); + dto.setMeetingImages(meetingImages != null ? meetingImages.toArray(new MultipartFile[0]) : null); if (dto != null) { service.saveMeeting(dto); diff --git a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java index 2bfb29700..0e8437141 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java @@ -5,6 +5,7 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.util.List; @Entity @Data @@ -39,6 +40,18 @@ public class MaaMeeting { @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/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java index 9d4c19b1d..8211be661 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -1,10 +1,12 @@ 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 { @@ -14,5 +16,9 @@ public class MaaMeetingRequestDTO { private Integer participants; private MultipartFile[] meetingImages; // up to 5 images private Integer ashaId; + private String villageName; + private Integer noOfPragnentWomen; + private Integer noOfLactingMother; + private List 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 index 9ba81ad82..0f1f6e67d 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java @@ -35,6 +35,11 @@ public class MaaMeetingResponseDTO { example = "[\"iVBORw0KGgoAAAANSUhEUgAA...\", \"iVBORw0KGgoAAAANSUhEUgBB...\"]") private List meetingImages; + private String villageName; + private String noOfPragnentWomen; + private String noOfLactingMother; + private List mitaninActivityCheckList; + @Column(name = "created_by") private String createdBy; diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 2c48df267..97a5a6026 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -46,6 +46,12 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { meeting.setPlace(req.getPlace()); meeting.setParticipants(req.getParticipants()); meeting.setAshaId(req.getAshaId()); + meeting.setNoOfLactingMother(req.getNoOfLactingMother()); + meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); + meeting.setVillageName(req.getVillageName()); + String checklistJson = + objectMapper.writeValueAsString(req.getMitaninActivityCheckList()); + meeting.setMitaninActivityCheckList(checklistJson); meeting.setCreatedBy(req.getCreatedBY()); // Convert meeting images to Base64 JSON @@ -102,7 +108,7 @@ public MaaMeeting updateMeeting(MaaMeetingRequestDTO req) throws JsonProcessingE } checkAndAddIncentive(existingMeeting); - if(existingMeeting.getMeetingImagesJson()!=null){ + if (existingMeeting.getMeetingImagesJson() != null) { checkAndUpdateIncentive(existingMeeting); } @@ -119,8 +125,6 @@ private String convertToBase64(MultipartFile file) { } - - public List getAllMeetings(GetBenRequestHandler getBenRequestHandler) throws Exception { List meetings = repository.findByAshaId(getBenRequestHandler.getAshaId()); @@ -131,13 +135,28 @@ public List getAllMeetings(GetBenRequestHandler getBenReq 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())); + List checklist = + null; + try { + checklist = objectMapper.readValue( + meeting.getMitaninActivityCheckList(), + new TypeReference>() {} + ); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + dto.setMitaninActivityCheckList(checklist); dto.setCreatedBy(meeting.getCreatedBy()); try { if (meeting.getMeetingImagesJson() != null) { List base64Images = objectMapper.readValue( meeting.getMeetingImagesJson(), - new TypeReference>() {} + new TypeReference>() { + } ); dto.setMeetingImages(base64Images); @@ -151,45 +170,48 @@ public List getAllMeetings(GetBenRequestHandler getBenReq return dto; }).collect(Collectors.toList()); } - private void updatePendingActivity(Integer userId,Long recordId,Long activityId,String moduleName){ + + 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){ + 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 (incentiveActivityAM != null) { + updateIncentive(incentiveActivityAM, meeting); } - if(incentiveActivityCH!=null){ - updateIncentive(incentiveActivityCH,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); + if (incentiveActivityAM != null) { + addIncentive(incentiveActivityAM, meeting); + } + if (incentiveActivityCH != null) { + addIncentive(incentiveActivityCH, meeting); - } + } } - private void addIncentive(IncentiveActivity incentiveActivity,MaaMeeting meeting){ + private void addIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L,meeting.getAshaId()); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); if (record == null) { record = new IncentiveActivityRecord(); @@ -202,11 +224,11 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(meeting.getCreatedBy()); record.setBenId(0L); record.setAshaId(meeting.getAshaId()); - if(meeting.getMeetingImagesJson()!=null){ + if (meeting.getMeetingImagesJson() != null) { record.setIsEligible(true); - }else { + } else { record.setIsEligible(false); - updatePendingActivity(meeting.getAshaId(),meeting.getId(),record.getId(),"MAA_MEETING"); + updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); } record.setAmount(Long.valueOf(incentiveActivity.getRate())); @@ -215,11 +237,11 @@ record = new IncentiveActivityRecord(); } - private void updateIncentive(IncentiveActivity incentiveActivity,MaaMeeting meeting){ + private void updateIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L,meeting.getAshaId()); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); - if (record!= null) { + if (record != null) { record = new IncentiveActivityRecord(); record.setIsEligible(true); recordRepo.save(record); From 27d624dd803b1c7009c00bf9ad2362309756a16e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 12:05:27 +0530 Subject: [PATCH 042/450] fix column type issue --- .../flw/controller/MaaMeetingController.java | 2 +- .../iemr/flw/dto/iemr/MaaMeetingRequestDTO.java | 2 +- .../iemr/flw/dto/iemr/MaaMeetingResponseDTO.java | 2 +- .../com/iemr/flw/service/MaaMeetingService.java | 16 ++-------------- 4 files changed, 5 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 1ed1bb014..83741682b 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -38,7 +38,7 @@ public ResponseEntity saveMeeting( @RequestPart("villageName") String villageName, @RequestPart("noOfPragnentWoment") String noOfPragnentWomen, @RequestPart("noOfLactingMother") String noOfLactingMother, - @RequestPart("mitaninActivityCheckList") List mitaninActivityCheckList, + @RequestPart("mitaninActivityCheckList") String mitaninActivityCheckList, @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, @RequestPart("participants") String participants, diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java index 8211be661..e4ca6af5e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -19,6 +19,6 @@ public class MaaMeetingRequestDTO { private String villageName; private Integer noOfPragnentWomen; private Integer noOfLactingMother; - private List mitaninActivityCheckList; + 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 index 0f1f6e67d..b56356c2d 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java @@ -38,7 +38,7 @@ public class MaaMeetingResponseDTO { private String villageName; private String noOfPragnentWomen; private String noOfLactingMother; - private List mitaninActivityCheckList; + private String mitaninActivityCheckList; @Column(name = "created_by") private String createdBy; diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 97a5a6026..9c103078b 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -49,9 +49,7 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { meeting.setNoOfLactingMother(req.getNoOfLactingMother()); meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); meeting.setVillageName(req.getVillageName()); - String checklistJson = - objectMapper.writeValueAsString(req.getMitaninActivityCheckList()); - meeting.setMitaninActivityCheckList(checklistJson); + meeting.setMitaninActivityCheckList(req.getMitaninActivityCheckList()); meeting.setCreatedBy(req.getCreatedBY()); // Convert meeting images to Base64 JSON @@ -138,17 +136,7 @@ public List getAllMeetings(GetBenRequestHandler getBenReq dto.setVillageName(meeting.getVillageName()); dto.setNoOfLactingMother(String.valueOf(meeting.getNoOfLactingMother())); dto.setNoOfPragnentWomen(String.valueOf(meeting.getNoOfPragnentWomen())); - List checklist = - null; - try { - checklist = objectMapper.readValue( - meeting.getMitaninActivityCheckList(), - new TypeReference>() {} - ); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - dto.setMitaninActivityCheckList(checklist); + dto.setMitaninActivityCheckList(meeting.getMitaninActivityCheckList()); dto.setCreatedBy(meeting.getCreatedBy()); try { From 862d708435b4920bdcab5cc5e9862cdf76972baf Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 12:12:33 +0530 Subject: [PATCH 043/450] AMM-2100 --- .../java/com/iemr/flw/domain/iemr/PHCReviewForm.java | 12 ++++++++++++ .../iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java index 50ec33756..d65ff5518 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java @@ -42,6 +42,18 @@ public class PHCReviewForm { @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/dto/iemr/PhcReviewMeetingFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java index 00830988c..e94e34b26 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java @@ -1,5 +1,6 @@ package com.iemr.flw.dto.iemr; +import jakarta.persistence.Column; import lombok.Data; @Data @@ -8,6 +9,10 @@ public class PhcReviewMeetingFormDTO { 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; From d6c0aa0852cffd0abf190da6c9154c5bc07db976 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 12:12:54 +0530 Subject: [PATCH 044/450] AMM-2100 --- .../iemr/flw/service/impl/VillageLevelFormServiceImpl.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index a4df2b7d4..fbaff0d5b 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -157,6 +157,10 @@ private Boolean savePhcForm(PhcReviewMeetingFormDTO dto, Integer userID) { 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); From 18094526fee9dbf92e278a7fbc5a175b512480a7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 12:14:31 +0530 Subject: [PATCH 045/450] AMM-2100 --- src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java | 1 + src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java | 1 - src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java | 1 + .../com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java | 1 + 4 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java index d65ff5518..4dea0ce7c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PHCReviewForm.java @@ -56,4 +56,5 @@ public class PHCReviewForm { @Column(name = "form_type") private String formType; + } \ 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 index 4efc6dccb..a943affec 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java @@ -26,7 +26,6 @@ import jakarta.persistence.*; import lombok.Data; - import java.sql.Timestamp; import java.util.Date; diff --git a/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java index e94e34b26..b08386c6e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PhcReviewMeetingFormDTO.java @@ -17,4 +17,5 @@ public class PhcReviewMeetingFormDTO { private String image2; + } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index fbaff0d5b..c64654d33 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -232,6 +232,7 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { } + @Override public List getAll(GetVillageLevelRequestHandler getVillageLevelRequestHandler) { if (Objects.equals(getVillageLevelRequestHandler.getFormType(), "VHND")) { From 40d8b228b098cc283f614ae7375766684c6a4496 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 18:16:03 +0530 Subject: [PATCH 046/450] AMM-2102 --- .../iemr/flw/controller/MaaMeetingController.java | 2 ++ .../java/com/iemr/flw/domain/iemr/MaaMeeting.java | 3 +++ .../com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java | 1 + .../iemr/flw/dto/iemr/MaaMeetingResponseDTO.java | 1 + .../com/iemr/flw/service/MaaMeetingService.java | 13 +++++++++++++ 5 files changed, 20 insertions(+) diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 83741682b..0b247fe39 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -38,6 +38,7 @@ public ResponseEntity saveMeeting( @RequestPart("villageName") String villageName, @RequestPart("noOfPragnentWoment") String noOfPragnentWomen, @RequestPart("noOfLactingMother") String noOfLactingMother, + @RequestPart("isSelectAll") String isSelectAll, @RequestPart("mitaninActivityCheckList") String mitaninActivityCheckList, @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, @@ -53,6 +54,7 @@ public ResponseEntity saveMeeting( dto.setAshaId(Integer.parseInt(ashaId)); dto.setCreatedBY(createdBy); dto.setVillageName(villageName); + dto.setIsSelectAll(isSelectAll); dto.setNoOfLactingMother(Integer.parseInt(noOfLactingMother)); dto.setNoOfPragnentWomen(Integer.parseInt(noOfPragnentWomen)); dto.setMitaninActivityCheckList(mitaninActivityCheckList); diff --git a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java index 0e8437141..90cca318f 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java @@ -52,6 +52,9 @@ public class MaaMeeting { @Column(name = "mitanin_activity_checkList") private String mitaninActivityCheckList; + @Column(name = "is_select_all") + private Boolean isSelectAll; + @Column(name = "created_by") private String createdBy; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java index e4ca6af5e..b0a67e55e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -20,5 +20,6 @@ public class MaaMeetingRequestDTO { private Integer noOfPragnentWomen; private Integer noOfLactingMother; private String mitaninActivityCheckList; + private String isSelectAll; 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 index b56356c2d..29c571671 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java @@ -39,6 +39,7 @@ public class MaaMeetingResponseDTO { private String noOfPragnentWomen; private String noOfLactingMother; private String mitaninActivityCheckList; + private String isSelectAll; @Column(name = "created_by") private String createdBy; diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 9c103078b..350c91250 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -50,6 +50,12 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); meeting.setVillageName(req.getVillageName()); meeting.setMitaninActivityCheckList(req.getMitaninActivityCheckList()); + if(Objects.equals(req.getIsSelectAll(), "Yes")){ + meeting.setIsSelectAll(true); + }else { + meeting.setIsSelectAll(false); + + } meeting.setCreatedBy(req.getCreatedBY()); // Convert meeting images to Base64 JSON @@ -137,6 +143,13 @@ public List getAllMeetings(GetBenRequestHandler getBenReq dto.setNoOfLactingMother(String.valueOf(meeting.getNoOfLactingMother())); dto.setNoOfPragnentWomen(String.valueOf(meeting.getNoOfPragnentWomen())); dto.setMitaninActivityCheckList(meeting.getMitaninActivityCheckList()); + if(meeting.getIsSelectAll()){ + dto.setIsSelectAll("Yes"); + + }else { + dto.setIsSelectAll("No"); + + } dto.setCreatedBy(meeting.getCreatedBy()); try { From de29668af3620e728f46c1837a69938ace87b247 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 13 Jan 2026 18:24:41 +0530 Subject: [PATCH 047/450] AMM-2102 --- .../java/com/iemr/flw/domain/iemr/MaaMeeting.java | 2 +- .../com/iemr/flw/service/MaaMeetingService.java | 14 ++------------ 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java index 90cca318f..364ecb570 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java @@ -53,7 +53,7 @@ public class MaaMeeting { private String mitaninActivityCheckList; @Column(name = "is_select_all") - private Boolean isSelectAll; + private String isSelectAll; @Column(name = "created_by") private String createdBy; diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 350c91250..631398f97 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -50,12 +50,8 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); meeting.setVillageName(req.getVillageName()); meeting.setMitaninActivityCheckList(req.getMitaninActivityCheckList()); - if(Objects.equals(req.getIsSelectAll(), "Yes")){ - meeting.setIsSelectAll(true); - }else { - meeting.setIsSelectAll(false); + meeting.setIsSelectAll(req.getIsSelectAll()); - } meeting.setCreatedBy(req.getCreatedBY()); // Convert meeting images to Base64 JSON @@ -143,13 +139,7 @@ public List getAllMeetings(GetBenRequestHandler getBenReq dto.setNoOfLactingMother(String.valueOf(meeting.getNoOfLactingMother())); dto.setNoOfPragnentWomen(String.valueOf(meeting.getNoOfPragnentWomen())); dto.setMitaninActivityCheckList(meeting.getMitaninActivityCheckList()); - if(meeting.getIsSelectAll()){ - dto.setIsSelectAll("Yes"); - - }else { - dto.setIsSelectAll("No"); - - } + dto.setIsSelectAll(meeting.getIsSelectAll()); dto.setCreatedBy(meeting.getCreatedBy()); try { From 07e0cd5b4e85480d814f82bcfde919e8e7e062e8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 14 Jan 2026 12:08:26 +0530 Subject: [PATCH 048/450] AMM-2102 remove select all column --- .../java/com/iemr/flw/controller/MaaMeetingController.java | 2 -- src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java | 3 --- src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java | 1 - src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java | 1 - src/main/java/com/iemr/flw/service/MaaMeetingService.java | 2 -- 5 files changed, 9 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 0b247fe39..83741682b 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -38,7 +38,6 @@ public ResponseEntity saveMeeting( @RequestPart("villageName") String villageName, @RequestPart("noOfPragnentWoment") String noOfPragnentWomen, @RequestPart("noOfLactingMother") String noOfLactingMother, - @RequestPart("isSelectAll") String isSelectAll, @RequestPart("mitaninActivityCheckList") String mitaninActivityCheckList, @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, @@ -54,7 +53,6 @@ public ResponseEntity saveMeeting( dto.setAshaId(Integer.parseInt(ashaId)); dto.setCreatedBY(createdBy); dto.setVillageName(villageName); - dto.setIsSelectAll(isSelectAll); dto.setNoOfLactingMother(Integer.parseInt(noOfLactingMother)); dto.setNoOfPragnentWomen(Integer.parseInt(noOfPragnentWomen)); dto.setMitaninActivityCheckList(mitaninActivityCheckList); diff --git a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java index 364ecb570..0e8437141 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MaaMeeting.java @@ -52,9 +52,6 @@ public class MaaMeeting { @Column(name = "mitanin_activity_checkList") private String mitaninActivityCheckList; - @Column(name = "is_select_all") - private String isSelectAll; - @Column(name = "created_by") private String createdBy; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java index b0a67e55e..e4ca6af5e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingRequestDTO.java @@ -20,6 +20,5 @@ public class MaaMeetingRequestDTO { private Integer noOfPragnentWomen; private Integer noOfLactingMother; private String mitaninActivityCheckList; - private String isSelectAll; 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 index 29c571671..b56356c2d 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MaaMeetingResponseDTO.java @@ -39,7 +39,6 @@ public class MaaMeetingResponseDTO { private String noOfPragnentWomen; private String noOfLactingMother; private String mitaninActivityCheckList; - private String isSelectAll; @Column(name = "created_by") private String createdBy; diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 631398f97..d3319821c 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -50,7 +50,6 @@ public MaaMeeting saveMeeting(MaaMeetingRequestDTO req) throws Exception { meeting.setNoOfPragnentWomen(req.getNoOfPragnentWomen()); meeting.setVillageName(req.getVillageName()); meeting.setMitaninActivityCheckList(req.getMitaninActivityCheckList()); - meeting.setIsSelectAll(req.getIsSelectAll()); meeting.setCreatedBy(req.getCreatedBY()); @@ -139,7 +138,6 @@ public List getAllMeetings(GetBenRequestHandler getBenReq dto.setNoOfLactingMother(String.valueOf(meeting.getNoOfLactingMother())); dto.setNoOfPragnentWomen(String.valueOf(meeting.getNoOfPragnentWomen())); dto.setMitaninActivityCheckList(meeting.getMitaninActivityCheckList()); - dto.setIsSelectAll(meeting.getIsSelectAll()); dto.setCreatedBy(meeting.getCreatedBy()); try { From 33e1faf29cd831b1d81f85920624ccbef24139a3 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 14 Jan 2026 12:47:46 +0530 Subject: [PATCH 049/450] fix pending incentive code --- src/main/java/com/iemr/flw/service/MaaMeetingService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index d3319821c..cb23b7b9c 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -217,7 +217,7 @@ record = new IncentiveActivityRecord(); record.setIsEligible(true); } else { record.setIsEligible(false); - updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); + // updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); } record.setAmount(Long.valueOf(incentiveActivity.getRate())); From e310c5c442866e610bc48c65149f8c2f4e86a9d2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:29:22 +0530 Subject: [PATCH 050/450] api for ORS campaign AMM-2104 --- .../flw/controller/CampaignController.java | 78 ++++++++++++++++ .../com/iemr/flw/domain/iemr/CampaignOrs.java | 63 +++++++++++++ .../com/iemr/flw/dto/iemr/OrsCampaignDTO.java | 10 ++ .../iemr/flw/dto/iemr/OrsCampaignListDTO.java | 16 ++++ .../iemr/flw/repo/iemr/OrsCampaignRepo.java | 17 ++++ .../com/iemr/flw/service/CampaignService.java | 11 +++ .../flw/service/impl/CampaignServiceImpl.java | 92 +++++++++++++++++++ 7 files changed, 287 insertions(+) create mode 100644 src/main/java/com/iemr/flw/controller/CampaignController.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/OrsCampaignDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/OrsCampaignRepo.java create mode 100644 src/main/java/com/iemr/flw/service/CampaignService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java 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 000000000..3ee70aeef --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -0,0 +1,78 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.service.CampaignService; +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.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping(value = "/Campaign") +public class CampaignController { + private final Logger logger = LoggerFactory.getLogger(CampaignController.class); + + @Autowired + private CampaignService campaignService; + + @RequestMapping(value = "ors/distribution/saveAll", method = RequestMethod.POST) + public ResponseEntity> saveOrsDistribution(@RequestBody List orsCampaignDTO, @RequestHeader(value = "jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + Object result = campaignService.saveOrsCampaign(orsCampaignDTO,token); + + + if (result != null) { + 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 save ors distribution :", 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/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.NOT_FOUND.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + } + + } catch (Exception e) { + logger.error("Error save ors distribution :", 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/domain/iemr/CampaignOrs.java b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java new file mode 100644 index 000000000..b9fab48e6 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java @@ -0,0 +1,63 @@ +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") +@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; + + /** + * 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/dto/iemr/OrsCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignDTO.java new file mode 100644 index 000000000..dbd83c26b --- /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 000000000..1b2d64f43 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -0,0 +1,16 @@ +package com.iemr.flw.dto.iemr; + +import com.google.gson.annotations.SerializedName; +import lombok.Data; + +import java.sql.Timestamp; + +@Data +public class OrsCampaignListDTO { + private String visit_date; + private Timestamp end_date; + private String number_of_families; + private String campaign_photos; + + +} 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 000000000..fbbe380bb --- /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/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java new file mode 100644 index 000000000..05f1f4be4 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -0,0 +1,11 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.utils.exception.IEMRException; + +import java.util.List; + +public interface CampaignService { + Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; + List getOrsCampaign(String token) throws IEMRException; +} 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 000000000..67d98fea5 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -0,0 +1,92 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.repo.iemr.OrsCampaignRepo; +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 java.util.ArrayList; +import java.util.List; + +@Service +public class CampaignServiceImpl implements CampaignService { + + @Autowired + private OrsCampaignRepo orsCampaignRepo; + + @Autowired + private JwtUtil jwtUtil; + + @Override + public Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException { + if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { + return null; + } + + List campaignOrsRequest = new ArrayList<>(); + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + + for (OrsCampaignDTO campaignDTO : orsCampaignDTO) { + if (campaignDTO.getFields() == null) { + continue; // or throw exception based on your requirements + } + + CampaignOrs campaignOrsEntity = new CampaignOrs(); // Create new entity for each DTO + campaignOrsEntity.setUserId(userId); + campaignOrsEntity.setCreatedBy(userName); + campaignOrsEntity.setUpdatedBy(userName); + + try { + campaignOrsEntity.setNumberOfFamilies( + Integer.parseInt(campaignDTO.getFields().getNumber_of_families()) + ); + } catch (NumberFormatException e) { + // Handle invalid number format - log or throw exception + throw new IEMRException("Invalid number format for families"); + } + + campaignOrsEntity.setCampaignPhotos(campaignDTO.getFields().getCampaign_photos()); + campaignOrsRequest.add(campaignOrsEntity); + } + + if (!campaignOrsRequest.isEmpty()) { + orsCampaignRepo.saveAll(campaignOrsRequest); + return campaignOrsRequest; + } + + return null; + } + + @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()){ + OrsCampaignDTO dto = convertToDTO(campaignOrs); + orsCampaignDTOSResponse.add(dto); + } + page++; + }while (campaignOrsPage.hasNext()); + return orsCampaignDTOSResponse; + } + private OrsCampaignDTO convertToDTO(CampaignOrs campaign) { + OrsCampaignDTO dto = new OrsCampaignDTO(); + // Set DTO fields from entity + // dto.setXxx(campaign.getXxx()); + return dto; + } +} From ba717c66e5a8d2ae9f9610e0efd62993236d02df Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:33:10 +0530 Subject: [PATCH 051/450] api for ORS campaign AMM-2104 --- src/main/java/com/iemr/flw/controller/CampaignController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 3ee70aeef..1ca2d695c 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -14,7 +14,7 @@ import java.util.Map; @RestController -@RequestMapping(value = "/Campaign") +@RequestMapping(value = "/campaign") public class CampaignController { private final Logger logger = LoggerFactory.getLogger(CampaignController.class); From 8e7a8f34558a35c2f72e8a3bde6977086c4d1351 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:47:35 +0530 Subject: [PATCH 052/450] api for ORS campaign AMM-2104 --- .../java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java | 5 +++-- .../com/iemr/flw/service/impl/CampaignServiceImpl.java | 9 +++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 1b2d64f43..f10ce4d17 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -4,11 +4,12 @@ import lombok.Data; import java.sql.Timestamp; +import java.time.LocalDate; @Data public class OrsCampaignListDTO { - private String visit_date; - private Timestamp end_date; + private LocalDate start_date; + private LocalDate end_date; private String number_of_families; private String campaign_photos; diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 67d98fea5..f072144d7 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -2,6 +2,7 @@ import com.iemr.flw.domain.iemr.CampaignOrs; import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.dto.iemr.OrsCampaignListDTO; import com.iemr.flw.repo.iemr.OrsCampaignRepo; import com.iemr.flw.service.CampaignService; import com.iemr.flw.utils.JwtUtil; @@ -85,8 +86,12 @@ public List getOrsCampaign(String token) throws IEMRException { } private OrsCampaignDTO convertToDTO(CampaignOrs campaign) { OrsCampaignDTO dto = new OrsCampaignDTO(); - // Set DTO fields from entity - // dto.setXxx(campaign.getXxx()); + OrsCampaignListDTO orsCampaignListDTO = new OrsCampaignListDTO(); + orsCampaignListDTO.setCampaign_photos(campaign.getCampaignPhotos()); + orsCampaignListDTO.setEnd_date(campaign.getEndDate()); + orsCampaignListDTO.setStart_date(campaign.getStartDate()); + orsCampaignListDTO.setNumber_of_families(String.valueOf(campaign.getNumberOfFamilies())); + dto.setFields(orsCampaignListDTO); return dto; } } From a2ea2ca3358b8f78a810b8a4ae689cabab9ea043 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:51:55 +0530 Subject: [PATCH 053/450] api for ORS campaign AMM-2104 --- .../iemr/flw/dto/iemr/OrsCampaignListDTO.java | 16 ++++++++++++---- .../flw/service/impl/CampaignServiceImpl.java | 12 ++++++------ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index f10ce4d17..3ed417b21 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -1,5 +1,6 @@ package com.iemr.flw.dto.iemr; +import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.SerializedName; import lombok.Data; @@ -8,10 +9,17 @@ @Data public class OrsCampaignListDTO { - private LocalDate start_date; - private LocalDate end_date; - private String number_of_families; - private String campaign_photos; + @JsonProperty("start_date") + private LocalDate StartDate; + + @JsonProperty("end_date") + private LocalDate EndDate; + + @JsonProperty("number_of_families") + private String NumberOfFamilies; + + @JsonProperty("campaign_photos") + private String CampaignPhotos; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index f072144d7..0955aee75 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -47,14 +47,14 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) try { campaignOrsEntity.setNumberOfFamilies( - Integer.parseInt(campaignDTO.getFields().getNumber_of_families()) + Integer.parseInt(campaignDTO.getFields().getNumberOfFamilies()) ); } catch (NumberFormatException e) { // Handle invalid number format - log or throw exception throw new IEMRException("Invalid number format for families"); } - campaignOrsEntity.setCampaignPhotos(campaignDTO.getFields().getCampaign_photos()); + campaignOrsEntity.setCampaignPhotos(campaignDTO.getFields().getCampaignPhotos()); campaignOrsRequest.add(campaignOrsEntity); } @@ -87,10 +87,10 @@ public List getOrsCampaign(String token) throws IEMRException { private OrsCampaignDTO convertToDTO(CampaignOrs campaign) { OrsCampaignDTO dto = new OrsCampaignDTO(); OrsCampaignListDTO orsCampaignListDTO = new OrsCampaignListDTO(); - orsCampaignListDTO.setCampaign_photos(campaign.getCampaignPhotos()); - orsCampaignListDTO.setEnd_date(campaign.getEndDate()); - orsCampaignListDTO.setStart_date(campaign.getStartDate()); - orsCampaignListDTO.setNumber_of_families(String.valueOf(campaign.getNumberOfFamilies())); + orsCampaignListDTO.setCampaignPhotos(campaign.getCampaignPhotos()); + orsCampaignListDTO.setEndDate(campaign.getEndDate()); + orsCampaignListDTO.setStartDate(campaign.getStartDate()); + orsCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); dto.setFields(orsCampaignListDTO); return dto; } From 5e3e951508ac35040a363c79bac39b8a7a2c10dd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:53:02 +0530 Subject: [PATCH 054/450] api for ORS campaign AMM-2104 --- src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java index b9fab48e6..9d4c5c1ad 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java +++ b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java @@ -7,7 +7,7 @@ import java.time.LocalDateTime; @Entity -@Table(name = "campaign_ors") +@Table(name = "campaign_ors",schema = "db_iemr") @Data public class CampaignOrs { From f1cb12f9d2dbf0ff0fad634dd915a77737e31cf8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:54:43 +0530 Subject: [PATCH 055/450] api for ORS campaign AMM-2104 --- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 0955aee75..917b2662b 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -12,6 +12,7 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @@ -26,6 +27,7 @@ public class CampaignServiceImpl implements CampaignService { private JwtUtil jwtUtil; @Override + @Transactional public Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException { if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { return null; @@ -67,6 +69,7 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) } @Override + @Transactional public List getOrsCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); List orsCampaignDTOSResponse = new ArrayList<>(); From 6cdbbf8f7a1b2699d93820b0e17ab89e48c7d7b1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:55:15 +0530 Subject: [PATCH 056/450] api for ORS campaign AMM-2104 --- src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 917b2662b..3ef919d24 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -69,7 +69,6 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) } @Override - @Transactional public List getOrsCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); List orsCampaignDTOSResponse = new ArrayList<>(); From 33b0fa19f3a56ea5b74616bb14232087eb22a888 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 14:57:46 +0530 Subject: [PATCH 057/450] api for ORS campaign AMM-2104 --- .../flw/service/impl/CampaignServiceImpl.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 3ef919d24..98ae7eb24 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -15,6 +15,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; +import java.util.Collections; import java.util.List; @Service @@ -28,9 +29,9 @@ public class CampaignServiceImpl implements CampaignService { @Override @Transactional - public Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException { + public List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException { if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { - return null; + return Collections.emptyList(); // } List campaignOrsRequest = new ArrayList<>(); @@ -39,10 +40,10 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) for (OrsCampaignDTO campaignDTO : orsCampaignDTO) { if (campaignDTO.getFields() == null) { - continue; // or throw exception based on your requirements + continue; } - CampaignOrs campaignOrsEntity = new CampaignOrs(); // Create new entity for each DTO + CampaignOrs campaignOrsEntity = new CampaignOrs(); campaignOrsEntity.setUserId(userId); campaignOrsEntity.setCreatedBy(userName); campaignOrsEntity.setUpdatedBy(userName); @@ -52,7 +53,6 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) Integer.parseInt(campaignDTO.getFields().getNumberOfFamilies()) ); } catch (NumberFormatException e) { - // Handle invalid number format - log or throw exception throw new IEMRException("Invalid number format for families"); } @@ -61,11 +61,11 @@ public Object saveOrsCampaign(List orsCampaignDTO, String token) } if (!campaignOrsRequest.isEmpty()) { - orsCampaignRepo.saveAll(campaignOrsRequest); - return campaignOrsRequest; + List savedCampaigns = orsCampaignRepo.saveAll(campaignOrsRequest); + return savedCampaigns; } - return null; + return Collections.emptyList(); } @Override From 2a87fea8a0cf9ebf0277e90097237e4a71740094 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 16:56:57 +0530 Subject: [PATCH 058/450] api for Pulse polio campaign AMM-2105 --- .../flw/controller/CampaignController.java | 61 ++++++++++++- .../flw/domain/iemr/PulsePolioCampaign.java | 63 +++++++++++++ .../iemr/flw/dto/iemr/PolioCampaignDTO.java | 10 +++ .../flw/dto/iemr/PolioCampaignListDTO.java | 23 +++++ .../flw/repo/iemr/PulsePolioCampaignRepo.java | 13 +++ .../com/iemr/flw/service/CampaignService.java | 4 + .../flw/service/impl/CampaignServiceImpl.java | 90 ++++++++++++++++++- 7 files changed, 260 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PolioCampaignDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/PulsePolioCampaignRepo.java diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 1ca2d695c..730fb46de 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -1,6 +1,7 @@ package com.iemr.flw.controller; import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.dto.iemr.PolioCampaignDTO; import com.iemr.flw.service.CampaignService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +42,7 @@ public ResponseEntity> saveOrsDistribution(@RequestBody List } } catch (Exception e) { - logger.error("Error save ors distribution :", 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); @@ -69,7 +70,63 @@ public ResponseEntity> getAllOrsDistribution(@RequestHeader( } } catch (Exception e) { - logger.error("Error save ors distribution :", 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); + } + } + + + @RequestMapping(value = "polio/campaign/saveAll", method = RequestMethod.POST) + public ResponseEntity> savePolioCampaign(@RequestBody List polioCampaignDTOS, @RequestHeader(value = "jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + Object result = campaignService.savePolioCampaign(polioCampaignDTOS,token); + + + if (result != null) { + 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 save polio:", e.getMessage()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + 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.NOT_FOUND.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND).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/domain/iemr/PulsePolioCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java new file mode 100644 index 000000000..446217eb2 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java @@ -0,0 +1,63 @@ +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; + + /** + * 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/dto/iemr/PolioCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignDTO.java new file mode 100644 index 000000000..7f6cfc87b --- /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 000000000..5c172ffab --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -0,0 +1,23 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.time.LocalDate; + +@Data +public class PolioCampaignListDTO { + @JsonProperty("start_date") + private LocalDate startDate; + + @JsonProperty("end_date") + private LocalDate endDate; + + @JsonProperty("number_of_children") + private String numberOfChildren; + + @JsonProperty("campaign_photos") + private String campaignPhotos; + + +} 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 000000000..c2cded971 --- /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/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index 05f1f4be4..e73016656 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -1,11 +1,15 @@ package com.iemr.flw.service; import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.dto.iemr.PolioCampaignDTO; import com.iemr.flw.utils.exception.IEMRException; import java.util.List; public interface CampaignService { Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; + Object savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException; List getOrsCampaign(String token) throws IEMRException; + + List getPolioCampaign(String token) throws IEMRException; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 98ae7eb24..6baade1a4 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -1,9 +1,13 @@ package com.iemr.flw.service.impl; import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; import com.iemr.flw.dto.iemr.OrsCampaignDTO; import com.iemr.flw.dto.iemr.OrsCampaignListDTO; +import com.iemr.flw.dto.iemr.PolioCampaignDTO; +import com.iemr.flw.dto.iemr.PolioCampaignListDTO; import com.iemr.flw.repo.iemr.OrsCampaignRepo; +import com.iemr.flw.repo.iemr.PulsePolioCampaignRepo; import com.iemr.flw.service.CampaignService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.exception.IEMRException; @@ -24,6 +28,9 @@ public class CampaignServiceImpl implements CampaignService { @Autowired private OrsCampaignRepo orsCampaignRepo; + @Autowired + private PulsePolioCampaignRepo pulsePolioCampaignRepo; + @Autowired private JwtUtil jwtUtil; @@ -79,14 +86,77 @@ public List getOrsCampaign(String token) throws IEMRException { Pageable pageable = PageRequest.of(page,pageSize); campaignOrsPage = orsCampaignRepo.findByUserId(userId,pageable); for(CampaignOrs campaignOrs:campaignOrsPage.getContent()){ - OrsCampaignDTO dto = convertToDTO(campaignOrs); + OrsCampaignDTO dto = convertOrsToDTO(campaignOrs); orsCampaignDTOSResponse.add(dto); } page++; }while (campaignOrsPage.hasNext()); return orsCampaignDTOSResponse; } - private OrsCampaignDTO convertToDTO(CampaignOrs campaign) { + + + @Override + @Transactional + public List savePolioCampaign(List orsCampaignDTO, String token) throws IEMRException { + if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { + return Collections.emptyList(); // + } + + List campaignPolioRequest = new ArrayList<>(); + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + + for (PolioCampaignDTO campaignDTO : orsCampaignDTO) { + if (campaignDTO.getFields() == null) { + continue; + } + + PulsePolioCampaign campaignPolioEntity = new PulsePolioCampaign(); + campaignPolioEntity.setUserId(userId); + campaignPolioEntity.setCreatedBy(userName); + campaignPolioEntity.setUpdatedBy(userName); + + try { + campaignPolioEntity.setNumberOfChildren( + Integer.parseInt(campaignDTO.getFields().getNumberOfChildren()) + ); + } catch (NumberFormatException e) { + throw new IEMRException("Invalid number format for families"); + } + + campaignPolioEntity.setCampaignPhotos(campaignDTO.getFields().getCampaignPhotos()); + campaignPolioRequest.add(campaignPolioEntity); + } + + if (!campaignPolioRequest.isEmpty()) { + List savedCampaigns = pulsePolioCampaignRepo.saveAll(campaignPolioRequest); + return savedCampaigns; + } + + return Collections.emptyList(); + } + + @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()){ + PolioCampaignDTO dto = convertPolioToDTO(campaignOrs); + polioCampaignDTOSResponse.add(dto); + } + page++; + }while (campaignPolioPage.hasNext()); + return polioCampaignDTOSResponse; + } + + + private OrsCampaignDTO convertOrsToDTO(CampaignOrs campaign) { OrsCampaignDTO dto = new OrsCampaignDTO(); OrsCampaignListDTO orsCampaignListDTO = new OrsCampaignListDTO(); orsCampaignListDTO.setCampaignPhotos(campaign.getCampaignPhotos()); @@ -96,4 +166,20 @@ private OrsCampaignDTO convertToDTO(CampaignOrs campaign) { dto.setFields(orsCampaignListDTO); return dto; } + + private PolioCampaignDTO convertPolioToDTO(PulsePolioCampaign campaign) { + PolioCampaignDTO dto = new PolioCampaignDTO(); + PolioCampaignListDTO polioCampaignListDTO = new PolioCampaignListDTO(); + polioCampaignListDTO.setCampaignPhotos(campaign.getCampaignPhotos()); + polioCampaignListDTO.setEndDate(campaign.getEndDate()); + polioCampaignListDTO.setStartDate(campaign.getStartDate()); + polioCampaignListDTO.setNumberOfChildren(String.valueOf(campaign.getNumberOfChildren())); + dto.setFields(polioCampaignListDTO); + return dto; + } + + + + + } From 44c18f784d2c87060130b47da3eca9e664908e40 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 15 Jan 2026 19:09:59 +0530 Subject: [PATCH 059/450] fix option parameter issue --- .../flw/controller/MaaMeetingController.java | 59 +++++++++++++------ 1 file changed, 40 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 83741682b..49c2236be 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -35,35 +35,56 @@ public MaaMeetingController(MaaMeetingService service) { @PostMapping(value = "/saveAll", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity saveMeeting( - @RequestPart("villageName") String villageName, - @RequestPart("noOfPragnentWoment") String noOfPragnentWomen, - @RequestPart("noOfLactingMother") String noOfLactingMother, - @RequestPart("mitaninActivityCheckList") String mitaninActivityCheckList, - @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) { + + @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(); - dto.setMeetingDate(LocalDate.parse(meetingDate)); + + if (meetingDate != null && !meetingDate.isEmpty()) { + dto.setMeetingDate(LocalDate.parse(meetingDate)); + } + dto.setPlace(place); - dto.setParticipants(Integer.parseInt(participants)); - dto.setAshaId(Integer.parseInt(ashaId)); - dto.setCreatedBY(createdBy); dto.setVillageName(villageName); - dto.setNoOfLactingMother(Integer.parseInt(noOfLactingMother)); - dto.setNoOfPragnentWomen(Integer.parseInt(noOfPragnentWomen)); dto.setMitaninActivityCheckList(mitaninActivityCheckList); + dto.setCreatedBY(createdBy); - dto.setMeetingImages(meetingImages != null ? meetingImages.toArray(new MultipartFile[0]) : null); - if (dto != null) { - service.saveMeeting(dto); + 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()); } } From 3c91469c4c78ab7b8bfd3938f1a6405ea35a21b9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 09:45:00 +0530 Subject: [PATCH 060/450] fix request issue in ors campaign --- .../flw/controller/CampaignController.java | 75 ++++++++++--- .../iemr/flw/dto/iemr/OrsCampaignListDTO.java | 3 +- .../dto/iemr/OrsCampaignListResponseDTO.java | 15 +++ .../flw/dto/iemr/OrsCampaignResponseDTO.java | 10 ++ .../com/iemr/flw/service/CampaignService.java | 3 +- .../flw/service/impl/CampaignServiceImpl.java | 101 +++++++++++++----- 6 files changed, 163 insertions(+), 44 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 730fb46de..16a0080d5 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -1,18 +1,22 @@ package com.iemr.flw.controller; -import com.iemr.flw.dto.iemr.OrsCampaignDTO; -import com.iemr.flw.dto.iemr.PolioCampaignDTO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import com.iemr.flw.domain.iemr.CampaignOrs; +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.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.sql.Timestamp; +import java.util.*; @RestController @RequestMapping(value = "/campaign") @@ -22,28 +26,69 @@ public class CampaignController { @Autowired private CampaignService campaignService; - @RequestMapping(value = "ors/distribution/saveAll", method = RequestMethod.POST) - public ResponseEntity> saveOrsDistribution(@RequestBody List orsCampaignDTO, @RequestHeader(value = "jwtToken") String token) { + @PostMapping("/ors/distribution/saveAll") + public ResponseEntity> saveOrsDistribution( + @RequestPart("formDataJson") String fields, + @RequestPart(value = "campaignPhotos", required = false) List campaignPhotos, + @RequestHeader("jwtToken") String token) { Map response = new LinkedHashMap<>(); try { - Object result = campaignService.saveOrsCampaign(orsCampaignDTO,token); + // 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()); + OrsCampaignListDTO orsCampaignFields = objectMapper.readValue(fields, OrsCampaignListDTO.class); + + // Set campaign photos if present + if (campaignPhotos != null && !campaignPhotos.isEmpty()) { + orsCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); + } + // Create DTO + OrsCampaignDTO campaignDTO = new OrsCampaignDTO(); + campaignDTO.setFields(orsCampaignFields); + + List orsCampaignDTOList = Collections.singletonList(campaignDTO); + + // Save to database + Object result = campaignService.saveOrsCampaign(orsCampaignDTOList, token); if (result != null) { - response.put("statusCode", HttpStatus.OK.value()); + response.put("statusCode", HttpStatus.CREATED.value()); + response.put("message", "Campaign saved successfully"); response.put("data", result); - return ResponseEntity.ok(response); + return ResponseEntity.status(HttpStatus.CREATED).body(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); - response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + 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 save ors distribution :", e.getMessage()); + 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); } @@ -56,7 +101,7 @@ public ResponseEntity> getAllOrsDistribution(@RequestHeader( Map response = new LinkedHashMap<>(); try { - List result = campaignService.getOrsCampaign(token); + List result = campaignService.getOrsCampaign(token); if (result != null) { diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 3ed417b21..7f8b67570 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -3,6 +3,7 @@ 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; @@ -19,7 +20,7 @@ public class OrsCampaignListDTO { private String NumberOfFamilies; @JsonProperty("campaign_photos") - private String CampaignPhotos; + private MultipartFile[] 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 000000000..7b8ec2dab --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java @@ -0,0 +1,15 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +import java.time.LocalDate; +import java.util.List; + +@Data +public class OrsCampaignListResponseDTO { + private Long id; + private LocalDate startDate; + private LocalDate endDate; + private String numberOfFamilies; + private List campaignPhotos; // Base64 or URLs +} \ 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 000000000..44351ddbf --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class OrsCampaignResponseDTO { + private Long id; + private String visitDate; + private OrsCampaignListResponseDTO fields; +} diff --git a/src/main/java/com/iemr/flw/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index e73016656..8c690e25c 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -1,6 +1,7 @@ package com.iemr.flw.service; import com.iemr.flw.dto.iemr.OrsCampaignDTO; +import com.iemr.flw.dto.iemr.OrsCampaignResponseDTO; import com.iemr.flw.dto.iemr.PolioCampaignDTO; import com.iemr.flw.utils.exception.IEMRException; @@ -9,7 +10,7 @@ public interface CampaignService { Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; Object savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException; - List getOrsCampaign(String token) throws IEMRException; + List getOrsCampaign(String token) throws IEMRException; List getPolioCampaign(String token) throws IEMRException; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 6baade1a4..f8a315a84 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -1,11 +1,11 @@ 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.CampaignOrs; import com.iemr.flw.domain.iemr.PulsePolioCampaign; -import com.iemr.flw.dto.iemr.OrsCampaignDTO; -import com.iemr.flw.dto.iemr.OrsCampaignListDTO; -import com.iemr.flw.dto.iemr.PolioCampaignDTO; -import com.iemr.flw.dto.iemr.PolioCampaignListDTO; +import com.iemr.flw.dto.iemr.*; import com.iemr.flw.repo.iemr.OrsCampaignRepo; import com.iemr.flw.repo.iemr.PulsePolioCampaignRepo; import com.iemr.flw.service.CampaignService; @@ -17,8 +17,11 @@ 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.util.ArrayList; +import java.util.Base64; import java.util.Collections; import java.util.List; @@ -63,7 +66,11 @@ public List saveOrsCampaign(List orsCampaignDTO, St throw new IEMRException("Invalid number format for families"); } - campaignOrsEntity.setCampaignPhotos(campaignDTO.getFields().getCampaignPhotos()); + MultipartFile[] photos = campaignDTO.getFields().getCampaignPhotos(); + if (photos != null && photos.length > 0) { + String base64Json = convertPhotosToBase64Json(photos); + campaignOrsEntity.setCampaignPhotos(base64Json); + } campaignOrsRequest.add(campaignOrsEntity); } @@ -76,21 +83,21 @@ public List saveOrsCampaign(List orsCampaignDTO, St } @Override - public List getOrsCampaign(String token) throws IEMRException { + public List getOrsCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); - List orsCampaignDTOSResponse = new ArrayList<>(); - int page=0; - int pageSize =10; + 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()){ - OrsCampaignDTO dto = convertOrsToDTO(campaignOrs); + 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()); + } while (campaignOrsPage.hasNext()); return orsCampaignDTOSResponse; } @@ -140,27 +147,29 @@ public List savePolioCampaign(List orsCamp public List getPolioCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); List polioCampaignDTOSResponse = new ArrayList<>(); - int page=0; - int pageSize =10; + 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()){ + do { + Pageable pageable = PageRequest.of(page, pageSize); + campaignPolioPage = pulsePolioCampaignRepo.findByUserId(userId, pageable); + for (PulsePolioCampaign campaignOrs : campaignPolioPage.getContent()) { PolioCampaignDTO dto = convertPolioToDTO(campaignOrs); polioCampaignDTOSResponse.add(dto); } page++; - }while (campaignPolioPage.hasNext()); + } while (campaignPolioPage.hasNext()); return polioCampaignDTOSResponse; } - private OrsCampaignDTO convertOrsToDTO(CampaignOrs campaign) { - OrsCampaignDTO dto = new OrsCampaignDTO(); - OrsCampaignListDTO orsCampaignListDTO = new OrsCampaignListDTO(); - orsCampaignListDTO.setCampaignPhotos(campaign.getCampaignPhotos()); - orsCampaignListDTO.setEndDate(campaign.getEndDate()); + private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { + OrsCampaignResponseDTO dto = new OrsCampaignResponseDTO(); + OrsCampaignListResponseDTO orsCampaignListDTO = new OrsCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + List photosList = parseBase64Json(campaign.getCampaignPhotos()); + orsCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches + } orsCampaignListDTO.setEndDate(campaign.getEndDate()); orsCampaignListDTO.setStartDate(campaign.getStartDate()); orsCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); dto.setFields(orsCampaignListDTO); @@ -177,9 +186,47 @@ private PolioCampaignDTO convertPolioToDTO(PulsePolioCampaign campaign) { dto.setFields(polioCampaignListDTO); 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 String convertPhotosToBase64Json(MultipartFile[] photos) throws IEMRException { + try { + List base64Images = new ArrayList<>(); + for (MultipartFile photo : photos) { + if (photo != null && !photo.isEmpty()) { + // Get file bytes + byte[] bytes = photo.getBytes(); + // Convert to Base64 + String base64 = Base64.getEncoder().encodeToString(bytes); + // Get content type (image/jpeg, image/png, etc.) + String contentType = photo.getContentType(); + if (contentType == null) { + contentType = "image/jpeg"; // default + } + // Create data URL format: data:image/jpeg;base64,xxxxx + String base64Image = "data:" + contentType + ";base64," + base64; + base64Images.add(base64Image); + } + } + + // Convert list to JSON array string + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.writeValueAsString(base64Images); + } catch (IOException e) { + throw new IEMRException("Error converting photos to base64: " + e.getMessage()); + } + } } + From 58b7a06c54feda72c06745e9d5db0e45167e3e5a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 09:53:43 +0530 Subject: [PATCH 061/450] fix request issue in pulse polio campaign --- .../flw/controller/CampaignController.java | 68 +++++++++++++++---- .../flw/dto/iemr/PolioCampaignListDTO.java | 3 +- .../iemr/PolioCampaignListResponseDTO.java | 25 +++++++ .../dto/iemr/PolioCampaignResponseDTO.java | 10 +++ .../com/iemr/flw/service/CampaignService.java | 9 ++- .../flw/service/impl/CampaignServiceImpl.java | 55 ++++++++++----- 6 files changed, 136 insertions(+), 34 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 16a0080d5..e11bc7445 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -4,6 +4,7 @@ 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.PulsePolioCampaign; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.service.CampaignService; import com.iemr.flw.utils.exception.IEMRException; @@ -59,9 +60,9 @@ public ResponseEntity> saveOrsDistribution( List orsCampaignDTOList = Collections.singletonList(campaignDTO); // Save to database - Object result = campaignService.saveOrsCampaign(orsCampaignDTOList, token); + List result = campaignService.saveOrsCampaign(orsCampaignDTOList, token); - if (result != null) { + if (result != null && !result.isEmpty()) { response.put("statusCode", HttpStatus.CREATED.value()); response.put("message", "Campaign saved successfully"); response.put("data", result); @@ -123,28 +124,69 @@ public ResponseEntity> getAllOrsDistribution(@RequestHeader( } - @RequestMapping(value = "polio/campaign/saveAll", method = RequestMethod.POST) - public ResponseEntity> savePolioCampaign(@RequestBody List polioCampaignDTOS, @RequestHeader(value = "jwtToken") String token) { + @PostMapping("/polio/campaign/saveAll") + public ResponseEntity> savePolioCampaign( + @RequestPart("formDataJson") String fields, + @RequestPart(value = "campaignPhotos", required = false) List campaignPhotos, + @RequestHeader("jwtToken") String token) { Map response = new LinkedHashMap<>(); try { - Object result = campaignService.savePolioCampaign(polioCampaignDTOS,token); + // 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()); + PolioCampaignListDTO polioCampaignFields = objectMapper.readValue(fields, PolioCampaignListDTO.class); - if (result != null) { - response.put("statusCode", HttpStatus.OK.value()); + // Set campaign photos if present + if (campaignPhotos != null && !campaignPhotos.isEmpty()) { + polioCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); + } + + // Create DTO + PolioCampaignDTO campaignDTO = new PolioCampaignDTO(); + campaignDTO.setFields(polioCampaignFields); + + List polioCampaignDTOList = Collections.singletonList(campaignDTO); + + // Save to database + List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.CREATED.value()); + response.put("message", "Polio campaign saved successfully"); response.put("data", result); - return ResponseEntity.ok(response); + return ResponseEntity.status(HttpStatus.CREATED).body(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); - response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + 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 save polio:", e.getMessage()); + logger.error("Error saving polio 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); } @@ -157,7 +199,7 @@ public ResponseEntity> getAllPolioCampaign(@RequestHeader(va Map response = new LinkedHashMap<>(); try { - List result = campaignService.getPolioCampaign(token); + List result = campaignService.getPolioCampaign(token); if (result != null) { diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java index 5c172ffab..649d3adf4 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; +import org.springframework.web.multipart.MultipartFile; import java.time.LocalDate; @@ -17,7 +18,7 @@ public class PolioCampaignListDTO { private String numberOfChildren; @JsonProperty("campaign_photos") - private String campaignPhotos; + private MultipartFile[] 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 000000000..603d1676e --- /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("number_of_children") + private String 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 000000000..06370ac07 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class PolioCampaignResponseDTO { + private Long id; + private String visitDate; + private PolioCampaignListResponseDTO fields; +} diff --git a/src/main/java/com/iemr/flw/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index 8c690e25c..f443c0eda 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -1,16 +1,19 @@ package com.iemr.flw.service; +import com.iemr.flw.domain.iemr.CampaignOrs; +import com.iemr.flw.domain.iemr.PulsePolioCampaign; import com.iemr.flw.dto.iemr.OrsCampaignDTO; import com.iemr.flw.dto.iemr.OrsCampaignResponseDTO; import com.iemr.flw.dto.iemr.PolioCampaignDTO; +import com.iemr.flw.dto.iemr.PolioCampaignResponseDTO; import com.iemr.flw.utils.exception.IEMRException; import java.util.List; public interface CampaignService { - Object saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; - Object savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException; + List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; + List savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException; List getOrsCampaign(String token) throws IEMRException; - List getPolioCampaign(String token) throws IEMRException; + List getPolioCampaign(String token) throws IEMRException; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index f8a315a84..e1f2c1c0c 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -104,16 +104,18 @@ public List getOrsCampaign(String token) throws IEMRExce @Override @Transactional - public List savePolioCampaign(List orsCampaignDTO, String token) throws IEMRException { - if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { - return Collections.emptyList(); // + public List savePolioCampaign(List polioCampaignDTOs, String token) + throws IEMRException { + + 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 : orsCampaignDTO) { + for (PolioCampaignDTO campaignDTO : polioCampaignDTOs) { if (campaignDTO.getFields() == null) { continue; } @@ -123,15 +125,29 @@ public List savePolioCampaign(List orsCamp 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 { - campaignPolioEntity.setNumberOfChildren( - Integer.parseInt(campaignDTO.getFields().getNumberOfChildren()) - ); + String childrenStr = campaignDTO.getFields().getNumberOfChildren(); + if (childrenStr != null && !childrenStr.trim().isEmpty()) { + campaignPolioEntity.setNumberOfChildren(Integer.parseInt(childrenStr)); + } else { + campaignPolioEntity.setNumberOfChildren(0); + } } catch (NumberFormatException e) { - throw new IEMRException("Invalid number format for families"); + throw new IEMRException("Invalid number format for children: " + e.getMessage()); + } + + // Convert photos to base64 JSON array + MultipartFile[] photos = campaignDTO.getFields().getCampaignPhotos(); + if (photos != null && photos.length > 0) { + String base64Json = convertPhotosToBase64Json(photos); + campaignPolioEntity.setCampaignPhotos(base64Json); } - campaignPolioEntity.setCampaignPhotos(campaignDTO.getFields().getCampaignPhotos()); campaignPolioRequest.add(campaignPolioEntity); } @@ -140,13 +156,14 @@ public List savePolioCampaign(List orsCamp return savedCampaigns; } - return Collections.emptyList(); + throw new IEMRException("No valid campaign data to save"); } + @Override - public List getPolioCampaign(String token) throws IEMRException { + public List getPolioCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); - List polioCampaignDTOSResponse = new ArrayList<>(); + List polioCampaignDTOSResponse = new ArrayList<>(); int page = 0; int pageSize = 10; Page campaignPolioPage; @@ -154,7 +171,7 @@ public List getPolioCampaign(String token) throws IEMRExceptio Pageable pageable = PageRequest.of(page, pageSize); campaignPolioPage = pulsePolioCampaignRepo.findByUserId(userId, pageable); for (PulsePolioCampaign campaignOrs : campaignPolioPage.getContent()) { - PolioCampaignDTO dto = convertPolioToDTO(campaignOrs); + PolioCampaignResponseDTO dto = convertPolioToDTO(campaignOrs); polioCampaignDTOSResponse.add(dto); } page++; @@ -170,16 +187,20 @@ private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { List photosList = parseBase64Json(campaign.getCampaignPhotos()); orsCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches } orsCampaignListDTO.setEndDate(campaign.getEndDate()); + orsCampaignListDTO.setStartDate(campaign.getStartDate()); orsCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); dto.setFields(orsCampaignListDTO); return dto; } - private PolioCampaignDTO convertPolioToDTO(PulsePolioCampaign campaign) { - PolioCampaignDTO dto = new PolioCampaignDTO(); - PolioCampaignListDTO polioCampaignListDTO = new PolioCampaignListDTO(); - polioCampaignListDTO.setCampaignPhotos(campaign.getCampaignPhotos()); + private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) { + PolioCampaignResponseDTO dto = new PolioCampaignResponseDTO(); + PolioCampaignListResponseDTO polioCampaignListDTO = new PolioCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + List photosList = parseBase64Json(campaign.getCampaignPhotos()); + polioCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches + } polioCampaignListDTO.setEndDate(campaign.getEndDate()); polioCampaignListDTO.setStartDate(campaign.getStartDate()); polioCampaignListDTO.setNumberOfChildren(String.valueOf(campaign.getNumberOfChildren())); From 9e0349902ef8988d60ba306ca13cae14d66d1c12 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 12:26:57 +0530 Subject: [PATCH 062/450] fix request issue in ors and pulse polio campaign --- .../flw/controller/CampaignController.java | 138 +++++++++++++++++- 1 file changed, 130 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index e11bc7445..7b9daf3e6 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -1,6 +1,7 @@ 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; @@ -30,12 +31,13 @@ public class CampaignController { @PostMapping("/ors/distribution/saveAll") public ResponseEntity> saveOrsDistribution( @RequestPart("formDataJson") String fields, - @RequestPart(value = "campaignPhotos", required = false) List campaignPhotos, @RequestHeader("jwtToken") String token) { Map response = new LinkedHashMap<>(); try { + logger.info("Received formDataJson: {}", fields.substring(0, Math.min(100, fields.length()))); // Log first 100 chars + // Validate input if (fields == null || fields.trim().isEmpty()) { response.put("statusCode", HttpStatus.BAD_REQUEST.value()); @@ -46,16 +48,27 @@ public ResponseEntity> saveOrsDistribution( // Parse JSON to DTO ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); - OrsCampaignListDTO orsCampaignFields = objectMapper.readValue(fields, OrsCampaignListDTO.class); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // Set campaign photos if present - if (campaignPhotos != null && !campaignPhotos.isEmpty()) { - orsCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); + 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() != null ? requestDTO.getFields().getCampaignPhotos().length : 0 + ); + // Create DTO OrsCampaignDTO campaignDTO = new OrsCampaignDTO(); - campaignDTO.setFields(orsCampaignFields); + campaignDTO.setFields(requestDTO.getFields()); List orsCampaignDTOList = Collections.singletonList(campaignDTO); @@ -126,6 +139,115 @@ public ResponseEntity> getAllOrsDistribution(@RequestHeader( @PostMapping("/polio/campaign/saveAll") public ResponseEntity> savePolioCampaign( + @RequestPart("formDataJson") String fields, + @RequestHeader("jwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + try { + logger.info("Received filariasis 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() != null ? requestDTO.getFields().getCampaignPhotos().length : 0 + ); + + // Create DTO + PolioCampaignDTO campaignDTO = new PolioCampaignDTO(); + campaignDTO.setFields(requestDTO.getFields()); + + List filariasisCampaignDTOList = Collections.singletonList(campaignDTO); + + // Save to database + List result = campaignService.savePolioCampaign(filariasisCampaignDTOList, token); + + if (result != null && !result.isEmpty()) { + response.put("statusCode", HttpStatus.CREATED.value()); + response.put("message", "Filariasis (MDA) campaign saved successfully"); + response.put("data", result); + return ResponseEntity.status(HttpStatus.CREATED).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 = "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.NOT_FOUND.value()); + response.put("message", "No records found"); + return ResponseEntity.status(HttpStatus.NOT_FOUND).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, @RequestPart(value = "campaignPhotos", required = false) List campaignPhotos, @RequestHeader("jwtToken") String token) { @@ -193,8 +315,8 @@ public ResponseEntity> savePolioCampaign( } - @RequestMapping(value = "polio/campaign/getAll", method = RequestMethod.POST) - public ResponseEntity> getAllPolioCampaign(@RequestHeader(value = "jwtToken") String token) { + @RequestMapping(value = "filariasis/campaign/getAll", method = RequestMethod.POST) + public ResponseEntity> getAllFilariasisCampaign(@RequestHeader(value = "jwtToken") String token) { Map response = new LinkedHashMap<>(); From 46eb10cb6fd9ba2c7c0845ca3478ee95341934dd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 12:34:35 +0530 Subject: [PATCH 063/450] make changes in tb api --- .../com/iemr/flw/controller/TBController.java | 15 ++- .../com/iemr/flw/domain/iemr/TBScreening.java | 113 ++++++++++++++--- .../com/iemr/flw/dto/iemr/TBScreeningDTO.java | 120 +++--------------- 3 files changed, 120 insertions(+), 128 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index 6beb9008e..39f119e23 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -42,9 +42,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 +66,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 +91,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(); } @@ -124,4 +124,5 @@ public String saveAllSuspectedByUserId(@RequestBody TBSuspectedRequestDTO reques } return response.toString(); } + } 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 9bf7ea8de..3b6af4faf 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java @@ -4,9 +4,10 @@ import jakarta.persistence.*; import java.sql.Timestamp; +import java.time.LocalDateTime; @Entity -@Table(name = "tb_screening", schema = "db_iemr") +@Table(name = "screening_tb", schema = "db_iemr") @Data public class TBScreening { @@ -23,27 +24,105 @@ public class TBScreening { @Column(name = "visit_date") private Timestamp visitDate; - @Column(name = "cough_check") - private Boolean coughMoreThan2Weeks; + @Column(name = "visit_code", nullable = false) + private Long visitCode; - @Column(name = "blood_check") - private Boolean bloodInSputum; + // Visit Information + @Column(name = "visit_label", length = 100, nullable = false) + private String visitLabel; - @Column(name = "fever_check") - private Boolean feverMoreThan2Weeks; + @Column(name = "type_of_tb_case", length = 50, nullable = false) + private String typeOfTBCase; - @Column(name = "weight_check") - private Boolean lossOfWeight; + @Column(name = "reason_for_suspicion", length = 500) + private String reasonForSuspicion; - @Column(name = "sweats_check") - private Boolean nightSweats; + // Symptoms + @Column(name = "has_symptoms", nullable = false) + private Boolean hasSymptoms = false; - @Column(name = "history_check") - private Boolean historyOfTb; + // Sputum Test + @Column(name = "is_sputum_collected") + private Boolean isSputumCollected; - @Column(name = "drugs_check") - private Boolean takingAntiTBDrugs; + @Column(name = "sputum_submitted_at", length = 200) + private String sputumSubmittedAt; - @Column(name = "family_check") - private Boolean familySufferingFromTB; + @Column(name = "nikshay_id", length = 50) + private String nikshayId; + + @Column(name = "sputum_test_result", length = 50) + private String sputumTestResult; + + // 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 = "is_confirmed", nullable = false) + private Boolean isConfirmed = false; + + @Column(name = "referred") + private Boolean referred; + + @Column(name = "follow_ups", columnDefinition = "TEXT") + private String followUps; + + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapId; + + @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; + + @Column(name = "deleted") + private Boolean deleted = false; + + @Column(name = "processed", length = 4) + private String processed = "N"; + + @PrePersist + protected void onCreate() { + this.createdDate = LocalDateTime.now(); + this.updatedDate = LocalDateTime.now(); + if (this.hasSymptoms == null) { + this.hasSymptoms = false; + } + if (this.isConfirmed == null) { + this.isConfirmed = false; + } + + if (this.deleted == null) { + this.deleted = false; + } + if (this.processed == null) { + this.processed = "N"; + } + } + + @PreUpdate + protected void onUpdate() { + this.updatedDate = LocalDateTime.now(); + } } 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 270526bdc..9b30b5ba9 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -12,108 +12,20 @@ public class TBScreeningDTO { private Long benId; private Timestamp visitDate; - - private Boolean coughMoreThan2Weeks; - - private Boolean bloodInSputum; - - private Boolean feverMoreThan2Weeks; - - private Boolean lossOfWeight; - - private Boolean nightSweats; - - private Boolean historyOfTb; - - private Boolean takingAntiTBDrugs; - - 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 String visitLabel; + private String typeOfTBCase; + private String reasonForSuspicion; + private Boolean hasSymptoms; + 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 isDRTBConfirmed; + private Boolean isConfirmed = false; + private Boolean referred; + private String followUps; } From e96c8a8e8ad1f198d28858d62644ec3f3a660d0e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 12:50:31 +0530 Subject: [PATCH 064/450] make tb api changes --- .../com/iemr/flw/controller/TBController.java | 4 +- .../com/iemr/flw/domain/iemr/TBScreening.java | 113 +++-------------- .../com/iemr/flw/domain/iemr/TBSuspected.java | 43 +++++++ .../com/iemr/flw/dto/iemr/TBScreeningDTO.java | 120 +++++++++++++++--- .../com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 19 +-- 5 files changed, 177 insertions(+), 122 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index 39f119e23..56afcb987 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -115,9 +115,9 @@ 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); 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 3b6af4faf..9bf7ea8de 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java @@ -4,10 +4,9 @@ import jakarta.persistence.*; import java.sql.Timestamp; -import java.time.LocalDateTime; @Entity -@Table(name = "screening_tb", schema = "db_iemr") +@Table(name = "tb_screening", schema = "db_iemr") @Data public class TBScreening { @@ -24,105 +23,27 @@ public class TBScreening { @Column(name = "visit_date") private Timestamp visitDate; - @Column(name = "visit_code", nullable = false) - private Long visitCode; + @Column(name = "cough_check") + private Boolean coughMoreThan2Weeks; - // Visit Information - @Column(name = "visit_label", length = 100, nullable = false) - private String visitLabel; + @Column(name = "blood_check") + private Boolean bloodInSputum; - @Column(name = "type_of_tb_case", length = 50, nullable = false) - private String typeOfTBCase; + @Column(name = "fever_check") + private Boolean feverMoreThan2Weeks; - @Column(name = "reason_for_suspicion", length = 500) - private String reasonForSuspicion; + @Column(name = "weight_check") + private Boolean lossOfWeight; - // Symptoms - @Column(name = "has_symptoms", nullable = false) - private Boolean hasSymptoms = false; + @Column(name = "sweats_check") + private Boolean nightSweats; - // Sputum Test - @Column(name = "is_sputum_collected") - private Boolean isSputumCollected; + @Column(name = "history_check") + private Boolean historyOfTb; - @Column(name = "sputum_submitted_at", length = 200) - private String sputumSubmittedAt; + @Column(name = "drugs_check") + private Boolean takingAntiTBDrugs; - @Column(name = "nikshay_id", length = 50) - private String nikshayId; - - @Column(name = "sputum_test_result", length = 50) - private String sputumTestResult; - - // 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 = "is_confirmed", nullable = false) - private Boolean isConfirmed = false; - - @Column(name = "referred") - private Boolean referred; - - @Column(name = "follow_ups", columnDefinition = "TEXT") - private String followUps; - - - @Column(name = "provider_service_map_id") - private Integer providerServiceMapId; - - @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; - - @Column(name = "deleted") - private Boolean deleted = false; - - @Column(name = "processed", length = 4) - private String processed = "N"; - - @PrePersist - protected void onCreate() { - this.createdDate = LocalDateTime.now(); - this.updatedDate = LocalDateTime.now(); - if (this.hasSymptoms == null) { - this.hasSymptoms = false; - } - if (this.isConfirmed == null) { - this.isConfirmed = false; - } - - if (this.deleted == null) { - this.deleted = false; - } - if (this.processed == null) { - this.processed = "N"; - } - } - - @PreUpdate - protected void onUpdate() { - this.updatedDate = LocalDateTime.now(); - } + @Column(name = "family_check") + private Boolean familySufferingFromTB; } 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 7cb945a89..481e613d7 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,47 @@ public class TBSuspected { @Column(name = "followups") private String followUps; + + @Column(name = "visit_code", nullable = false) + private Long visitCode; + + // Visit Information + @Column(name = "visit_label", length = 100, nullable = false) + private String visitLabel; + + @Column(name = "type_of_tb_case", length = 50, nullable = false) + private String typeOfTBCase; + + @Column(name = "reason_for_suspicion", length = 500) + private String reasonForSuspicion; + + // Symptoms + @Column(name = "has_symptoms", nullable = false) + private Boolean hasSymptoms = false; + + // 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 = "is_confirmed", nullable = false) + private Boolean isConfirmed = false; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapId; + + + } 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 9b30b5ba9..270526bdc 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -12,20 +12,108 @@ public class TBScreeningDTO { private Long benId; private Timestamp visitDate; - private String visitLabel; - private String typeOfTBCase; - private String reasonForSuspicion; - private Boolean hasSymptoms; - 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 isDRTBConfirmed; - private Boolean isConfirmed = false; - private Boolean referred; - private String followUps; + + private Boolean coughMoreThan2Weeks; + + private Boolean bloodInSputum; + + private Boolean feverMoreThan2Weeks; + + private Boolean lossOfWeight; + + private Boolean nightSweats; + + private Boolean historyOfTb; + + private Boolean takingAntiTBDrugs; + + 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; + } } 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 8d224a9ce..b44e0ed44 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,21 @@ public class TBSuspectedDTO { private Long id; private Long benId; - - private Timestamp visitDate; - + private Long visitCode; + private String visitLabel; + private String typeOfTBCase; + private String reasonForSuspicion; + private Boolean hasSymptoms; 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 isDRTBConfirmed; + private Boolean isConfirmed; private Boolean referred; - private String followUps; } From 27f033a02629fdb0821811c58a5309743d8a04d0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 12:57:23 +0530 Subject: [PATCH 065/450] fix date issue in request --- src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java | 3 +++ src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java | 3 +++ 2 files changed, 6 insertions(+) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 7f8b67570..5c92c3ac2 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -1,5 +1,6 @@ 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; @@ -10,9 +11,11 @@ @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; diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java index 649d3adf4..86a2c6d6e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -1,5 +1,6 @@ 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; @@ -8,9 +9,11 @@ @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; From 9964f790176ceeb7b2ab530a7fa0b24009c4747e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 13:14:05 +0530 Subject: [PATCH 066/450] fix image issue --- .../flw/controller/CampaignController.java | 7 ++- .../iemr/flw/dto/iemr/OrsCampaignListDTO.java | 3 +- .../flw/dto/iemr/PolioCampaignListDTO.java | 3 +- .../flw/service/impl/CampaignServiceImpl.java | 58 ++++++++++--------- 4 files changed, 39 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 7b9daf3e6..5304784a1 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -63,7 +63,7 @@ public ResponseEntity> saveOrsDistribution( requestDTO.getFields().getStartDate(), requestDTO.getFields().getEndDate(), requestDTO.getFields().getNumberOfFamilies(), - requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().length : 0 + requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().size() : 0 ); // Create DTO @@ -172,7 +172,8 @@ public ResponseEntity> savePolioCampaign( requestDTO.getFields().getStartDate(), requestDTO.getFields().getEndDate(), requestDTO.getFields().getNumberOfChildren(), - requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().length : 0 + + requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().size() : 0 ); // Create DTO @@ -269,7 +270,7 @@ public ResponseEntity> saveFilariasisCampaign( // Set campaign photos if present if (campaignPhotos != null && !campaignPhotos.isEmpty()) { - polioCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); + // polioCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); } // Create DTO diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 5c92c3ac2..552c4fc8a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -8,6 +8,7 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.util.List; @Data public class OrsCampaignListDTO { @@ -23,7 +24,7 @@ public class OrsCampaignListDTO { private String NumberOfFamilies; @JsonProperty("campaign_photos") - private MultipartFile[] CampaignPhotos; + private List campaignPhotos; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java index 86a2c6d6e..670e790b6 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -6,6 +6,7 @@ import org.springframework.web.multipart.MultipartFile; import java.time.LocalDate; +import java.util.List; @Data public class PolioCampaignListDTO { @@ -21,7 +22,7 @@ public class PolioCampaignListDTO { private String numberOfChildren; @JsonProperty("campaign_photos") - private MultipartFile[] campaignPhotos; + private List campaignPhotos; // base64 strings } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index e1f2c1c0c..45992c988 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -66,11 +66,21 @@ public List saveOrsCampaign(List orsCampaignDTO, St throw new IEMRException("Invalid number format for families"); } - MultipartFile[] photos = campaignDTO.getFields().getCampaignPhotos(); - if (photos != null && photos.length > 0) { - String base64Json = convertPhotosToBase64Json(photos); - campaignOrsEntity.setCampaignPhotos(base64Json); + List photos = campaignDTO.getFields().getCampaignPhotos(); + + if (photos != null && !photos.isEmpty()) { + + // remove null / empty / invalid entries + List validPhotos = photos.stream() + .filter(p -> p != null && !p.trim().isEmpty()) + .toList(); + + if (!validPhotos.isEmpty()) { + String base64Json = convertPhotosToBase64Json(validPhotos); + campaignOrsEntity.setCampaignPhotos(base64Json); + } } + campaignOrsRequest.add(campaignOrsEntity); } @@ -142,12 +152,14 @@ public List savePolioCampaign(List polioCa } // Convert photos to base64 JSON array - MultipartFile[] photos = campaignDTO.getFields().getCampaignPhotos(); - if (photos != null && photos.length > 0) { + List photos = campaignDTO.getFields().getCampaignPhotos(); + + if (photos != null && !photos.isEmpty()) { String base64Json = convertPhotosToBase64Json(photos); campaignPolioEntity.setCampaignPhotos(base64Json); } + campaignPolioRequest.add(campaignPolioEntity); } @@ -217,37 +229,29 @@ private List parseBase64Json(String jsonString) { } - private String convertPhotosToBase64Json(MultipartFile[] photos) throws IEMRException { + private String convertPhotosToBase64Json(List photos) throws IEMRException { try { - List base64Images = new ArrayList<>(); + List cleanedBase64Images = new ArrayList<>(); - for (MultipartFile photo : photos) { - if (photo != null && !photo.isEmpty()) { - // Get file bytes - byte[] bytes = photo.getBytes(); + for (String photo : photos) { + if (photo != null && !photo.trim().isEmpty()) { - // Convert to Base64 - String base64 = Base64.getEncoder().encodeToString(bytes); + // remove data:image/...;base64, if present + String cleanBase64 = photo.contains(",") + ? photo.substring(photo.indexOf(",") + 1) + : photo; - // Get content type (image/jpeg, image/png, etc.) - String contentType = photo.getContentType(); - if (contentType == null) { - contentType = "image/jpeg"; // default - } - - // Create data URL format: data:image/jpeg;base64,xxxxx - String base64Image = "data:" + contentType + ";base64," + base64; - base64Images.add(base64Image); + cleanedBase64Images.add(cleanBase64); } } - // Convert list to JSON array string ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.writeValueAsString(base64Images); + return objectMapper.writeValueAsString(cleanedBase64Images); - } catch (IOException e) { - throw new IEMRException("Error converting photos to base64: " + e.getMessage()); + } catch (Exception e) { + throw new IEMRException("Error processing base64 photos: " + e.getMessage()); } } + } From 7266b1c985ec899ce4175ff2b45afd98e7829cbb Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 14:30:00 +0530 Subject: [PATCH 067/450] fix base64 image issue --- .../com/iemr/flw/service/CampaignService.java | 5 ++-- .../flw/service/impl/CampaignServiceImpl.java | 28 ++++++------------- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index f443c0eda..1f2cf0926 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -1,5 +1,6 @@ package com.iemr.flw.service; +import com.fasterxml.jackson.core.JsonProcessingException; import com.iemr.flw.domain.iemr.CampaignOrs; import com.iemr.flw.domain.iemr.PulsePolioCampaign; import com.iemr.flw.dto.iemr.OrsCampaignDTO; @@ -11,8 +12,8 @@ import java.util.List; public interface CampaignService { - List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException; - List savePolioCampaign(List polioCampaignDTOS, String token) throws IEMRException; + 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; diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 45992c988..63e642120 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -39,7 +39,7 @@ public class CampaignServiceImpl implements CampaignService { @Override @Transactional - public List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException { + public List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException, JsonProcessingException { if (orsCampaignDTO == null || orsCampaignDTO.isEmpty()) { return Collections.emptyList(); // } @@ -66,20 +66,9 @@ public List saveOrsCampaign(List orsCampaignDTO, St throw new IEMRException("Invalid number format for families"); } - List photos = campaignDTO.getFields().getCampaignPhotos(); - - if (photos != null && !photos.isEmpty()) { - - // remove null / empty / invalid entries - List validPhotos = photos.stream() - .filter(p -> p != null && !p.trim().isEmpty()) - .toList(); - - if (!validPhotos.isEmpty()) { - String base64Json = convertPhotosToBase64Json(validPhotos); - campaignOrsEntity.setCampaignPhotos(base64Json); - } - } + ObjectMapper mapper = new ObjectMapper(); + String jsonPhotos = mapper.writeValueAsString(campaignDTO.getFields().getCampaignPhotos()); + campaignOrsEntity.setCampaignPhotos(jsonPhotos); campaignOrsRequest.add(campaignOrsEntity); } @@ -115,7 +104,7 @@ public List getOrsCampaign(String token) throws IEMRExce @Override @Transactional public List savePolioCampaign(List polioCampaignDTOs, String token) - throws IEMRException { + throws IEMRException, JsonProcessingException { if (polioCampaignDTOs == null || polioCampaignDTOs.isEmpty()) { throw new IEMRException("Campaign data is required"); @@ -154,10 +143,9 @@ public List savePolioCampaign(List polioCa // Convert photos to base64 JSON array List photos = campaignDTO.getFields().getCampaignPhotos(); - if (photos != null && !photos.isEmpty()) { - String base64Json = convertPhotosToBase64Json(photos); - campaignPolioEntity.setCampaignPhotos(base64Json); - } + ObjectMapper mapper = new ObjectMapper(); + String jsonPhotos = mapper.writeValueAsString(campaignDTO.getFields().getCampaignPhotos()); + campaignPolioEntity.setCampaignPhotos(jsonPhotos); campaignPolioRequest.add(campaignPolioEntity); From d24f9cda47a4a081fc40cf424e57d01bf6831fd8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 14:48:19 +0530 Subject: [PATCH 068/450] fix base64 image issue --- .../flw/controller/CampaignController.java | 14 +++++++------- .../iemr/flw/dto/iemr/OrsCampaignListDTO.java | 2 +- .../flw/dto/iemr/PolioCampaignListDTO.java | 2 +- .../flw/service/impl/CampaignServiceImpl.java | 19 ++++++++++++++++--- 4 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 5304784a1..070a3ea80 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -63,7 +63,7 @@ public ResponseEntity> saveOrsDistribution( requestDTO.getFields().getStartDate(), requestDTO.getFields().getEndDate(), requestDTO.getFields().getNumberOfFamilies(), - requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().size() : 0 + requestDTO.getFields().getCampaignPhotos() ); // Create DTO @@ -145,7 +145,7 @@ public ResponseEntity> savePolioCampaign( Map response = new LinkedHashMap<>(); try { - logger.info("Received filariasis campaign data"); + logger.info("Received polio campaign data"); // Validate input if (fields == null || fields.trim().isEmpty()) { @@ -173,26 +173,26 @@ public ResponseEntity> savePolioCampaign( requestDTO.getFields().getEndDate(), requestDTO.getFields().getNumberOfChildren(), - requestDTO.getFields().getCampaignPhotos() != null ? requestDTO.getFields().getCampaignPhotos().size() : 0 + requestDTO.getFields().getCampaignPhotos() ); // Create DTO PolioCampaignDTO campaignDTO = new PolioCampaignDTO(); campaignDTO.setFields(requestDTO.getFields()); - List filariasisCampaignDTOList = Collections.singletonList(campaignDTO); + List polioCampaignDTOList = Collections.singletonList(campaignDTO); // Save to database - List result = campaignService.savePolioCampaign(filariasisCampaignDTOList, token); + List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); if (result != null && !result.isEmpty()) { response.put("statusCode", HttpStatus.CREATED.value()); - response.put("message", "Filariasis (MDA) campaign saved successfully"); + response.put("message", "polio campaign saved successfully"); response.put("data", result); return ResponseEntity.status(HttpStatus.CREATED).body(response); } else { response.put("statusCode", HttpStatus.BAD_REQUEST.value()); - response.put("message", "Failed to save filariasis campaign"); + response.put("message", "Failed to save Polio campaign"); return ResponseEntity.badRequest().body(response); } diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 552c4fc8a..71f54a5f0 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -24,7 +24,7 @@ public class OrsCampaignListDTO { private String NumberOfFamilies; @JsonProperty("campaign_photos") - private List campaignPhotos; + private String campaignPhotos; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java index 670e790b6..ef6b22689 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -22,7 +22,7 @@ public class PolioCampaignListDTO { private String numberOfChildren; @JsonProperty("campaign_photos") - private List campaignPhotos; // base64 strings + private String campaignPhotos; // base64 strings } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 63e642120..cda1479c2 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -67,7 +67,14 @@ public List saveOrsCampaign(List orsCampaignDTO, St } ObjectMapper mapper = new ObjectMapper(); - String jsonPhotos = mapper.writeValueAsString(campaignDTO.getFields().getCampaignPhotos()); + String photosStr = campaignDTO.getFields().getCampaignPhotos(); + + List photosList = Collections.emptyList(); + if (photosStr != null && !photosStr.isEmpty()) { + photosList = mapper.readValue(photosStr, new TypeReference>() {}); + } + + String jsonPhotos = mapper.writeValueAsString(photosList); campaignOrsEntity.setCampaignPhotos(jsonPhotos); campaignOrsRequest.add(campaignOrsEntity); @@ -141,10 +148,16 @@ public List savePolioCampaign(List polioCa } // Convert photos to base64 JSON array - List photos = campaignDTO.getFields().getCampaignPhotos(); ObjectMapper mapper = new ObjectMapper(); - String jsonPhotos = mapper.writeValueAsString(campaignDTO.getFields().getCampaignPhotos()); + String photosStr = campaignDTO.getFields().getCampaignPhotos(); + + List photosList = Collections.emptyList(); + if (photosStr != null && !photosStr.isEmpty()) { + photosList = mapper.readValue(photosStr, new TypeReference>() {}); + } + + String jsonPhotos = mapper.writeValueAsString(photosList); campaignPolioEntity.setCampaignPhotos(jsonPhotos); From e35b9d0636e11e625c9bddb6808bfc44a317b11f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:05:54 +0530 Subject: [PATCH 069/450] fix base64 image issue --- src/main/java/com/iemr/flw/controller/CampaignController.java | 1 - src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 070a3ea80..bf7db3061 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -36,7 +36,6 @@ public ResponseEntity> saveOrsDistribution( Map response = new LinkedHashMap<>(); try { - logger.info("Received formDataJson: {}", fields.substring(0, Math.min(100, fields.length()))); // Log first 100 chars // Validate input if (fields == null || fields.trim().isEmpty()) { diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index cda1479c2..b66f430b0 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -77,6 +77,7 @@ public List saveOrsCampaign(List orsCampaignDTO, St String jsonPhotos = mapper.writeValueAsString(photosList); campaignOrsEntity.setCampaignPhotos(jsonPhotos); + campaignOrsRequest.add(campaignOrsEntity); } From 7522177ec713ac2143b3de68eabdd68a1a018bf6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:08:56 +0530 Subject: [PATCH 070/450] change status code --- .../com/iemr/flw/controller/CampaignController.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index bf7db3061..c35ef03cf 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -75,10 +75,10 @@ public ResponseEntity> saveOrsDistribution( List result = campaignService.saveOrsCampaign(orsCampaignDTOList, token); if (result != null && !result.isEmpty()) { - response.put("statusCode", HttpStatus.CREATED.value()); + response.put("statusCode", HttpStatus.OK.value()); response.put("message", "Campaign saved successfully"); response.put("data", result); - return ResponseEntity.status(HttpStatus.CREATED).body(response); + return ResponseEntity.status(HttpStatus.OK).body(response); } else { response.put("statusCode", HttpStatus.BAD_REQUEST.value()); response.put("message", "Failed to save campaign"); @@ -185,10 +185,10 @@ public ResponseEntity> savePolioCampaign( List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); if (result != null && !result.isEmpty()) { - response.put("statusCode", HttpStatus.CREATED.value()); + response.put("statusCode", HttpStatus.OK.value()); response.put("message", "polio campaign saved successfully"); response.put("data", result); - return ResponseEntity.status(HttpStatus.CREATED).body(response); + return ResponseEntity.status(HttpStatus.OK).body(response); } else { response.put("statusCode", HttpStatus.BAD_REQUEST.value()); response.put("message", "Failed to save Polio campaign"); @@ -282,10 +282,10 @@ public ResponseEntity> saveFilariasisCampaign( List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); if (result != null && !result.isEmpty()) { - response.put("statusCode", HttpStatus.CREATED.value()); + response.put("statusCode", HttpStatus.OK.value()); response.put("message", "Polio campaign saved successfully"); response.put("data", result); - return ResponseEntity.status(HttpStatus.CREATED).body(response); + return ResponseEntity.status(HttpStatus.OK).body(response); } else { response.put("statusCode", HttpStatus.BAD_REQUEST.value()); response.put("message", "Failed to save polio campaign"); From 68d09dd04a409412963bae4993d375974cd1436a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:14:08 +0530 Subject: [PATCH 071/450] change status code --- .../flw/controller/ChildCareController.java | 4 ++-- .../flw/service/impl/CampaignServiceImpl.java | 21 ++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index d5e4335f8..e29193c12 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -40,7 +40,7 @@ public class ChildCareController { @Operation(summary = "save HBYC details") @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) public String saveHbycRecords(@RequestBody List hbycDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "JwtToken") String token) { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // Pretty print @@ -52,7 +52,7 @@ public String saveHbycRecords(@RequestBody List hbycDTOs, logger.info("Saving All HBYC Details"); if (hbycDTOs != null) { - String s = childCareService.registerHBYC(hbycDTOs); + String s = childCareService.registerHBYC(hbycDTOs,token); if (s != null) response.setResponse(s); else diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index b66f430b0..107eb67a2 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -59,13 +59,18 @@ public List saveOrsCampaign(List orsCampaignDTO, St campaignOrsEntity.setUpdatedBy(userName); try { - campaignOrsEntity.setNumberOfFamilies( - Integer.parseInt(campaignDTO.getFields().getNumberOfFamilies()) - ); + 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"); + throw new IEMRException("Invalid number format for families: " + campaignDTO.getFields().getNumberOfFamilies()); } + ObjectMapper mapper = new ObjectMapper(); String photosStr = campaignDTO.getFields().getCampaignPhotos(); @@ -140,7 +145,13 @@ public List savePolioCampaign(List polioCa try { String childrenStr = campaignDTO.getFields().getNumberOfChildren(); if (childrenStr != null && !childrenStr.trim().isEmpty()) { - campaignPolioEntity.setNumberOfChildren(Integer.parseInt(childrenStr)); + 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); } From 7aac355fe554df488dc641db19af8202feed1544 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Fri, 16 Jan 2026 15:20:14 +0530 Subject: [PATCH 072/450] Update ChildCareController.java --- src/main/java/com/iemr/flw/controller/ChildCareController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index e29193c12..e1e2c91fe 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -52,7 +52,7 @@ public String saveHbycRecords(@RequestBody List hbycDTOs, logger.info("Saving All HBYC Details"); if (hbycDTOs != null) { - String s = childCareService.registerHBYC(hbycDTOs,token); + String s = childCareService.registerHBYC(hbycDTOs); if (s != null) response.setResponse(s); else From b57ab885530884faa18209bbeadb553f627e9e8b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:32:57 +0530 Subject: [PATCH 073/450] fix issue image --- .../flw/service/impl/CampaignServiceImpl.java | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 107eb67a2..6a806bcee 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -71,16 +71,11 @@ public List saveOrsCampaign(List orsCampaignDTO, St } - ObjectMapper mapper = new ObjectMapper(); - String photosStr = campaignDTO.getFields().getCampaignPhotos(); - - List photosList = Collections.emptyList(); - if (photosStr != null && !photosStr.isEmpty()) { - photosList = mapper.readValue(photosStr, new TypeReference>() {}); - } - - String jsonPhotos = mapper.writeValueAsString(photosList); - campaignOrsEntity.setCampaignPhotos(jsonPhotos); + List photos = campaignDTO.getFields().getCampaignPhotos(); + String photosStr = (photos != null && !photos.isEmpty()) + ? String.join(",", photos) + : null; + campaignOrsEntity.setCampaignPhotos(photosStr); campaignOrsRequest.add(campaignOrsEntity); @@ -161,16 +156,12 @@ public List savePolioCampaign(List polioCa // Convert photos to base64 JSON array - ObjectMapper mapper = new ObjectMapper(); - String photosStr = campaignDTO.getFields().getCampaignPhotos(); - - List photosList = Collections.emptyList(); - if (photosStr != null && !photosStr.isEmpty()) { - photosList = mapper.readValue(photosStr, new TypeReference>() {}); - } + List photosList = campaignDTO.getFields().getCampaignPhotos(); + String photosStr = (photosList != null && !photosList.isEmpty()) + ? String.join(",", photosList) + : null; - String jsonPhotos = mapper.writeValueAsString(photosList); - campaignPolioEntity.setCampaignPhotos(jsonPhotos); + campaignPolioEntity.setCampaignPhotos(photosStr); campaignPolioRequest.add(campaignPolioEntity); From 9d4eb33b1cf4fc4cfe4234d96f8ae4ec205b85f8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:37:31 +0530 Subject: [PATCH 074/450] fix issue image --- src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java | 2 +- src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java index 71f54a5f0..552c4fc8a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListDTO.java @@ -24,7 +24,7 @@ public class OrsCampaignListDTO { private String NumberOfFamilies; @JsonProperty("campaign_photos") - private String campaignPhotos; + private List campaignPhotos; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java index ef6b22689..a42ef3c63 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListDTO.java @@ -18,11 +18,11 @@ public class PolioCampaignListDTO { @JsonProperty("end_date") private LocalDate endDate; - @JsonProperty("number_of_children") + @JsonProperty("children_vaccinated") private String numberOfChildren; @JsonProperty("campaign_photos") - private String campaignPhotos; // base64 strings + private List campaignPhotos; } From 3c19e25141a3c3159499ca0570785d161feb635d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 15:50:31 +0530 Subject: [PATCH 075/450] fix date issue --- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 6a806bcee..a2b098966 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -57,6 +57,8 @@ public List saveOrsCampaign(List orsCampaignDTO, St campaignOrsEntity.setUserId(userId); campaignOrsEntity.setCreatedBy(userName); campaignOrsEntity.setUpdatedBy(userName); + campaignOrsEntity.setStartDate(campaignDTO.getFields().getStartDate()); + campaignOrsEntity.setStartDate(campaignDTO.getFields().getEndDate()); try { String familiesStr = campaignDTO.getFields().getNumberOfFamilies(); From b296e9b2c1a0fc59993606e8223ed2ecba1246fa Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 16:42:09 +0530 Subject: [PATCH 076/450] Filariasis Campaign --- .../flw/controller/CampaignController.java | 42 +++++-- .../flw/domain/iemr/FilariasisCampaign.java | 66 ++++++++++ .../flw/dto/iemr/FilariasisCampaignDTO.java | 10 ++ .../dto/iemr/FilariasisCampaignListDTO.java | 30 +++++ .../FilariasisCampaignListResponseDTO.java | 30 +++++ .../flw/dto/iemr/FilariasisResponseDTO.java | 10 ++ .../flw/repo/iemr/FilariasisCampaignRepo.java | 13 ++ .../com/iemr/flw/service/CampaignService.java | 12 +- .../flw/service/impl/CampaignServiceImpl.java | 118 ++++++++++++++++++ 9 files changed, 314 insertions(+), 17 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FilariasisResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/FilariasisCampaignRepo.java diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index c35ef03cf..93a19afdb 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -5,6 +5,7 @@ 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; @@ -249,12 +250,13 @@ public ResponseEntity> getAllPolioCampaign(@RequestHeader(va @PostMapping("/filariasis/campaign/saveAll") public ResponseEntity> saveFilariasisCampaign( @RequestPart("formDataJson") String fields, - @RequestPart(value = "campaignPhotos", required = false) List campaignPhotos, @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()); @@ -265,30 +267,44 @@ public ResponseEntity> saveFilariasisCampaign( // Parse JSON to DTO ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); - PolioCampaignListDTO polioCampaignFields = objectMapper.readValue(fields, PolioCampaignListDTO.class); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // Set campaign photos if present - if (campaignPhotos != null && !campaignPhotos.isEmpty()) { - // polioCampaignFields.setCampaignPhotos(campaignPhotos.toArray(new MultipartFile[0])); + 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 - PolioCampaignDTO campaignDTO = new PolioCampaignDTO(); - campaignDTO.setFields(polioCampaignFields); + FilariasisCampaignDTO campaignDTO = new FilariasisCampaignDTO(); + campaignDTO.setFields(requestDTO.getFields()); + + List filariasisCampaignDTOS = Collections.singletonList(campaignDTO); - List polioCampaignDTOList = Collections.singletonList(campaignDTO); // Save to database - List result = campaignService.savePolioCampaign(polioCampaignDTOList, token); + List result = campaignService.saveFilariasisCampaign(filariasisCampaignDTOS, token); if (result != null && !result.isEmpty()) { response.put("statusCode", HttpStatus.OK.value()); - response.put("message", "Polio campaign saved successfully"); + 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 polio campaign"); + response.put("message", "Failed to save filariasis campaign"); return ResponseEntity.badRequest().body(response); } @@ -306,7 +322,7 @@ public ResponseEntity> saveFilariasisCampaign( return ResponseEntity.badRequest().body(response); } catch (Exception e) { - logger.error("Error saving polio campaign: {}", e.getMessage(), 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()); @@ -321,7 +337,7 @@ public ResponseEntity> getAllFilariasisCampaign(@RequestHead Map response = new LinkedHashMap<>(); try { - List result = campaignService.getPolioCampaign(token); + List result = campaignService.getAllFilariasisCampaign(token); if (result != null) { 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 000000000..b9f98ee8e --- /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 = "no_of_families", nullable = false) + private Integer numberOfFamilies = 0; + + @Column(name = "no_of_individuals", nullable = false) + private Integer numberOfIndividuals = 0; + + /** + * Store JSON array like ["img1.jpg","img2.jpg"] + * MySQL JSON column + */ + @Column(name = "mda_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/dto/iemr/FilariasisCampaignDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignDTO.java new file mode 100644 index 000000000..2e53ee290 --- /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 000000000..81438df93 --- /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 000000000..644448a77 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.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 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 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/FilariasisResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisResponseDTO.java new file mode 100644 index 000000000..7b6dc5aa9 --- /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/repo/iemr/FilariasisCampaignRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FilariasisCampaignRepo.java new file mode 100644 index 000000000..1fe0d3e2e --- /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/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index 1f2cf0926..d1ac02017 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -2,19 +2,23 @@ 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.OrsCampaignDTO; -import com.iemr.flw.dto.iemr.OrsCampaignResponseDTO; -import com.iemr.flw.dto.iemr.PolioCampaignDTO; -import com.iemr.flw.dto.iemr.PolioCampaignResponseDTO; +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; + + List getAllFilariasisCampaign(String token) throws IEMRException; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index a2b098966..32596222a 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -4,8 +4,10 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; 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.repo.iemr.FilariasisCampaignRepo; import com.iemr.flw.repo.iemr.OrsCampaignRepo; import com.iemr.flw.repo.iemr.PulsePolioCampaignRepo; import com.iemr.flw.service.CampaignService; @@ -34,6 +36,9 @@ public class CampaignServiceImpl implements CampaignService { @Autowired private PulsePolioCampaignRepo pulsePolioCampaignRepo; + @Autowired + private FilariasisCampaignRepo filariasisCampaignRepo; + @Autowired private JwtUtil jwtUtil; @@ -178,6 +183,85 @@ public List savePolioCampaign(List polioCa } + @Override + @Transactional + public List saveFilariasisCampaign(List filariasisCampaignDTOS, String token) throws IEMRException { + + 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.getFields().getNumberOfFamilies(); + String numberOfIndividuals = campaignDTO.getFields().getNumberOfIndividuals(); + 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.setNumberOfFamilies((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 + + List photosList = campaignDTO.getFields().getMdaPhotos(); + String photosStr = (photosList != null && !photosList.isEmpty()) + ? String.join(",", photosList) + : null; + + filariasisCampaign.setCampaignPhotos(photosStr); + + + campaignPolioRequest.add(filariasisCampaign); + } + + if (!campaignPolioRequest.isEmpty()) { + List savedCampaigns = filariasisCampaignRepo.saveAll(campaignPolioRequest); + return savedCampaigns; + } + + throw new IEMRException("No valid campaign data to save"); + } + + @Override public List getPolioCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); @@ -197,6 +281,25 @@ public List getPolioCampaign(String token) throws IEMR 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(); @@ -225,6 +328,21 @@ private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) dto.setFields(polioCampaignListDTO); return dto; } + + private FilariasisResponseDTO convertFilariasisDTO(FilariasisCampaign campaign) { + FilariasisResponseDTO dto = new FilariasisResponseDTO(); + FilariasisCampaignListResponseDTO filariasisCampaignListDTO = new FilariasisCampaignListResponseDTO(); + if (campaign.getCampaignPhotos() != null) { + List photosList = parseBase64Json(campaign.getCampaignPhotos()); + filariasisCampaignListDTO.setMdaPhotos(photosList); // ✅ Now List matches + } + filariasisCampaignListDTO.setEndDate(campaign.getEndDate()); + filariasisCampaignListDTO.setStartDate(campaign.getStartDate()); + filariasisCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); + filariasisCampaignListDTO.setNumberOfIndividuals(String.valueOf(campaign.getNumberOfIndividuals())); + dto.setFields(filariasisCampaignListDTO); + return dto; + } private List parseBase64Json(String jsonString) { try { ObjectMapper objectMapper = new ObjectMapper(); From 2aa90c8238c48442e873330b6811917e79106ff2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 16:49:13 +0530 Subject: [PATCH 077/450] Tb confirmed cases --- .../com/iemr/flw/controller/TBController.java | 66 ++++++++ .../flw/domain/iemr/TBConfirmedCaseDTO.java | 29 ++++ .../iemr/flw/dto/iemr/TBConfirmedCase.java | 75 +++++++++ .../iemr/TBConfirmedTreatmentRepository.java | 18 ++ .../flw/service/TBConfirmedCaseService.java | 18 ++ .../impl/TBConfirmedCaseServiceImpl.java | 154 ++++++++++++++++++ 6 files changed, 360 insertions(+) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java create mode 100644 src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index 56afcb987..e18b1abbf 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -1,14 +1,17 @@ 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.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 +31,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, @@ -125,4 +131,64 @@ public String saveAllSuspectedByUserId(@RequestBody TBSuspectedRequestDTO reques return response.toString(); } + @Operation(summary = "save tb confirmed case data of beneficiary") + @RequestMapping(value = { "/confirmed/save" }, method = { RequestMethod.POST }) + public String saveConfirmedCase( + @RequestBody TBConfirmedCaseDTO 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, 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( + @PathVariable Long benId, + @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/domain/iemr/TBConfirmedCaseDTO.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java new file mode 100644 index 000000000..180c3bbed --- /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/dto/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java new file mode 100644 index 000000000..2c01638b6 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java @@ -0,0 +1,75 @@ +package com.iemr.flw.dto.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 = "suspected_tb_id", nullable = false) + private Integer suspectedTbId; + + @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/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java new file mode 100644 index 000000000..d3cceaf2e --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -0,0 +1,18 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.dto.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); + + Optional findByBenIdAndSuspectedTbId(Long benId, Integer suspectedTbId); +} 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 000000000..beaffa09d --- /dev/null +++ b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java @@ -0,0 +1,18 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; +import com.iemr.flw.dto.iemr.TBConfirmedCase; +import io.swagger.v3.oas.annotations.info.License; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public interface TBConfirmedCaseService { + + String save(TBConfirmedCaseDTO 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/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java new file mode 100644 index 000000000..5a46795f8 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -0,0 +1,154 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; +import com.iemr.flw.dto.iemr.TBConfirmedCase; +import com.iemr.flw.repo.iemr.TBConfirmedTreatmentRepository; +import com.iemr.flw.service.TBConfirmedCaseService; + +import com.iemr.flw.utils.JwtUtil; +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.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(TBConfirmedCaseDTO dto, String authorisation) throws Exception { + OutputResponse response = new OutputResponse(); + + try { + if (dto != null) { + logger.info("Saving TB confirmed case: " + dto); + + TBConfirmedCase entity = new TBConfirmedCase(); + + entity.setBenId(dto.getBenId()); + entity.setUserId(dto.getUserId()); + entity.setSuspectedTbId(dto.getSuspectedTbId()); + 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()); + + 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 { + OutputResponse response = new OutputResponse(); + + + try { + Integer userId = jwtUtil.extractUserId(authorisation); + + List list = repository.findByUserId(userId) + .stream() + .filter(x -> x.getUserId() != null && x.getUserId().equals(userId)) + .collect(Collectors.toList()); + + if (!list.isEmpty()) { + List dtoList = list.stream() + .map(this::toDTO) + .collect(Collectors.toList()); + + response.setResponse(dtoList.toString()); + } else { + response.setError(404, "No record found for userId: " + userId); + } + + } catch (Exception e) { + logger.error("Error getting TB confirmed case by userId", e); + response.setError(5000, "Error getting TB confirmed case: " + e.getMessage()); + } + + return response.toString(); + } + + // Utility: convert entity -> DTO + private TBConfirmedCaseDTO toDTO(TBConfirmedCase entity) { + TBConfirmedCaseDTO dto = new TBConfirmedCaseDTO(); + + dto.setBenId(entity.getBenId()); + dto.setUserId(entity.getUserId()); + dto.setSuspectedTbId(entity.getSuspectedTbId()); + 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; + } +} From 66ba4e8261ef772574b2cb1c6cdddecd44bf62f4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 17:07:26 +0530 Subject: [PATCH 078/450] Tb confirmed cases --- src/main/java/com/iemr/flw/controller/TBController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index e18b1abbf..f395f59b6 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -165,7 +165,7 @@ public String saveConfirmedCase( } @Operation(summary = "get tb confirmed case by beneficiary id") - @RequestMapping(value = { "/confirmed/getAll}" }, method = { RequestMethod.GET }) + @RequestMapping(value = { "/confirmed/getAll" }, method = { RequestMethod.GET }) public String getConfirmedByBenId( @PathVariable Long benId, @RequestHeader(value = "jwtToken") String token) { From 539a3e16851b69c08ac105d1ada3fd92af0a9787 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 17:19:10 +0530 Subject: [PATCH 079/450] Tb confirmed cases --- .../com/iemr/flw/{dto => domain}/iemr/TBConfirmedCase.java | 2 +- .../iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java | 2 +- .../java/com/iemr/flw/service/TBConfirmedCaseService.java | 4 ---- .../com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java | 2 +- 4 files changed, 3 insertions(+), 7 deletions(-) rename src/main/java/com/iemr/flw/{dto => domain}/iemr/TBConfirmedCase.java (98%) diff --git a/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java similarity index 98% rename from src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java rename to src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java index 2c01638b6..2d0da6ea6 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCase.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -1,4 +1,4 @@ -package com.iemr.flw.dto.iemr; +package com.iemr.flw.domain.iemr; import jakarta.persistence.*; import lombok.Data; diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java index d3cceaf2e..c3fae1e2b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -1,6 +1,6 @@ package com.iemr.flw.repo.iemr; -import com.iemr.flw.dto.iemr.TBConfirmedCase; +import com.iemr.flw.domain.iemr.TBConfirmedCase; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java index beaffa09d..61a8d2a38 100644 --- a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java +++ b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java @@ -1,12 +1,8 @@ package com.iemr.flw.service; import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; -import com.iemr.flw.dto.iemr.TBConfirmedCase; -import io.swagger.v3.oas.annotations.info.License; import org.springframework.stereotype.Service; -import java.util.List; - @Service public interface TBConfirmedCaseService { diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 5a46795f8..14c7acad5 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -1,7 +1,7 @@ package com.iemr.flw.service.impl; import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; -import com.iemr.flw.dto.iemr.TBConfirmedCase; +import com.iemr.flw.domain.iemr.TBConfirmedCase; import com.iemr.flw.repo.iemr.TBConfirmedTreatmentRepository; import com.iemr.flw.service.TBConfirmedCaseService; From cc5dc006519a712ae8de12b393c92893e4b125d8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 17:37:15 +0530 Subject: [PATCH 080/450] fix end date --- src/main/java/com/iemr/flw/controller/TBController.java | 1 - .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index f395f59b6..96a894916 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -167,7 +167,6 @@ public String saveConfirmedCase( @Operation(summary = "get tb confirmed case by beneficiary id") @RequestMapping(value = { "/confirmed/getAll" }, method = { RequestMethod.GET }) public String getConfirmedByBenId( - @PathVariable Long benId, @RequestHeader(value = "jwtToken") String token) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 32596222a..56e3549a4 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -63,7 +63,7 @@ public List saveOrsCampaign(List orsCampaignDTO, St campaignOrsEntity.setCreatedBy(userName); campaignOrsEntity.setUpdatedBy(userName); campaignOrsEntity.setStartDate(campaignDTO.getFields().getStartDate()); - campaignOrsEntity.setStartDate(campaignDTO.getFields().getEndDate()); + campaignOrsEntity.setEndDate(campaignDTO.getFields().getEndDate()); try { String familiesStr = campaignDTO.getFields().getNumberOfFamilies(); From 4ec2146aeef192f110b9f3262a6086263039f3b4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 16 Jan 2026 18:04:30 +0530 Subject: [PATCH 081/450] fix ors id issue --- .../com/iemr/flw/domain/iemr/CampaignOrs.java | 6 +----- .../flw/domain/iemr/PulsePolioCampaign.java | 7 ++----- .../dto/iemr/OrsCampaignListResponseDTO.java | 20 ++++++++++++++----- .../flw/dto/iemr/OrsCampaignResponseDTO.java | 1 - .../dto/iemr/PolioCampaignResponseDTO.java | 1 - .../flw/service/impl/CampaignServiceImpl.java | 6 ++++-- 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java index 9d4c5c1ad..1b53bfa12 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java +++ b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java @@ -27,11 +27,7 @@ public class CampaignOrs { @Column(name = "number_of_families", nullable = false) private Integer numberOfFamilies = 0; - /** - * Store JSON array like ["img1.jpg","img2.jpg"] - * MySQL JSON column - */ - @Column(name = "campaign_photos", columnDefinition = "json") + @Column(name = "campaign_photos") private String campaignPhotos; @Column(name = "created_by", length = 200) diff --git a/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java index 446217eb2..e4733b6f5 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java @@ -27,11 +27,8 @@ public class PulsePolioCampaign { @Column(name = "number_of_children", nullable = false) private Integer numberOfChildren = 0; - /** - * Store JSON array like ["img1.jpg","img2.jpg"] - * MySQL JSON column - */ - @Column(name = "campaign_photos", columnDefinition = "json") + + @Column(name = "campaign_photos") private String campaignPhotos; @Column(name = "created_by", length = 200) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java index 7b8ec2dab..8527b8067 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java @@ -1,5 +1,7 @@ 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; @@ -7,9 +9,17 @@ @Data public class OrsCampaignListResponseDTO { - private Long id; - private LocalDate startDate; - private LocalDate endDate; - private String numberOfFamilies; - private List campaignPhotos; // Base64 or URLs + @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; } \ 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 index 44351ddbf..5c8b954dd 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignResponseDTO.java @@ -5,6 +5,5 @@ @Data public class OrsCampaignResponseDTO { private Long id; - private String visitDate; private OrsCampaignListResponseDTO fields; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java index 06370ac07..a65042364 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignResponseDTO.java @@ -5,6 +5,5 @@ @Data public class PolioCampaignResponseDTO { private Long id; - private String visitDate; private PolioCampaignListResponseDTO fields; } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 56e3549a4..326212c4a 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -307,10 +307,11 @@ private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { if (campaign.getCampaignPhotos() != null) { List photosList = parseBase64Json(campaign.getCampaignPhotos()); orsCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches - } orsCampaignListDTO.setEndDate(campaign.getEndDate()); - + } + orsCampaignListDTO.setEndDate(campaign.getEndDate()); orsCampaignListDTO.setStartDate(campaign.getStartDate()); orsCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); + dto.setId(campaign.getId()); dto.setFields(orsCampaignListDTO); return dto; } @@ -325,6 +326,7 @@ private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) polioCampaignListDTO.setEndDate(campaign.getEndDate()); polioCampaignListDTO.setStartDate(campaign.getStartDate()); polioCampaignListDTO.setNumberOfChildren(String.valueOf(campaign.getNumberOfChildren())); + dto.setId(campaign.getId()); dto.setFields(polioCampaignListDTO); return dto; } From 28a231b2261db542278c5ba18b92905c35278e87 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Fri, 16 Jan 2026 20:36:54 +0530 Subject: [PATCH 082/450] Enable SpringDoc API docs and Swagger UI --- src/main/resources/application.properties | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ab7eae2a6..034fbcc4a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -63,12 +63,12 @@ fhir-url= # TM Config tm-url= -springdoc.api-docs.enabled=false -springdoc.swagger-ui.enabled=false +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 \ No newline at end of file +notificationurl=https://uatamrit.piramalswasthya.org/common-api/firebaseNotification/sendNotification From 41db3b3e4c8deac58311782cee3ca7d5e2bbee09 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 18 Jan 2026 22:31:29 +0530 Subject: [PATCH 083/450] remove has_symptoms --- src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java | 3 --- src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 1 - 2 files changed, 4 deletions(-) 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 481e613d7..9ea5ce64f 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -54,9 +54,6 @@ public class TBSuspected { @Column(name = "reason_for_suspicion", length = 500) private String reasonForSuspicion; - // Symptoms - @Column(name = "has_symptoms", nullable = false) - private Boolean hasSymptoms = false; // Chest X-Ray @Column(name = "is_chest_xray_done") 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 b44e0ed44..9c56df39a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -14,7 +14,6 @@ public class TBSuspectedDTO { private String visitLabel; private String typeOfTBCase; private String reasonForSuspicion; - private Boolean hasSymptoms; private Boolean isSputumCollected; private String sputumSubmittedAt; private String nikshayId; From 72fdce158a70401697d09a72cce86b3d7eff9ee4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 18 Jan 2026 22:40:05 +0530 Subject: [PATCH 084/450] remove isConfirmed --- src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java | 3 --- src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 1 - 2 files changed, 4 deletions(-) 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 9ea5ce64f..7a69a17f3 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -72,9 +72,6 @@ public class TBSuspected { @Column(name = "is_drtb_confirmed") private Boolean isDRTBConfirmed; - @Column(name = "is_confirmed", nullable = false) - private Boolean isConfirmed = false; - @Column(name = "provider_service_map_id") private Integer providerServiceMapId; 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 9c56df39a..821b0f037 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -23,7 +23,6 @@ public class TBSuspectedDTO { private String referralFacility; private Boolean isTBConfirmed; private Boolean isDRTBConfirmed; - private Boolean isConfirmed; private Boolean referred; private String followUps; } From cd6b0a24d362a094def426cab9ced9bbb85d21cd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 18 Jan 2026 22:47:49 +0530 Subject: [PATCH 085/450] remove visit_code --- src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java | 3 --- src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 1 - 2 files changed, 4 deletions(-) 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 7a69a17f3..3fe2d66a3 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -41,9 +41,6 @@ public class TBSuspected { @Column(name = "followups") private String followUps; - @Column(name = "visit_code", nullable = false) - private Long visitCode; - // Visit Information @Column(name = "visit_label", length = 100, nullable = false) private String visitLabel; 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 821b0f037..52c46e5b5 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -10,7 +10,6 @@ public class TBSuspectedDTO { private Long id; private Long benId; - private Long visitCode; private String visitLabel; private String typeOfTBCase; private String reasonForSuspicion; From 84a28bc6bf94978108c37e23f6226b5196ab8fbe Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 18 Jan 2026 22:48:33 +0530 Subject: [PATCH 086/450] remove visit_code --- src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 3fe2d66a3..417600f1c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -42,10 +42,10 @@ public class TBSuspected { private String followUps; // Visit Information - @Column(name = "visit_label", length = 100, nullable = false) + @Column(name = "visit_label") private String visitLabel; - @Column(name = "type_of_tb_case", length = 50, nullable = false) + @Column(name = "type_of_tb_case") private String typeOfTBCase; @Column(name = "reason_for_suspicion", length = 500) From 169bafea9d98fa8b9236d88f6de6f9a0b2081824 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 18 Jan 2026 23:26:55 +0530 Subject: [PATCH 087/450] fix photo campaign issue --- .../flw/service/impl/CampaignServiceImpl.java | 43 +++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 326212c4a..b1d618b08 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -305,8 +305,26 @@ private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { OrsCampaignResponseDTO dto = new OrsCampaignResponseDTO(); OrsCampaignListResponseDTO orsCampaignListDTO = new OrsCampaignListResponseDTO(); if (campaign.getCampaignPhotos() != null) { - List photosList = parseBase64Json(campaign.getCampaignPhotos()); - orsCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches + 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); + // ✅ Now List matches } orsCampaignListDTO.setEndDate(campaign.getEndDate()); orsCampaignListDTO.setStartDate(campaign.getStartDate()); @@ -320,7 +338,26 @@ private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) PolioCampaignResponseDTO dto = new PolioCampaignResponseDTO(); PolioCampaignListResponseDTO polioCampaignListDTO = new PolioCampaignListResponseDTO(); if (campaign.getCampaignPhotos() != null) { - List photosList = parseBase64Json(campaign.getCampaignPhotos()); + 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()); + } + } + + polioCampaignListDTO.setCampaignPhotos(photosList); + polioCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches } polioCampaignListDTO.setEndDate(campaign.getEndDate()); From dedbc4aa5413333ca1f077d24d52f969e0f66809 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 10:43:36 +0530 Subject: [PATCH 088/450] fix data type issue --- .../FilariasisCampaignListResponseDTO.java | 2 +- .../dto/iemr/OrsCampaignListResponseDTO.java | 2 +- .../iemr/PolioCampaignListResponseDTO.java | 4 +- .../com/iemr/flw/service/CampaignService.java | 2 +- .../flw/service/impl/CampaignServiceImpl.java | 92 ++++++++----------- 5 files changed, 44 insertions(+), 58 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java index 644448a77..be62cfe0e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java @@ -21,7 +21,7 @@ public class FilariasisCampaignListResponseDTO { private String numberOfFamilies; @JsonProperty("no_of_individuals") - private String numberOfIndividuals; + private Double numberOfIndividuals; @JsonProperty("mda_photos") private List mdaPhotos; diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java index 8527b8067..e72fb04c6 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsCampaignListResponseDTO.java @@ -18,7 +18,7 @@ public class OrsCampaignListResponseDTO { private LocalDate EndDate; @JsonProperty("number_of_families") - private String NumberOfFamilies; + private Double NumberOfFamilies; @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 index 603d1676e..f27468f3f 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PolioCampaignListResponseDTO.java @@ -15,8 +15,8 @@ public class PolioCampaignListResponseDTO { @JsonProperty("end_date") private LocalDate endDate; - @JsonProperty("number_of_children") - private String numberOfChildren; + @JsonProperty("children_vaccinated") + private Double numberOfChildren; @JsonProperty("campaign_photos") private List campaignPhotos; diff --git a/src/main/java/com/iemr/flw/service/CampaignService.java b/src/main/java/com/iemr/flw/service/CampaignService.java index d1ac02017..26c67a6ac 100644 --- a/src/main/java/com/iemr/flw/service/CampaignService.java +++ b/src/main/java/com/iemr/flw/service/CampaignService.java @@ -18,7 +18,7 @@ public interface CampaignService { List getPolioCampaign(String token) throws IEMRException; - List saveFilariasisCampaign(List filariasisCampaignDTOS, 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/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index b1d618b08..08a966cdf 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -42,6 +42,9 @@ public class CampaignServiceImpl implements CampaignService { @Autowired private JwtUtil jwtUtil; + @Autowired + private ObjectMapper objectMapper; + @Override @Transactional public List saveOrsCampaign(List orsCampaignDTO, String token) throws IEMRException, JsonProcessingException { @@ -77,13 +80,11 @@ public List saveOrsCampaign(List orsCampaignDTO, St throw new IEMRException("Invalid number format for families: " + campaignDTO.getFields().getNumberOfFamilies()); } - - List photos = campaignDTO.getFields().getCampaignPhotos(); - String photosStr = (photos != null && !photos.isEmpty()) - ? String.join(",", photos) - : null; - campaignOrsEntity.setCampaignPhotos(photosStr); - + OrsCampaignListDTO campaignListDTO = new OrsCampaignListDTO(); + if(campaignListDTO!=null){ + String photosJson = objectMapper.writeValueAsString(campaignListDTO.getCampaignPhotos()); + campaignOrsEntity.setCampaignPhotos(photosJson); + } campaignOrsRequest.add(campaignOrsEntity); } @@ -163,13 +164,13 @@ public List savePolioCampaign(List polioCa // Convert photos to base64 JSON array - List photosList = campaignDTO.getFields().getCampaignPhotos(); - String photosStr = (photosList != null && !photosList.isEmpty()) - ? String.join(",", photosList) - : null; + PolioCampaignListDTO polioCampaignListDTO = campaignDTO.getFields(); + if(polioCampaignListDTO!=null){ + String photosJson = objectMapper.writeValueAsString(polioCampaignListDTO.getCampaignPhotos()); + campaignPolioEntity.setCampaignPhotos(photosJson); - campaignPolioEntity.setCampaignPhotos(photosStr); + } campaignPolioRequest.add(campaignPolioEntity); } @@ -185,7 +186,7 @@ public List savePolioCampaign(List polioCa @Override @Transactional - public List saveFilariasisCampaign(List filariasisCampaignDTOS, String token) throws IEMRException { + public List saveFilariasisCampaign(List filariasisCampaignDTOS, String token) throws IEMRException, JsonProcessingException { if (filariasisCampaignDTOS == null || filariasisCampaignDTOS.isEmpty()) { throw new IEMRException("Campaign data is required"); @@ -241,14 +242,13 @@ public List saveFilariasisCampaign(List photosList = campaignDTO.getFields().getMdaPhotos(); - String photosStr = (photosList != null && !photosList.isEmpty()) - ? String.join(",", photosList) - : null; - - filariasisCampaign.setCampaignPhotos(photosStr); + } campaignPolioRequest.add(filariasisCampaign); } @@ -322,13 +322,11 @@ private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { photosList.add(photoStr.trim()); } } - orsCampaignListDTO.setCampaignPhotos(photosList); - // ✅ Now List matches } orsCampaignListDTO.setEndDate(campaign.getEndDate()); orsCampaignListDTO.setStartDate(campaign.getStartDate()); - orsCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); + orsCampaignListDTO.setNumberOfFamilies(Double.valueOf(campaign.getNumberOfFamilies())); dto.setId(campaign.getId()); dto.setFields(orsCampaignListDTO); return dto; @@ -338,7 +336,6 @@ private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) PolioCampaignResponseDTO dto = new PolioCampaignResponseDTO(); PolioCampaignListResponseDTO polioCampaignListDTO = new PolioCampaignListResponseDTO(); if (campaign.getCampaignPhotos() != null) { - ObjectMapper objectMapper = new ObjectMapper(); List photosList = new ArrayList<>(); String photoStr = campaign.getCampaignPhotos(); @@ -357,12 +354,10 @@ private PolioCampaignResponseDTO convertPolioToDTO(PulsePolioCampaign campaign) } polioCampaignListDTO.setCampaignPhotos(photosList); - - polioCampaignListDTO.setCampaignPhotos(photosList); // ✅ Now List matches } polioCampaignListDTO.setEndDate(campaign.getEndDate()); polioCampaignListDTO.setStartDate(campaign.getStartDate()); - polioCampaignListDTO.setNumberOfChildren(String.valueOf(campaign.getNumberOfChildren())); + polioCampaignListDTO.setNumberOfChildren(Double.valueOf(campaign.getNumberOfChildren())); dto.setId(campaign.getId()); dto.setFields(polioCampaignListDTO); return dto; @@ -372,13 +367,27 @@ private FilariasisResponseDTO convertFilariasisDTO(FilariasisCampaign campaign) FilariasisResponseDTO dto = new FilariasisResponseDTO(); FilariasisCampaignListResponseDTO filariasisCampaignListDTO = new FilariasisCampaignListResponseDTO(); if (campaign.getCampaignPhotos() != null) { - List photosList = parseBase64Json(campaign.getCampaignPhotos()); - filariasisCampaignListDTO.setMdaPhotos(photosList); // ✅ Now List matches + 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()); - filariasisCampaignListDTO.setNumberOfFamilies(String.valueOf(campaign.getNumberOfFamilies())); - filariasisCampaignListDTO.setNumberOfIndividuals(String.valueOf(campaign.getNumberOfIndividuals())); + filariasisCampaignListDTO.setNumberOfIndividuals(Double.valueOf(campaign.getNumberOfIndividuals())); dto.setFields(filariasisCampaignListDTO); return dto; } @@ -392,29 +401,6 @@ private List parseBase64Json(String jsonString) { } - private String convertPhotosToBase64Json(List photos) throws IEMRException { - try { - List cleanedBase64Images = new ArrayList<>(); - - for (String photo : photos) { - if (photo != null && !photo.trim().isEmpty()) { - - // remove data:image/...;base64, if present - String cleanBase64 = photo.contains(",") - ? photo.substring(photo.indexOf(",") + 1) - : photo; - - cleanedBase64Images.add(cleanBase64); - } - } - - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.writeValueAsString(cleanedBase64Images); - - } catch (Exception e) { - throw new IEMRException("Error processing base64 photos: " + e.getMessage()); - } - } } From b6e39e82c336d9ce395353da57aa421ce368faec Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 10:59:44 +0530 Subject: [PATCH 089/450] add column defination --- src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java | 2 +- src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java | 2 +- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java index 1b53bfa12..e33e15439 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java +++ b/src/main/java/com/iemr/flw/domain/iemr/CampaignOrs.java @@ -27,7 +27,7 @@ public class CampaignOrs { @Column(name = "number_of_families", nullable = false) private Integer numberOfFamilies = 0; - @Column(name = "campaign_photos") + @Column(name = "campaign_photos",columnDefinition = "LONGTEXT") private String campaignPhotos; @Column(name = "created_by", length = 200) diff --git a/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java index e4733b6f5..ddf7b8b60 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java +++ b/src/main/java/com/iemr/flw/domain/iemr/PulsePolioCampaign.java @@ -28,7 +28,7 @@ public class PulsePolioCampaign { private Integer numberOfChildren = 0; - @Column(name = "campaign_photos") + @Column(name = "campaign_photos",columnDefinition = "LONGTEXT") private String campaignPhotos; @Column(name = "created_by", length = 200) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 08a966cdf..0005bfb2d 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -42,8 +42,7 @@ public class CampaignServiceImpl implements CampaignService { @Autowired private JwtUtil jwtUtil; - @Autowired - private ObjectMapper objectMapper; + private ObjectMapper objectMapper = new ObjectMapper(); @Override @Transactional From ca5d70cce6e19add5f1a8278a6057f4302410d1d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 11:25:33 +0530 Subject: [PATCH 090/450] add ors image --- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 0005bfb2d..29c67a96e 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -79,7 +79,8 @@ public List saveOrsCampaign(List orsCampaignDTO, St throw new IEMRException("Invalid number format for families: " + campaignDTO.getFields().getNumberOfFamilies()); } - OrsCampaignListDTO campaignListDTO = new OrsCampaignListDTO(); + OrsCampaignListDTO campaignListDTO = campaignDTO.getFields(); + if(campaignListDTO!=null){ String photosJson = objectMapper.writeValueAsString(campaignListDTO.getCampaignPhotos()); campaignOrsEntity.setCampaignPhotos(photosJson); From 08251ddd994d3c6e3805eb76be5549018d9b90eb Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 18:59:00 +0530 Subject: [PATCH 091/450] add NumberOfIndividuals --- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 29c67a96e..04ad5c371 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -230,7 +230,7 @@ public List saveFilariasisCampaign(List Date: Mon, 19 Jan 2026 19:15:40 +0530 Subject: [PATCH 092/450] add NumberOfIndividuals --- .../iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java | 2 +- .../java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java index be62cfe0e..6baa38d91 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java @@ -18,7 +18,7 @@ public class FilariasisCampaignListResponseDTO { private LocalDate endDate; @JsonProperty("no_of_families") - private String numberOfFamilies; + private Double numberOfFamilies; @JsonProperty("no_of_individuals") private Double numberOfIndividuals; diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 04ad5c371..4db9209a4 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -388,6 +388,7 @@ private FilariasisResponseDTO convertFilariasisDTO(FilariasisCampaign campaign) filariasisCampaignListDTO.setEndDate(campaign.getEndDate()); filariasisCampaignListDTO.setStartDate(campaign.getStartDate()); filariasisCampaignListDTO.setNumberOfIndividuals(Double.valueOf(campaign.getNumberOfIndividuals())); + filariasisCampaignListDTO.setNumberOfFamilies(Double.valueOf(campaign.getNumberOfFamilies())); dto.setFields(filariasisCampaignListDTO); return dto; } From 5a5cdd3c04dd014923fbb6eb7d028c597a3da2a0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 19:16:34 +0530 Subject: [PATCH 093/450] add NumberOfIndividuals --- .../com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java | 1 + src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java index 6baa38d91..700d46653 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/FilariasisCampaignListResponseDTO.java @@ -27,4 +27,5 @@ public class FilariasisCampaignListResponseDTO { private List mdaPhotos; + } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 4db9209a4..d989df6c7 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -389,6 +389,7 @@ private FilariasisResponseDTO convertFilariasisDTO(FilariasisCampaign campaign) filariasisCampaignListDTO.setStartDate(campaign.getStartDate()); filariasisCampaignListDTO.setNumberOfIndividuals(Double.valueOf(campaign.getNumberOfIndividuals())); filariasisCampaignListDTO.setNumberOfFamilies(Double.valueOf(campaign.getNumberOfFamilies())); + dto.setFields(filariasisCampaignListDTO); return dto; } From 88238398f26aa13b7a0195f195ce1a8791bff605 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 19:32:49 +0530 Subject: [PATCH 094/450] add api for tb confirmed cases --- .../com/iemr/flw/controller/TBController.java | 5 +- .../iemr/flw/domain/iemr/TBConfirmedCase.java | 2 +- .../flw/dto/iemr/TBConfirmedRequestDTO.java | 13 +++++ .../flw/service/TBConfirmedCaseService.java | 4 +- .../impl/TBConfirmedCaseServiceImpl.java | 50 +++++++++++-------- 5 files changed, 48 insertions(+), 26 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/TBConfirmedRequestDTO.java diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index 96a894916..e95c3ab4c 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -2,6 +2,7 @@ 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; @@ -134,7 +135,7 @@ public String saveAllSuspectedByUserId(@RequestBody TBSuspectedRequestDTO reques @Operation(summary = "save tb confirmed case data of beneficiary") @RequestMapping(value = { "/confirmed/save" }, method = { RequestMethod.POST }) public String saveConfirmedCase( - @RequestBody TBConfirmedCaseDTO requestDTO, + @RequestBody TBConfirmedRequestDTO requestDTO, @RequestHeader(value = "jwtToken") String token) { OutputResponse response = new OutputResponse(); @@ -146,7 +147,7 @@ public String saveConfirmedCase( + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); - String result = tbConfirmedCaseService.save(requestDTO, token); + String result = tbConfirmedCaseService.save(requestDTO.getTbConfirmedList(), token); if (result != null) response.setResponse(result); diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java index 2d0da6ea6..826fa2905 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -17,8 +17,8 @@ public class TBConfirmedCase { @Column(name = "ben_id", nullable = false) private Long benId; - @Column(name = "user_id",nullable = false) + @Column(name = "user_id",nullable = false) private Integer userId; @Column(name = "suspected_tb_id", nullable = false) 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 000000000..d3e76a4a7 --- /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/service/TBConfirmedCaseService.java b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java index 61a8d2a38..64505b791 100644 --- a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java +++ b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java @@ -3,10 +3,12 @@ import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; import org.springframework.stereotype.Service; +import java.util.List; + @Service public interface TBConfirmedCaseService { - String save(TBConfirmedCaseDTO tbConfirmedCaseDTO, String token) throws Exception; + String save(List tbConfirmedCaseDTO, String token) throws Exception; String getByBenId(Long benId, String authorisation) throws Exception; diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 14c7acad5..c09e30e85 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -29,34 +29,40 @@ public TBConfirmedCaseServiceImpl(TBConfirmedTreatmentRepository repository) { } @Override - public String save(TBConfirmedCaseDTO dto, String authorisation) throws Exception { + public String save(List request, String authorisation) throws Exception { OutputResponse response = new OutputResponse(); try { - if (dto != null) { - logger.info("Saving TB confirmed case: " + dto); + if (request != null) { + logger.info("Saving TB confirmed case: " + request); TBConfirmedCase entity = new TBConfirmedCase(); + for(TBConfirmedCaseDTO dto:request){ + entity.setBenId(dto.getBenId()); + entity.setUserId(dto.getUserId()); + entity.setSuspectedTbId(dto.getSuspectedTbId()); + 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); + + } + } + + - entity.setBenId(dto.getBenId()); - entity.setUserId(dto.getUserId()); - entity.setSuspectedTbId(dto.getSuspectedTbId()); - 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()); - - repository.save(entity); response.setResponse("TB Confirmed case saved successfully"); From c6109b4dc5978fe003aae0063d67c5a0866aa8f5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 19:42:24 +0530 Subject: [PATCH 095/450] add api for tb confirmed cases --- src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java | 2 -- .../com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java index 826fa2905..adacdb1b8 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -21,8 +21,6 @@ public class TBConfirmedCase { @Column(name = "user_id",nullable = false) private Integer userId; - @Column(name = "suspected_tb_id", nullable = false) - private Integer suspectedTbId; @Column(name = "regimen_type") private String regimenType; diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index c09e30e85..2f4a26b7e 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -40,7 +40,6 @@ public String save(List request, String authorisation) throw for(TBConfirmedCaseDTO dto:request){ entity.setBenId(dto.getBenId()); entity.setUserId(dto.getUserId()); - entity.setSuspectedTbId(dto.getSuspectedTbId()); entity.setRegimenType(dto.getRegimenType()); entity.setTreatmentStartDate(dto.getTreatmentStartDate()); entity.setExpectedTreatmentCompletionDate(dto.getExpectedTreatmentCompletionDate()); @@ -139,7 +138,6 @@ private TBConfirmedCaseDTO toDTO(TBConfirmedCase entity) { dto.setBenId(entity.getBenId()); dto.setUserId(entity.getUserId()); - dto.setSuspectedTbId(entity.getSuspectedTbId()); dto.setRegimenType(entity.getRegimenType()); dto.setTreatmentStartDate(entity.getTreatmentStartDate()); dto.setExpectedTreatmentCompletionDate(entity.getExpectedTreatmentCompletionDate()); From 129fa37640e10d2525f82f73ef9d00ff1c6aa590 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 19 Jan 2026 19:46:39 +0530 Subject: [PATCH 096/450] Update TBConfirmedTreatmentRepository.java --- .../com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java index c3fae1e2b..31345dd40 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -14,5 +14,4 @@ public interface TBConfirmedTreatmentRepository List findByBenId(Long benId); List findByUserId(Integer benId); - Optional findByBenIdAndSuspectedTbId(Long benId, Integer suspectedTbId); } From f25f046afc34eab851f772d1bc52b8cbb68c692b Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 19 Jan 2026 19:55:42 +0530 Subject: [PATCH 097/450] Update TBConfirmedCaseServiceImpl.java --- .../com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 2f4a26b7e..3040558c4 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -39,7 +39,7 @@ public String save(List request, String authorisation) throw TBConfirmedCase entity = new TBConfirmedCase(); for(TBConfirmedCaseDTO dto:request){ entity.setBenId(dto.getBenId()); - entity.setUserId(dto.getUserId()); + entity.setUserId(jwtUtil.extractUserId(authorisation)); entity.setRegimenType(dto.getRegimenType()); entity.setTreatmentStartDate(dto.getTreatmentStartDate()); entity.setExpectedTreatmentCompletionDate(dto.getExpectedTreatmentCompletionDate()); From 726bfe145a091fb9c64bb7e758504ae85fb5e517 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 19 Jan 2026 20:02:15 +0530 Subject: [PATCH 098/450] Update TBConfirmedCaseServiceImpl.java --- .../impl/TBConfirmedCaseServiceImpl.java | 34 ++++--------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 3040558c4..bd8dddfa4 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -4,7 +4,8 @@ import com.iemr.flw.domain.iemr.TBConfirmedCase; 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.response.OutputResponse; import org.slf4j.Logger; @@ -103,33 +104,12 @@ public String getByBenId(Long benId, String authorisation) throws Exception { @Override public String getByUserId(String authorisation) throws Exception { - OutputResponse response = new OutputResponse(); - - - try { - Integer userId = jwtUtil.extractUserId(authorisation); - - List list = repository.findByUserId(userId) - .stream() - .filter(x -> x.getUserId() != null && x.getUserId().equals(userId)) - .collect(Collectors.toList()); - - if (!list.isEmpty()) { - List dtoList = list.stream() - .map(this::toDTO) - .collect(Collectors.toList()); + Integer userId = jwtUtil.extractUserId(authorisation); - response.setResponse(dtoList.toString()); - } else { - response.setError(404, "No record found for userId: " + userId); - } - - } catch (Exception e) { - logger.error("Error getting TB confirmed case by userId", e); - response.setError(5000, "Error getting TB confirmed case: " + e.getMessage()); - } - - return response.toString(); + List list = repository.findByUserId(userId); + + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(list); } // Utility: convert entity -> DTO From 6d9d005819fa1db1a4fa2d2858cf0d33f0087cfc Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 19 Jan 2026 20:27:19 +0530 Subject: [PATCH 099/450] Update TBSuspectedDTO.java --- src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 1 + 1 file changed, 1 insertion(+) 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 52c46e5b5..2eb0950c1 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -12,6 +12,7 @@ public class TBSuspectedDTO { private Long benId; private String visitLabel; private String typeOfTBCase; + private Timestamp visitDate; private String reasonForSuspicion; private Boolean isSputumCollected; private String sputumSubmittedAt; From 05281620a1a688fdac4009de9c9afead51d9351e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 22:46:12 +0530 Subject: [PATCH 100/450] add api for tb confirmed cases --- .../com/iemr/flw/domain/iemr/TBSuspected.java | 2 ++ .../com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 2 ++ .../iemr/TBConfirmedTreatmentRepository.java | 2 -- .../impl/TBConfirmedCaseServiceImpl.java | 36 ++++++------------- .../com/iemr/flw/utils/LocalDateAdapter.java | 20 +++++++++++ 5 files changed, 35 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/iemr/flw/utils/LocalDateAdapter.java 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 417600f1c..2de2baf82 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -72,6 +72,8 @@ public class TBSuspected { @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/dto/iemr/TBSuspectedDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java index 52c46e5b5..29fb25f6e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -11,6 +11,7 @@ public class TBSuspectedDTO { private Long benId; private String visitLabel; + private Timestamp visitDate; private String typeOfTBCase; private String reasonForSuspicion; private Boolean isSputumCollected; @@ -21,6 +22,7 @@ public class TBSuspectedDTO { 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/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java index c3fae1e2b..8b9303eac 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -13,6 +13,4 @@ public interface TBConfirmedTreatmentRepository List findByBenId(Long benId); List findByUserId(Integer benId); - - Optional findByBenIdAndSuspectedTbId(Long benId, Integer suspectedTbId); } diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 2f4a26b7e..212a83d76 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -1,17 +1,21 @@ 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.repo.iemr.TBConfirmedTreatmentRepository; import com.iemr.flw.service.TBConfirmedCaseService; 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; @@ -39,7 +43,7 @@ public String save(List request, String authorisation) throw TBConfirmedCase entity = new TBConfirmedCase(); for(TBConfirmedCaseDTO dto:request){ entity.setBenId(dto.getBenId()); - entity.setUserId(dto.getUserId()); + entity.setUserId(jwtUtil.extractUserId(authorisation)); entity.setRegimenType(dto.getRegimenType()); entity.setTreatmentStartDate(dto.getTreatmentStartDate()); entity.setExpectedTreatmentCompletionDate(dto.getExpectedTreatmentCompletionDate()); @@ -103,33 +107,15 @@ public String getByBenId(Long benId, String authorisation) throws Exception { @Override public String getByUserId(String authorisation) throws Exception { - OutputResponse response = new OutputResponse(); - - - try { - Integer userId = jwtUtil.extractUserId(authorisation); - - List list = repository.findByUserId(userId) - .stream() - .filter(x -> x.getUserId() != null && x.getUserId().equals(userId)) - .collect(Collectors.toList()); - - if (!list.isEmpty()) { - List dtoList = list.stream() - .map(this::toDTO) - .collect(Collectors.toList()); - response.setResponse(dtoList.toString()); - } else { - response.setError(404, "No record found for userId: " + userId); - } + Integer userId = jwtUtil.extractUserId(authorisation); + List list = repository.findByUserId(userId); - } catch (Exception e) { - logger.error("Error getting TB confirmed case by userId", e); - response.setError(5000, "Error getting TB confirmed case: " + e.getMessage()); - } + Gson gson = new GsonBuilder() + .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) + .create(); - return response.toString(); + return gson.toJson(list); } // Utility: convert entity -> DTO 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 000000000..d0081c299 --- /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()); + } +} From 35355e38f69cd00727d1e2c8540de6b5a3346fc5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 19 Jan 2026 23:11:19 +0530 Subject: [PATCH 101/450] add api for tb confirmed cases --- src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 1 - 1 file changed, 1 deletion(-) 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 13231fd44..29fb25f6e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -13,7 +13,6 @@ public class TBSuspectedDTO { private String visitLabel; private Timestamp visitDate; private String typeOfTBCase; - private Timestamp visitDate; private String reasonForSuspicion; private Boolean isSputumCollected; private String sputumSubmittedAt; From 1f6d2c689f2724e0634772ee6190edf03c9c535c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 20 Jan 2026 11:01:48 +0530 Subject: [PATCH 102/450] add api for tb tb confirmed cases --- .../flw/dto/iemr/TBConfirmedCasesResponseDTO.java | 11 +++++++++++ .../flw/service/impl/TBConfirmedCaseServiceImpl.java | 8 +++++--- 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/TBConfirmedCasesResponseDTO.java 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 000000000..42504dcdb --- /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/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 9b4f80a7a..39b121775 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -4,6 +4,7 @@ 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; @@ -108,15 +109,16 @@ public String getByBenId(Long benId, String authorisation) throws Exception { @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(list); + return gson.toJson(tbConfirmedCasesResponseDTO); } // Utility: convert entity -> DTO From 68e12262befbdd276cc1a5f0e49ac58e0bdda6bd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 20 Jan 2026 16:52:04 +0530 Subject: [PATCH 103/450] AMM-2135 add More Parameters in the API --- .../com/iemr/flw/domain/iemr/TBScreening.java | 24 +++++++++++++++++++ .../com/iemr/flw/dto/iemr/TBScreeningDTO.java | 11 +++++++++ 2 files changed, 35 insertions(+) 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 9bf7ea8de..aab7d251c 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,28 @@ 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; } 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 270526bdc..73e9a0306 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -29,6 +29,17 @@ public class TBScreeningDTO { private Boolean 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; + + + public Long getId() { return id; } From 4cc15d4d46eb8ba52986d5db0752c6d57818ac83 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 21 Jan 2026 16:43:11 +0530 Subject: [PATCH 104/450] add new column in tb screening --- src/main/java/com/iemr/flw/domain/iemr/TBScreening.java | 9 +++++++++ src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java | 4 ++++ 2 files changed, 13 insertions(+) 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 aab7d251c..6789f9bf7 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java @@ -70,4 +70,13 @@ public class TBScreening { @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/dto/iemr/TBScreeningDTO.java b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java index 73e9a0306..017d73af2 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -37,6 +37,10 @@ public class TBScreeningDTO { private Boolean bmi; private Boolean contactWithTBPatient; private Boolean historyOfTBInLastFiveYrs; + private String sympotomatic; + private String asymptomatic; + private String recommandateTest; + From 448d38361905f2b0f5ea1eb41c3088d3b384a760 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 2 Feb 2026 17:49:26 +0530 Subject: [PATCH 105/450] Update common_docker.properties --- src/main/environment/common_docker.properties | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index b6650a5d5..befe00694 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------------------------------------------------------------------- @@ -38,3 +38,4 @@ send-message-url=${SMS_MESSAGE_URL} #crash.logs.base.path=${CRASH_LOGS_PATH} + From 5fbfea4ab4d1ab845d10accfbe81e659718cf96c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 3 Feb 2026 12:25:03 +0530 Subject: [PATCH 106/450] Check is document is upload during claim incentive --- src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java | 5 +++++ 1 file changed, 5 insertions(+) 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 58da99587..9a07f65c4 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; } From 6a3b96b925d8030268f1ed5f1082ccee547c1a04 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 5 Feb 2026 11:45:58 +0530 Subject: [PATCH 107/450] Incentive for Completing treatment of PB (Paucibacillary) leprosy patients --- .../controller/DiseaseControlController.java | 4 +- .../flw/service/DiseaseControlService.java | 2 +- .../flw/service/IncentiveLogicService.java | 10 ++ .../impl/DiseaseControlServiceImpl.java | 40 +++--- .../flw/service/impl/IncentiveLogicImpl.java | 115 ++++++++++++++++++ 5 files changed, 152 insertions(+), 19 deletions(-) create mode 100644 src/main/java/com/iemr/flw/service/IncentiveLogicService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index e89a53067..5ca4db8d3 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -142,13 +142,13 @@ public ResponseEntity> saveFilaria(@RequestBody FilariaDTO f } @RequestMapping(value = "leprosy/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") - public ResponseEntity> saveLeprosy(@RequestBody LeprosyDTO leprosyDTO) { + public ResponseEntity> saveLeprosy(@RequestBody LeprosyDTO leprosyDTO,@RequestHeader(value = "JwtToken") String token) { Map response = new HashMap<>(); try { if(leprosyDTO!=null){ response.put("status", "Success"); response.put("statusCode", 200); - response.put("data", diseaseControlService.saveLeprosy(leprosyDTO)); + response.put("data", diseaseControlService.saveLeprosy(leprosyDTO,token)); }else { response.put("message", "Invalid request"); response.put("statusCode", 400); diff --git a/src/main/java/com/iemr/flw/service/DiseaseControlService.java b/src/main/java/com/iemr/flw/service/DiseaseControlService.java index 65e315dce..db20d712f 100644 --- a/src/main/java/com/iemr/flw/service/DiseaseControlService.java +++ b/src/main/java/com/iemr/flw/service/DiseaseControlService.java @@ -35,7 +35,7 @@ public interface DiseaseControlService { public String saveKalaAzar(KalaAzarDTO kalaAzarDTO); public String saveAES(AesJeDTO aesJeDTO); public String saveFilaria(FilariaDTO filariaDTO); - public String saveLeprosy(LeprosyDTO leprosyDTO); + public String saveLeprosy(LeprosyDTO leprosyDTO, String token); public Object getAllScreeningData(GetDiseaseRequestHandler getDiseaseRequestHandler); public List saveMosquitoMobilizationNet(List mosquitoNetDTOList); diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java new file mode 100644 index 000000000..3c48c1cf7 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -0,0 +1,10 @@ +package com.iemr.flw.service; + +import org.springframework.stereotype.Service; + +import java.util.Date; + +@Service +public interface IncentiveLogicService { + public void incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token); +} diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index d5f009eaf..f5d3ff736 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -32,6 +32,7 @@ import com.iemr.flw.masterEnum.DiseaseType; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.DiseaseControlService; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.exception.IEMRException; import org.slf4j.Logger; @@ -45,6 +46,7 @@ import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; + import org.modelmapper.ModelMapper; @Service @@ -86,8 +88,11 @@ public class DiseaseControlServiceImpl implements DiseaseControlService { @Autowired private JwtUtil jwtUtil; + @Autowired + private IncentiveLogicService incentiveLogicService; + - private final Logger logger = LoggerFactory.getLogger(CoupleController.class); + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @Override public String saveMalaria(MalariaDTO diseaseControlDTO) { @@ -109,7 +114,7 @@ public String saveMalaria(MalariaDTO diseaseControlDTO) { @Override public String saveKalaAzar(KalaAzarDTO diseaseControlDTO) { - logger.info("Save request: "+diseaseControlDTO.toString()); + logger.info("Save request: " + diseaseControlDTO.toString()); for (DiseaseKalaAzarDTO diseaseControlData : diseaseControlDTO.getKalaAzarLists()) { if (diseaseKalaAzarRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { return updateKalaAzarDisease(diseaseControlData); @@ -275,7 +280,7 @@ private String updateFilaria(DiseaseFilariasisDTO diseaseControlData) { @Override - public String saveLeprosy(LeprosyDTO diseaseControlDTO) { + public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { for (DiseaseLeprosyDTO diseaseControlData : diseaseControlDTO.getLeprosyLists()) { if (diseaseLeprosyRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { return updateLeprosyData(diseaseControlData); @@ -283,7 +288,15 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { if (diseaseControlDTO.getUserId() != null) { diseaseControlData.setUserId(diseaseControlDTO.getUserId()); } - diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); + ScreeningLeprosy screeningLeprosy = diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); + if (screeningLeprosy != null) { + if (screeningLeprosy.getIsConfirmed()) { + if (screeningLeprosy.getTypeOfLeprosy().toLowerCase().equals("PB (Paucibacillary)")) { + incentiveLogicService.incentiveForLeprosyConfirmed(screeningLeprosy.getBenId(), screeningLeprosy.getTreatmentStartDate(), screeningLeprosy.getTreatmentEndDate(), token); + } + } + } + return "Data add successfully"; } @@ -356,10 +369,10 @@ private String updateLeprosyFollowUpData(LeprosyFollowUpDTO data, LeprosyFollowU public String saveLeprosyFollowUp(LeprosyFollowUpDTO dto) { if (dto == null) return "Invalid data"; - LeprosyFollowUp entity = saveLeprosyFollowUpData(dto); - leprosyFollowUpRepository.save(entity); - return "Follow-up data added successfully"; - + LeprosyFollowUp entity = saveLeprosyFollowUpData(dto); + leprosyFollowUpRepository.save(entity); + return "Follow-up data added successfully"; + } @Override @@ -609,7 +622,7 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { private ScreeningKalaAzar saveKalaAzarDisease(DiseaseKalaAzarDTO dto) { - logger.info("KalaAzarRequest: "+dto); + logger.info("KalaAzarRequest: " + dto); ScreeningKalaAzar entity = new ScreeningKalaAzar(); entity.setBenId(dto.getBenId()); @@ -948,12 +961,10 @@ public List saveMosquitoMobilizationNet(List mos }).collect(Collectors.toList()); - // ✅ Save all List savedEntities = mosquitoNetRepository.saveAll(entityList); - // ✅ Entity → DTO return return savedEntities.stream().map(entity -> { @@ -1001,15 +1012,13 @@ public List getAllMosquitoMobilizationNet(Integer userId) { mosquitoNetListDTO.setIs_net_distributed(entity.getIsNetDistributed()); mosquitoNetListDTO.setVisit_date(entity.getVisitDate().format(formatter)); - dto.setFields(mosquitoNetListDTO); + dto.setFields(mosquitoNetListDTO); return dto; }).collect(Collectors.toList()); } - - private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { IncentiveActivity diseaseScreeningActivity; if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed Case")) { @@ -1060,10 +1069,9 @@ record = new IncentiveActivityRecord(); } - @Override public List saveChronicDiseaseVisit( - List requestList,String token) throws IEMRException { + List requestList, String token) throws IEMRException { List responseList = new ArrayList<>(); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java new file mode 100644 index 000000000..08b7e404f --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -0,0 +1,115 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +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.service.IncentiveLogicService; +import com.iemr.flw.service.UserService; +import com.iemr.flw.utils.JwtUtil; +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.util.Date; + +@Service +public class IncentiveLogicImpl implements IncentiveLogicService { + + private static final Logger logger = LoggerFactory.getLogger(IncentiveLogicImpl.class); + + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserService userService; + + @Override + public void incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token) { + try { + Integer stateCode = userService.getUserDetail(jwtUtil.extractUserId(token)).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", jwtUtil.extractUserId(token)); + return; + } + + String activityName = "NLEP_PB_TREATMENT"; + + if (stateCode.equals(StateCode.AM.getStateCode())) { + processIncentive(activityName, GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, treatmentStartDate, treatmentEndDate, token); + } + if (stateCode.equals(StateCode.CG.getStateCode())) { + processIncentive(activityName, GroupName.ACTIVITY.getDisplayName(), + benId, treatmentStartDate, treatmentEndDate, token); + } + + + } catch (Exception e) { + logger.error("Check Leprosy Incentive Exception: ", e); + } + } + + private void processIncentive(String activityName, String groupName, Long benId, + Date startDate, Date endDate, String token) { + try { + IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, groupName); + + if (activity == null) { + logger.info("No IncentiveActivity found for name: {} and group: {}", activityName, groupName); + return; + } + + saveIncentive(activity, benId, startDate, endDate, token); + + } catch (Exception e) { + logger.error("Process Incentive Exception: ", e); + } + } + + private void saveIncentive(IncentiveActivity activity, Long benId, Date startDate, Date endDate, String token) { + try { + Timestamp startTimestamp = new Timestamp(startDate.getTime()); + Timestamp endTimestamp = new Timestamp(endDate.getTime()); + String username = jwtUtil.extractUsername(token); + + IncentiveActivityRecord record = incentiveRecordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), startTimestamp, benId); + + if (record != null) { + logger.info("Incentive already exists for benId: {}, activityId: {}", benId, activity.getId()); + return; + } + + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(startTimestamp); + record.setUpdatedDate(startTimestamp); + record.setStartDate(startTimestamp); + record.setEndDate(endTimestamp); + record.setCreatedBy(username); + record.setUpdatedBy(username); + record.setBenId(benId); + record.setAshaId(jwtUtil.extractUserId(token)); + record.setName(activity.getName()); + record.setAmount(Long.valueOf(activity.getRate())); + + incentiveRecordRepo.save(record); + logger.info("Leprosy Incentive saved successfully for benId: {}", benId); + + } catch (Exception e) { + logger.error("Save Leprosy Incentive Exception: ", e); + } + } +} From e4af5f98b2a4c2bdbd39e32c6d28bcf3ecedfdd0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Feb 2026 13:10:58 +0530 Subject: [PATCH 108/450] fix code rabit comment --- .../flw/service/IncentiveLogicService.java | 4 +- .../impl/DiseaseControlServiceImpl.java | 17 +++- .../flw/service/impl/IncentiveLogicImpl.java | 87 ++++++++++++++----- .../impl/MaternalHealthServiceImpl.java | 2 + 4 files changed, 87 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 3c48c1cf7..ec3d86b8f 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -1,10 +1,10 @@ package com.iemr.flw.service; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import org.springframework.stereotype.Service; import java.util.Date; -@Service public interface IncentiveLogicService { - public void incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token); + public IncentiveActivityRecord incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index f5d3ff736..7a22fc8f0 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -35,6 +35,7 @@ import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.exception.IEMRException; +import jakarta.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -280,6 +281,7 @@ private String updateFilaria(DiseaseFilariasisDTO diseaseControlData) { @Override + @Transactional public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { for (DiseaseLeprosyDTO diseaseControlData : diseaseControlDTO.getLeprosyLists()) { if (diseaseLeprosyRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { @@ -292,7 +294,20 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { if (screeningLeprosy != null) { if (screeningLeprosy.getIsConfirmed()) { if (screeningLeprosy.getTypeOfLeprosy().toLowerCase().equals("PB (Paucibacillary)")) { - incentiveLogicService.incentiveForLeprosyConfirmed(screeningLeprosy.getBenId(), screeningLeprosy.getTreatmentStartDate(), screeningLeprosy.getTreatmentEndDate(), token); + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + token); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } } } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 08b7e404f..7ab0367ed 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -35,64 +35,106 @@ public class IncentiveLogicImpl implements IncentiveLogicService { private UserService userService; @Override - public void incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token) { + public IncentiveActivityRecord incentiveForLeprosyConfirmed( + Long benId, + Date treatmentStartDate, + Date treatmentEndDate, + String token) { + try { - Integer stateCode = userService.getUserDetail(jwtUtil.extractUserId(token)).getStateId(); + Integer userId = jwtUtil.extractUserId(token); + Integer stateCode = userService.getUserDetail(userId).getStateId(); if (stateCode == null) { - logger.warn("State code is null for user: {}", jwtUtil.extractUserId(token)); - return; + logger.warn("State code is null for user: {}", userId); + return null; } String activityName = "NLEP_PB_TREATMENT"; if (stateCode.equals(StateCode.AM.getStateCode())) { - processIncentive(activityName, GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), - benId, treatmentStartDate, treatmentEndDate, token); + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + token); } + if (stateCode.equals(StateCode.CG.getStateCode())) { - processIncentive(activityName, GroupName.ACTIVITY.getDisplayName(), - benId, treatmentStartDate, treatmentEndDate, token); + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + token); } + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; } catch (Exception e) { logger.error("Check Leprosy Incentive Exception: ", e); + return null; } } - private void processIncentive(String activityName, String groupName, Long benId, + + private IncentiveActivityRecord processIncentive(String activityName, String groupName, Long benId, Date startDate, Date endDate, String token) { try { IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, groupName); if (activity == null) { logger.info("No IncentiveActivity found for name: {} and group: {}", activityName, groupName); - return; + return null ; } - saveIncentive(activity, benId, startDate, endDate, token); + return saveIncentive(activity, benId, startDate, endDate, token); } catch (Exception e) { logger.error("Process Incentive Exception: ", e); + return null; + } } - private void saveIncentive(IncentiveActivity activity, Long benId, Date startDate, Date endDate, String token) { + private IncentiveActivityRecord saveIncentive( + IncentiveActivity activity, + Long benId, + Date startDate, + Date endDate, + String token) { + try { + + if (activity == null || benId == null || startDate == null || endDate == null) { + logger.warn("Invalid input for saving incentive"); + return null; + } + Timestamp startTimestamp = new Timestamp(startDate.getTime()); Timestamp endTimestamp = new Timestamp(endDate.getTime()); + + Integer userId = jwtUtil.extractUserId(token); String username = jwtUtil.extractUsername(token); - IncentiveActivityRecord record = incentiveRecordRepo - .findRecordByActivityIdCreatedDateBenId(activity.getId(), startTimestamp, benId); + // 🔍 duplicate check + IncentiveActivityRecord existing = incentiveRecordRepo + .findRecordByActivityIdCreatedDateBenId( + activity.getId(), startTimestamp, benId); - if (record != null) { - logger.info("Incentive already exists for benId: {}, activityId: {}", benId, activity.getId()); - return; + if (existing != null) { + logger.info("Incentive already exists for benId: {}, activityId: {}", + benId, activity.getId()); + return existing; } - record = new IncentiveActivityRecord(); + // 🆕 create record + IncentiveActivityRecord record = new IncentiveActivityRecord(); record.setActivityId(activity.getId()); record.setCreatedDate(startTimestamp); record.setUpdatedDate(startTimestamp); @@ -101,15 +143,20 @@ record = new IncentiveActivityRecord(); record.setCreatedBy(username); record.setUpdatedBy(username); record.setBenId(benId); - record.setAshaId(jwtUtil.extractUserId(token)); + record.setAshaId(userId); record.setName(activity.getName()); record.setAmount(Long.valueOf(activity.getRate())); - incentiveRecordRepo.save(record); + record = incentiveRecordRepo.save(record); + logger.info("Leprosy Incentive saved successfully for benId: {}", benId); + return record; + } catch (Exception e) { logger.error("Save Leprosy Incentive Exception: ", e); + return null; } } + } 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 8914941f1..b7e818c86 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -7,6 +7,7 @@ import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.IncentiveService; import com.iemr.flw.service.MaternalHealthService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.exception.IEMRException; @@ -440,6 +441,7 @@ public String saveANCVisitQuestions(List dtos, String aut } ancCounsellingCareRepo.saveAll(entities); + return "ANC Counselling & Care data saved successfully"; } From 22c538e0c67f29186559cb06c538e987a5a0d14d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Feb 2026 13:14:13 +0530 Subject: [PATCH 109/450] fix code rabit comment --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 7a22fc8f0..ca2ad1f78 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -293,7 +293,7 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { ScreeningLeprosy screeningLeprosy = diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); if (screeningLeprosy != null) { if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().toLowerCase().equals("PB (Paucibacillary)")) { + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyConfirmed( screeningLeprosy.getBenId(), From 249b22befa05bb4cba0640ee07ee79540643f6ec Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Feb 2026 15:32:30 +0530 Subject: [PATCH 110/450] fix code rabit comment --- .../controller/DiseaseControlController.java | 4 +- .../flw/service/DiseaseControlService.java | 2 +- .../flw/service/IncentiveLogicService.java | 7 +- .../impl/DiseaseControlServiceImpl.java | 39 +++++- .../flw/service/impl/IncentiveLogicImpl.java | 113 ++++++++++++++++-- .../impl/MaternalHealthServiceImpl.java | 5 + 6 files changed, 151 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 5ca4db8d3..e89a53067 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -142,13 +142,13 @@ public ResponseEntity> saveFilaria(@RequestBody FilariaDTO f } @RequestMapping(value = "leprosy/saveAll", method = RequestMethod.POST, consumes = "application/json", produces = "application/json",headers = "Authorization") - public ResponseEntity> saveLeprosy(@RequestBody LeprosyDTO leprosyDTO,@RequestHeader(value = "JwtToken") String token) { + 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,token)); + response.put("data", diseaseControlService.saveLeprosy(leprosyDTO)); }else { response.put("message", "Invalid request"); response.put("statusCode", 400); diff --git a/src/main/java/com/iemr/flw/service/DiseaseControlService.java b/src/main/java/com/iemr/flw/service/DiseaseControlService.java index db20d712f..65e315dce 100644 --- a/src/main/java/com/iemr/flw/service/DiseaseControlService.java +++ b/src/main/java/com/iemr/flw/service/DiseaseControlService.java @@ -35,7 +35,7 @@ public interface DiseaseControlService { public String saveKalaAzar(KalaAzarDTO kalaAzarDTO); public String saveAES(AesJeDTO aesJeDTO); public String saveFilaria(FilariaDTO filariaDTO); - public String saveLeprosy(LeprosyDTO leprosyDTO, String token); + public String saveLeprosy(LeprosyDTO leprosyDTO); public Object getAllScreeningData(GetDiseaseRequestHandler getDiseaseRequestHandler); public List saveMosquitoMobilizationNet(List mosquitoNetDTOList); diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index ec3d86b8f..a0aa5ec1e 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -6,5 +6,10 @@ import java.util.Date; public interface IncentiveLogicService { - public IncentiveActivityRecord incentiveForLeprosyConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, String token); + public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + public IncentiveActivityRecord incentiveForIdentificationLeprosy(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + public IncentiveActivityRecord incentiveAssistingANCVisits(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + + } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index ca2ad1f78..88932659c 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -282,7 +282,7 @@ private String updateFilaria(DiseaseFilariasisDTO diseaseControlData) { @Override @Transactional - public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { + public String saveLeprosy(LeprosyDTO diseaseControlDTO) { for (DiseaseLeprosyDTO diseaseControlData : diseaseControlDTO.getLeprosyLists()) { if (diseaseLeprosyRepository.findByBenId(diseaseControlData.getBenId()).isPresent()) { return updateLeprosyData(diseaseControlData); @@ -295,11 +295,44 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO, String token) { if (screeningLeprosy.getIsConfirmed()) { if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyConfirmed( + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), screeningLeprosy.getTreatmentStartDate(), screeningLeprosy.getTreatmentEndDate(), - token); + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + + } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + + } + + if (screeningLeprosy.getIsConfirmed()) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForIdentificationLeprosy( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 7ab0367ed..1257b8a5e 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -6,6 +6,7 @@ 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.service.IncentiveLogicService; import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; @@ -34,15 +35,64 @@ public class IncentiveLogicImpl implements IncentiveLogicService { @Autowired private UserService userService; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + + @Override + public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed( + Long benId, + Date treatmentStartDate, + Date treatmentEndDate, + Integer userId) { + + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NLEP_PB_TREATMENT"; + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Leprosy Incentive Exception: ", e); + return null; + } + } + @Override - public IncentiveActivityRecord incentiveForLeprosyConfirmed( + public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( Long benId, Date treatmentStartDate, Date treatmentEndDate, - String token) { + Integer userId) { try { - Integer userId = jwtUtil.extractUserId(token); Integer stateCode = userService.getUserDetail(userId).getStateId(); if (stateCode == null) { @@ -59,7 +109,7 @@ public IncentiveActivityRecord incentiveForLeprosyConfirmed( benId, treatmentStartDate, treatmentEndDate, - token); + userId); } if (stateCode.equals(StateCode.CG.getStateCode())) { @@ -69,7 +119,7 @@ public IncentiveActivityRecord incentiveForLeprosyConfirmed( benId, treatmentStartDate, treatmentEndDate, - token); + userId); } // state not supported @@ -82,9 +132,50 @@ public IncentiveActivityRecord incentiveForLeprosyConfirmed( } } + @Override + public IncentiveActivityRecord incentiveForIdentificationLeprosy(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NLEP_CASE_DETECTION"; + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Leprosy Incentive Exception: ", e); + return null; + } + } private IncentiveActivityRecord processIncentive(String activityName, String groupName, Long benId, - Date startDate, Date endDate, String token) { + Date startDate, Date endDate, Integer userId) { try { IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, groupName); @@ -93,7 +184,7 @@ private IncentiveActivityRecord processIncentive(String activityName, String gro return null ; } - return saveIncentive(activity, benId, startDate, endDate, token); + return saveIncentive(activity, benId, startDate, endDate, userId); } catch (Exception e) { logger.error("Process Incentive Exception: ", e); @@ -107,7 +198,7 @@ private IncentiveActivityRecord saveIncentive( Long benId, Date startDate, Date endDate, - String token) { + Integer userId) { try { @@ -119,8 +210,6 @@ private IncentiveActivityRecord saveIncentive( Timestamp startTimestamp = new Timestamp(startDate.getTime()); Timestamp endTimestamp = new Timestamp(endDate.getTime()); - Integer userId = jwtUtil.extractUserId(token); - String username = jwtUtil.extractUsername(token); // 🔍 duplicate check IncentiveActivityRecord existing = incentiveRecordRepo @@ -140,8 +229,8 @@ private IncentiveActivityRecord saveIncentive( record.setUpdatedDate(startTimestamp); record.setStartDate(startTimestamp); record.setEndDate(endTimestamp); - record.setCreatedBy(username); - record.setUpdatedBy(username); + record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); + record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); record.setBenId(benId); record.setAshaId(userId); record.setName(activity.getName()); 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 b7e818c86..52ff5e1d1 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -7,6 +7,7 @@ import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.IncentiveService; import com.iemr.flw.service.MaternalHealthService; import com.iemr.flw.utils.JwtUtil; @@ -22,6 +23,7 @@ import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalTime; +import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.*; @@ -68,6 +70,9 @@ public class MaternalHealthServiceImpl implements MaternalHealthService { @Autowired private JwtUtil jwtUtil; + @Autowired + private IncentiveLogicService incentiveLogicService; + ObjectMapper mapper = new ObjectMapper(); From d14afc4d473382f0bb644189e881f975eb734293 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Feb 2026 15:48:29 +0530 Subject: [PATCH 111/450] fix code rabit comment --- src/main/java/com/iemr/flw/service/IncentiveLogicService.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index a0aa5ec1e..640018638 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -9,7 +9,6 @@ public interface IncentiveLogicService { public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); public IncentiveActivityRecord incentiveForIdentificationLeprosy(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); - public IncentiveActivityRecord incentiveAssistingANCVisits(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); } From e9ee718951d8ceef5946edcf42bb9c173eea9f48 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 9 Feb 2026 15:57:26 +0530 Subject: [PATCH 112/450] Changes incentive loigc for CG in VillageLevel --- .../flw/service/IncentiveLogicService.java | 4 + .../flw/service/impl/IncentiveLogicImpl.java | 104 +++++++++++++++++- .../impl/VillageLevelFormServiceImpl.java | 27 ++++- 3 files changed, 128 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 640018638..1b3529b1e 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -10,5 +10,9 @@ public interface IncentiveLogicService { public IncentiveActivityRecord incentiveForIdentificationLeprosy(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + public IncentiveActivityRecord incentiveForVhndMeeting(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + + public IncentiveActivityRecord incentiveForClusterMeeting(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + public IncentiveActivityRecord incentiveForAttendingVhsnc(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 1257b8a5e..c564fab72 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -80,7 +80,7 @@ public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed( return null; } catch (Exception e) { - logger.error("Check Leprosy Incentive Exception: ", e); + logger.error("Check NLEP_PB_TREATMENT Incentive Exception: ", e); return null; } } @@ -127,7 +127,103 @@ public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( return null; } catch (Exception e) { - logger.error("Check Leprosy Incentive Exception: ", e); + logger.error("Check NLEP_PB_TREATMENT Incentive Exception: ", e); + return null; + } + } + + @Override + public IncentiveActivityRecord incentiveForVhndMeeting(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "VHND_PARTICIPATION"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check VHND_PARTICIPATION Incentive Exception: ", e); + return null; + } + } + + @Override + public IncentiveActivityRecord incentiveForClusterMeeting(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "CLUSTER_MEETING"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check CLUSTER_MEETING Incentive Exception: ", e); + return null; + } + } + + @Override + public IncentiveActivityRecord incentiveForAttendingVhsnc(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "VHSNC_MEETING"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check VHSNC_MEETING Incentive Exception: ", e); return null; } } @@ -238,12 +334,12 @@ private IncentiveActivityRecord saveIncentive( record = incentiveRecordRepo.save(record); - logger.info("Leprosy Incentive saved successfully for benId: {}", benId); + logger.info("Incentive saved successfully for benId: {}", benId); return record; } catch (Exception e) { - logger.error("Save Leprosy Incentive Exception: ", e); + logger.error("Error Incentive Exception: ", e); return null; } } diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index c64654d33..579b84c92 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -29,6 +29,7 @@ import com.iemr.flw.dto.iemr.*; import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.VillageLevelFormService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,8 +38,10 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Collections; +import java.util.Date; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -70,6 +73,9 @@ public class VillageLevelFormServiceImpl implements VillageLevelFormService { @Autowired private AHDFormRepo ahdFormRepo; + @Autowired + private IncentiveLogicService incentiveLogicService; + @Override public Boolean saveForm(VhndDto dto) { @@ -144,7 +150,12 @@ private Boolean saveVhncFormData(VhncFormDTO vhncFormDTO, Integer userID) { vhncForm.setFormType("VHNC"); vhncFormRepo.save(vhncForm); - checkAndAddIncentives(vhncForm.getVhncDate(), Math.toIntExact(vhncForm.getUserId()), "VHSNC_MEETING", vhncForm.getCreatedBy()); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + LocalDate localDate = LocalDate.parse(vhncForm.getVhncDate(), formatter); + + Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); + incentiveLogicService.incentiveForAttendingVhsnc(0L,date,date,Math.toIntExact(vhncForm.getUserId())); return true; } @@ -164,7 +175,12 @@ private Boolean savePhcForm(PhcReviewMeetingFormDTO dto, Integer userID) { phcReviewForm.setImage2(dto.getImage2()); phcReviewForm.setFormType("PHC"); phcReviewFormRepo.save(phcReviewForm); - checkAndAddIncentives(phcReviewForm.getPhcReviewDate(), Math.toIntExact(phcReviewForm.getUserId()), "CLUSTER_MEETING", phcReviewForm.getCreatedBy()); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + LocalDate localDate = LocalDate.parse(phcReviewForm.getPhcReviewDate(), formatter); + + Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); + incentiveLogicService.incentiveForClusterMeeting(0L,date,date,Math.toIntExact(phcReviewForm.getUserId())); return true; } @@ -226,7 +242,12 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { vhndForm.setFamilyPlanningHealthcare(vhndFormDTO.getFamilyPlanningHealthcare()); vhndForm.setFormType("VHND"); vhndRepo.save(vhndForm); - checkAndAddIncentives(vhndForm.getVhndDate(), vhndForm.getUserId(), "VHND_PARTICIPATION", vhndForm.getCreatedBy()); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + LocalDate localDate = LocalDate.parse(vhndForm.getVhndDate(), formatter); + + Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); + incentiveLogicService.incentiveForVhndMeeting(0L,date,date,vhndForm.getUserId()); return true; From 56d1bd2433b940fff6348a62bed8298128caf9a9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Feb 2026 15:45:42 +0530 Subject: [PATCH 113/450] incentive upload files --- .../java/com/iemr/flw/controller/IncentiveController.java | 4 ++-- src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index c76d26ae0..082c1cf05 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -103,8 +103,8 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request return response.toString(); } - @RequestMapping(value = {"/update"}, method = RequestMethod.POST) - public String updateIncentive(@RequestBody PendingActivityDTO requestDTO) { + @RequestMapping(value = {"/update"}, method = RequestMethod.POST, consumes = {"multipart/form-data"}) + public String updateIncentive(@ModelAttribute PendingActivityDTO requestDTO) { OutputResponse response = new OutputResponse(); try { diff --git a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java index 4d8dbd99e..df15d41d5 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -9,6 +9,6 @@ public class PendingActivityDTO { private Long id; private Integer userId; - private List Images; + private List images; private String moduleName; } From 79ddfa2d1ce9f7595ed4a30864d99d69eff4c9b9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Feb 2026 17:15:31 +0530 Subject: [PATCH 114/450] incentive upload files --- .../java/com/iemr/flw/controller/IncentiveController.java | 6 +++--- src/main/java/com/iemr/flw/service/MaaMeetingService.java | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index 082c1cf05..ba60dffb3 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -116,12 +116,12 @@ public String updateIncentive(@ModelAttribute PendingActivityDTO requestDTO) { 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 high risk assessment data : " + e); - response.setError(5000, "Error in high risk assessment data : " + e); + response.setError(500, "Error in high risk assessment data : " + e); } return response.toString(); diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index cb23b7b9c..d3319821c 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -217,7 +217,7 @@ record = new IncentiveActivityRecord(); record.setIsEligible(true); } else { record.setIsEligible(false); - // updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); + updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); } record.setAmount(Long.valueOf(incentiveActivity.getRate())); From dc864992e7766643da7e9664b098373143a0af25 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Feb 2026 17:32:53 +0530 Subject: [PATCH 115/450] incentive upload files --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 + 1 file changed, 1 insertion(+) 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 5580e8964..3dfd7278a 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -205,6 +205,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); + maaMeetingRequestDTO.setId(pendingActivityDTO.getId()); maaMeetingService.updateMeeting(maaMeetingRequestDTO); }catch (Exception e){ From 72612315a233b673660b56e444cd722cc5ad0afc Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Feb 2026 17:38:50 +0530 Subject: [PATCH 116/450] add record id --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 3dfd7278a..08749cddb 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -205,7 +205,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - maaMeetingRequestDTO.setId(pendingActivityDTO.getId()); + maaMeetingRequestDTO.setId(existingIncentivePendingActivity.getRecordId()); maaMeetingService.updateMeeting(maaMeetingRequestDTO); }catch (Exception e){ From c7f27583c51b6a7426be16132c25929c04ae0adb Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Feb 2026 18:00:40 +0530 Subject: [PATCH 117/450] add record id --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 08749cddb..37d538649 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -205,7 +205,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - maaMeetingRequestDTO.setId(existingIncentivePendingActivity.getRecordId()); + maaMeetingRequestDTO.setId(1L); maaMeetingService.updateMeeting(maaMeetingRequestDTO); }catch (Exception e){ From 917f8bc878313aecc19cebce0efe94f7d8521088 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 12 Feb 2026 12:57:30 +0530 Subject: [PATCH 118/450] add record id --- .../flw/repo/iemr/IncentiveRecordRepo.java | 2 + .../iemr/flw/service/MaaMeetingService.java | 53 ++++++++++++++----- .../service/impl/IncentiveServiceImpl.java | 4 +- 3 files changed, 43 insertions(+), 16 deletions(-) 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 6b8db13e3..2f6dcbe37 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,8 @@ public interface IncentiveRecordRepo extends JpaRepository 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)); + } + if (existingMeeting.getMeetingImagesJson() != null) { - checkAndUpdateIncentive(existingMeeting); + checkAndUpdateIncentive(incentiveRecordId); } return repository.save(existingMeeting); @@ -172,17 +206,8 @@ private void updatePendingActivity(Integer userId, Long recordId, Long activityI } - 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 checkAndUpdateIncentive(Long incentiveId) { + updateIncentive(incentiveId); } private void checkAndAddIncentive(MaaMeeting meeting) { @@ -226,9 +251,9 @@ record = new IncentiveActivityRecord(); } - private void updateIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { + private void updateIncentive(Long id ) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); + .findRecordById(id); if (record != null) { record = new IncentiveActivityRecord(); 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 37d538649..c18d7e50c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -205,8 +205,8 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - maaMeetingRequestDTO.setId(1L); - maaMeetingService.updateMeeting(maaMeetingRequestDTO); + maaMeetingRequestDTO.setId(existingIncentivePendingActivity.getRecordId()); + maaMeetingService.updateMeetingFromFileUpload(maaMeetingRequestDTO,pendingActivityDTO.getId()); }catch (Exception e){ return e.getMessage(); From 4db1fb2a0e667fe01deca76ba3124e020d7ee0af Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 12 Feb 2026 13:08:25 +0530 Subject: [PATCH 119/450] fix method name --- .../com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 3 ++- .../java/com/iemr/flw/service/MaaMeetingService.java | 12 ++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) 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 2f6dcbe37..0c2dc21b5 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -9,6 +9,7 @@ import java.sql.Timestamp; import java.util.List; +import java.util.Optional; @Repository public interface IncentiveRecordRepo extends JpaRepository { @@ -16,7 +17,7 @@ public interface IncentiveRecordRepo extends JpaRepository findById(Long id); @Query("select record from IncentiveActivityRecord record where record.activityId = :id and record.createdDate = :createdDate and record.benId = :benId and record.ashaId = :ashaId") diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index cd7341109..87010d90d 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -251,17 +251,17 @@ record = new IncentiveActivityRecord(); } - private void updateIncentive(Long id ) { - IncentiveActivityRecord record = recordRepo - .findRecordById(id); + private void updateIncentive(Long id) { - if (record != null) { - record = new IncentiveActivityRecord(); + Optional optionalRecord = recordRepo.findById(id); + + if (optionalRecord.isPresent()) { + IncentiveActivityRecord record = optionalRecord.get(); record.setIsEligible(true); recordRepo.save(record); } - } + } From adf16a4804c6365f0f1eb7539a8c7b0d5773dfb7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 12 Feb 2026 13:17:47 +0530 Subject: [PATCH 120/450] make changes in response --- .../com/iemr/flw/service/MaaMeetingService.java | 16 ++++++++++------ .../flw/service/impl/IncentiveServiceImpl.java | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 87010d90d..bde156a6b 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -111,7 +111,7 @@ public MaaMeeting updateMeeting(MaaMeetingRequestDTO req) throws JsonProcessingE return repository.save(existingMeeting); } - public MaaMeeting updateMeetingFromFileUpload(MaaMeetingRequestDTO req,Long incentiveRecordId) throws JsonProcessingException { + public String updateMeetingFromFileUpload(MaaMeetingRequestDTO req,Long incentiveRecordId) throws JsonProcessingException { MaaMeeting existingMeeting = repository.findById(req.getId()) .orElseThrow(() -> new EntityNotFoundException("Meeting not found: " + req.getId())); @@ -140,12 +140,14 @@ public MaaMeeting updateMeetingFromFileUpload(MaaMeetingRequestDTO req,Long ince .collect(Collectors.toList()); existingMeeting.setMeetingImagesJson(objectMapper.writeValueAsString(base64Images)); } + repository.save(existingMeeting); if (existingMeeting.getMeetingImagesJson() != null) { - checkAndUpdateIncentive(incentiveRecordId); + return checkAndUpdateIncentive(incentiveRecordId); } - return repository.save(existingMeeting); + + return "Fail to update meeting image"; } @@ -206,8 +208,8 @@ private void updatePendingActivity(Integer userId, Long recordId, Long activityI } - private void checkAndUpdateIncentive(Long incentiveId) { - updateIncentive(incentiveId); + private String checkAndUpdateIncentive(Long incentiveId) { + return updateIncentive(incentiveId); } private void checkAndAddIncentive(MaaMeeting meeting) { @@ -251,7 +253,7 @@ record = new IncentiveActivityRecord(); } - private void updateIncentive(Long id) { + private String updateIncentive(Long id) { Optional optionalRecord = recordRepo.findById(id); @@ -259,7 +261,9 @@ private void updateIncentive(Long id) { IncentiveActivityRecord record = optionalRecord.get(); record.setIsEligible(true); recordRepo.save(record); + return "Incentive update successfully"; } + return "Fail to update Incentive"; } 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 c18d7e50c..8d6446671 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -206,7 +206,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); maaMeetingRequestDTO.setId(existingIncentivePendingActivity.getRecordId()); - maaMeetingService.updateMeetingFromFileUpload(maaMeetingRequestDTO,pendingActivityDTO.getId()); + return maaMeetingService.updateMeetingFromFileUpload(maaMeetingRequestDTO,pendingActivityDTO.getId()); }catch (Exception e){ return e.getMessage(); From d1f81401d6f3aebc076164253a005d42a18e43ba Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 15:30:13 +0530 Subject: [PATCH 121/450] implement check on pending doc for incentive review --- .../domain/iemr/IncentivePendingActivity.java | 8 +- .../iemr/flw/dto/iemr/PendingActivityDTO.java | 1 + .../IncentivePendingActivityRepository.java | 1 + .../iemr/flw/service/MaaMeetingService.java | 11 ++- .../service/impl/IncentiveServiceImpl.java | 96 ++++++++++--------- 5 files changed, 61 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java b/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java index 870a48f53..3f35dc599 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentivePendingActivity.java @@ -24,10 +24,10 @@ public class IncentivePendingActivity { @Column(name = "record_id", nullable = false) private Long recordId; - - @Column(name = "module_name", nullable = false, length = 100) - private String moduleName; - + + @Column(name = "m_incentive_id") + private Long mincentiveId; + @Column(name = "user_id", nullable = false) private Integer userId; diff --git a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java index 4d8dbd99e..78a20516a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -11,4 +11,5 @@ public class PendingActivityDTO { private Integer userId; private List Images; private String moduleName; + private String name; } diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java index 9bac8d219..89b2bed5c 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java @@ -15,4 +15,5 @@ public interface IncentivePendingActivityRepository extends JpaRepository findByMincentiveIdAndActivityId(Long mIncentiveId,Long activityId); } diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index cb23b7b9c..5813bbffe 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -160,12 +160,12 @@ public List getAllMeetings(GetBenRequestHandler getBenReq }).collect(Collectors.toList()); } - private void updatePendingActivity(Integer userId, Long recordId, Long activityId, String moduleName) { + private void updatePendingActivity(Integer userId, Long recordId, Long activityId, Long mIncentiveId) { IncentivePendingActivity incentivePendingActivity = new IncentivePendingActivity(); incentivePendingActivity.setActivityId(activityId); incentivePendingActivity.setRecordId(recordId); incentivePendingActivity.setUserId(userId); - incentivePendingActivity.setModuleName(moduleName); + incentivePendingActivity.setMincentiveId(mIncentiveId); if (incentivePendingActivity != null) { incentivePendingActivityRepository.save(incentivePendingActivity); } @@ -186,8 +186,9 @@ private void checkAndUpdateIncentive(MaaMeeting 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()); + String activityName = "MAA_QUARTERLY_MEETING"; + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, GroupName.ACTIVITY.getDisplayName()); if (incentiveActivityAM != null) { addIncentive(incentiveActivityAM, meeting); } @@ -217,7 +218,7 @@ record = new IncentiveActivityRecord(); record.setIsEligible(true); } else { record.setIsEligible(false); - // updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), "MAA_MEETING"); + updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), incentiveActivity.getId()); } record.setAmount(Long.valueOf(incentiveActivity.getRate())); 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 5580e8964..72b4b1bed 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -78,7 +78,7 @@ 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) { } @@ -90,10 +90,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { try { List incs = new ArrayList<>(); - if(incentiveRequestDTO.getState()==StateCode.CG.getStateCode()){ + if (incentiveRequestDTO.getState() == StateCode.CG.getStateCode()) { incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); - }else { + } else { incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> !incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); } @@ -102,40 +102,38 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { // Fetch language mapping IncentiveActivityLangMapping mapping = incentiveActivityLangMappingRepo - .findByIdAndName(inc.getId(),inc.getName()); - + .findByIdAndName(inc.getId(), inc.getName()); if (mapping != null) { dto.setName(mapping.getName()); dto.setGroupName(mapping.getGroup()); - if(Objects.equals(incentiveRequestDTO.getLangCode(), "en")){ + if (Objects.equals(incentiveRequestDTO.getLangCode(), "en")) { dto.setDescription(inc.getDescription()); + } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "as")) { - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "as")){ - - if(mapping.getAssameActivityDescription()!=null){ + if (mapping.getAssameActivityDescription() != null) { dto.setDescription(mapping.getAssameActivityDescription()); - }else { + } else { dto.setDescription(mapping.getDescription()); } - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "hi")){ - if(mapping.getHindiActivityDescription()!=null){ + } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "hi")) { + if (mapping.getHindiActivityDescription() != null) { dto.setDescription(mapping.getHindiActivityDescription()); - }else { + } else { dto.setDescription(mapping.getDescription()); } } - }else { + } else { dto.setGroupName(inc.getGroup()); } @@ -156,30 +154,30 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { - if(request.getVillageID()!= StateCode.CG.getStateCode()){ + if (request.getVillageID() != StateCode.CG.getStateCode()) { checkMonthlyAshaIncentive(request.getAshaId()); } List dtos = new ArrayList<>(); List entities = recordRepo.findRecordsByAsha(request.getAshaId()); - if(request.getVillageID()==StateCode.CG.getStateCode()){ - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),true)!=null).collect(Collectors.toList()); + if (request.getVillageID() == StateCode.CG.getStateCode()) { + entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), true) != null).collect(Collectors.toList()); - }else { - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),false)!=null).collect(Collectors.toList()); + } else { + entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), false) != null).collect(Collectors.toList()); } entities.forEach(entry -> { - if(entry.getName()==null){ - if(entry.getBenId()!=0 && entry.getBenId()>0L){ + if (entry.getName() == null) { + if (entry.getBenId() != 0 && entry.getBenId() > 0L) { Long regId = beneficiaryRepo.getBenRegIdFromBenId(entry.getBenId()); - logger.info("rmnchBeneficiaryDetailsRmnch"+regId); + logger.info("rmnchBeneficiaryDetailsRmnch" + regId); BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(regId)).getBenDetailsId(); RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); - String beneName = rmnchBeneficiaryDetails.getFirstName()+" "+rmnchBeneficiaryDetails.getLastName(); + String beneName = rmnchBeneficiaryDetails.getFirstName() + " " + rmnchBeneficiaryDetails.getLastName(); entry.setName(beneName); - }else{ + } else { entry.setName(""); } @@ -196,47 +194,51 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { @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(); - } + IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup(pendingActivityDTO.getName(), pendingActivityDTO.getModuleName()); + if (incentiveActivity != null) { + Optional incentivePendingActivity = incentivePendingActivityRepository.findByMincentiveIdAndActivityId(pendingActivityDTO.getId(), incentiveActivity.getId()); + if (incentivePendingActivity.isPresent()) { + IncentivePendingActivity existingIncentivePendingActivity = incentivePendingActivity.get(); + if (existingIncentivePendingActivity.getActivityId().equals(pendingActivityDTO.getId())) { + 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; + + + return null; } - private void checkMonthlyAshaIncentive(Integer ashaId){ + private void checkMonthlyAshaIncentive(Integer 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); + if (MOBILEBILLREIMB_ACTIVITY != null) { + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId); } - if(ADDITIONAL_ASHA_INCENTIVE!=null){ - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE,ashaId); + if (ADDITIONAL_ASHA_INCENTIVE != null) { + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId); } - if(ASHA_MONTHLY_ROUTINE!=null){ - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE,ashaId); + if (ASHA_MONTHLY_ROUTINE != null) { + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId); } } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId){ + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId) { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); From fc13d610ff46c4299df2b4e7411b6b15cc60f6f0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 16:01:04 +0530 Subject: [PATCH 122/450] implement check on pending doc for incentive review --- .../iemr/flw/service/MaaMeetingService.java | 68 +++++++++++++------ .../service/impl/IncentiveServiceImpl.java | 27 ++++---- 2 files changed, 60 insertions(+), 35 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 5813bbffe..24b1447e5 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -107,8 +107,42 @@ public MaaMeeting updateMeeting(MaaMeetingRequestDTO req) throws JsonProcessingE } checkAndAddIncentive(existingMeeting); + + return repository.save(existingMeeting); + } + + public MaaMeeting updateMeetingFromFileUpload(MaaMeetingRequestDTO req,Long incentiveRecordId) 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)); + } + if (existingMeeting.getMeetingImagesJson() != null) { - checkAndUpdateIncentive(existingMeeting); + checkAndUpdateIncentive(incentiveRecordId); } return repository.save(existingMeeting); @@ -172,23 +206,13 @@ private void updatePendingActivity(Integer userId, Long recordId, Long activityI } - 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 checkAndUpdateIncentive(Long incentiveId) { + updateIncentive(incentiveId); } private void checkAndAddIncentive(MaaMeeting meeting) { - String activityName = "MAA_QUARTERLY_MEETING"; - IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, GroupName.CHILD_HEALTH.getDisplayName()); - IncentiveActivity incentiveActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup(activityName, GroupName.ACTIVITY.getDisplayName()); + 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); } @@ -218,7 +242,7 @@ record = new IncentiveActivityRecord(); record.setIsEligible(true); } else { record.setIsEligible(false); - updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(), incentiveActivity.getId()); + updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(),incentiveActivity.getId()); } record.setAmount(Long.valueOf(incentiveActivity.getRate())); @@ -227,17 +251,17 @@ record = new IncentiveActivityRecord(); } - private void updateIncentive(IncentiveActivity incentiveActivity, MaaMeeting meeting) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), Timestamp.valueOf(meeting.getMeetingDate().atStartOfDay()), 0L, meeting.getAshaId()); + private void updateIncentive(Long id) { - if (record != null) { - record = new IncentiveActivityRecord(); + Optional optionalRecord = recordRepo.findById(id); + + if (optionalRecord.isPresent()) { + IncentiveActivityRecord record = optionalRecord.get(); record.setIsEligible(true); recordRepo.save(record); } - } + } 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 306516cda..ed3cc0b37 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -78,7 +78,7 @@ 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) { } @@ -206,12 +206,13 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - maaMeetingService.updateMeeting(maaMeetingRequestDTO); + maaMeetingService.updateMeetingFromFileUpload(maaMeetingRequestDTO,pendingActivityDTO.getId()); - }catch (Exception e){ - return e.getMessage(); - } + } catch (Exception e) { + return e.getMessage(); + } + } } } } @@ -219,25 +220,25 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } - private void checkMonthlyAshaIncentive(Integer ashaId) { + private void checkMonthlyAshaIncentive(Integer 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); + if(MOBILEBILLREIMB_ACTIVITY!=null){ + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY,ashaId); } - if (ADDITIONAL_ASHA_INCENTIVE != null) { - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId); + if(ADDITIONAL_ASHA_INCENTIVE!=null){ + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE,ashaId); } - if (ASHA_MONTHLY_ROUTINE != null) { - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId); + if(ASHA_MONTHLY_ROUTINE!=null){ + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE,ashaId); } } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId) { + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId){ Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); From d13fe8a13ab67bb16096725121fcd3cb488b25e9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 17:31:47 +0530 Subject: [PATCH 123/450] implement check on pending doc for incentive review --- .../com/iemr/flw/masterEnum/GroupName.java | 3 + .../iemr/flw/masterEnum/IncentiveName.java | 139 ++++++++++++ .../service/impl/ChildCareServiceImpl.java | 198 +++++++++++------- .../service/impl/IncentiveServiceImpl.java | 166 ++++++++++----- 4 files changed, 387 insertions(+), 119 deletions(-) create mode 100644 src/main/java/com/iemr/flw/masterEnum/IncentiveName.java diff --git a/src/main/java/com/iemr/flw/masterEnum/GroupName.java b/src/main/java/com/iemr/flw/masterEnum/GroupName.java index 8d6736eb3..e53733b02 100644 --- a/src/main/java/com/iemr/flw/masterEnum/GroupName.java +++ b/src/main/java/com/iemr/flw/masterEnum/GroupName.java @@ -33,3 +33,6 @@ public String getDisplayName() { } + + + diff --git a/src/main/java/com/iemr/flw/masterEnum/IncentiveName.java b/src/main/java/com/iemr/flw/masterEnum/IncentiveName.java new file mode 100644 index 000000000..052ab011c --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/IncentiveName.java @@ -0,0 +1,139 @@ +package com.iemr.flw.masterEnum; + +public enum IncentiveName { + + // ---------------- CHILD HEALTH ---------------- + HBNC_0_42_DAYS(GroupName.CHILD_HEALTH), + HBYC_QUARTERLY_VISITS(GroupName.CHILD_HEALTH), + SNCU_LBW_FOLLOWUP(GroupName.CHILD_HEALTH), + SAM_REFERRAL_NRC(GroupName.CHILD_HEALTH), + CHILD_DEATH_REPORTING(GroupName.CHILD_HEALTH), + E_HBNC_CACHAR(GroupName.CHILD_HEALTH), + MAA_QUARTERLY_MEETING(GroupName.CHILD_HEALTH), + NATIONAL_DEWORMING_DAY(GroupName.CHILD_HEALTH), + ORS_DISTRIBUTION(GroupName.CHILD_HEALTH), + NATIONAL_IRON_PLUS(GroupName.CHILD_HEALTH), + NIPI_CHILDREN(GroupName.CHILD_HEALTH), + + // ---------------- IMMUNIZATION ---------------- + FULL_IMMUNIZATION_0_1(GroupName.IMMUNIZATION), + COMPLETE_IMMUNIZATION_1_2(GroupName.IMMUNIZATION), + DPT_IMMUNIZATION_5_YEARS(GroupName.IMMUNIZATION), + CHILD_MOBILIZATION_SESSIONS(GroupName.IMMUNIZATION), + + // ---------------- MATERNAL HEALTH ---------------- + ANC_REGISTRATION_1ST_TRIM(GroupName.MATERNAL_HEALTH), + FULL_ANC(GroupName.MATERNAL_HEALTH), + COMPREHENSIVE_ABORTION_CARE(GroupName.MATERNAL_HEALTH), + INST_DELIVERY_HRP(GroupName.MATERNAL_HEALTH), + EPMSMA_INST_DELIVERY(GroupName.MATERNAL_HEALTH), + EPMSMA_HRP_IDENTIFIED(GroupName.MATERNAL_HEALTH), + MATERNAL_DEATH_REPORT(GroupName.MATERNAL_HEALTH), + MH_MISOPROSTOL(GroupName.MATERNAL_HEALTH), + MH_EARLY_REG_BANK(GroupName.MATERNAL_HEALTH), + MH_ANC_3RD_TRIM(GroupName.MATERNAL_HEALTH), + MH_MOTIVATE_INST_DEL(GroupName.MATERNAL_HEALTH), + MH_HR_POSTNATAL(GroupName.MATERNAL_HEALTH), + + // ---------------- JSY ---------------- + JSY_1ST_DEL_ANC_RURAL(GroupName.JSY), + JSY_1ST_DEL_INST_RURAL(GroupName.JSY), + JSY_2ND_DEL_ANC_RURAL(GroupName.JSY), + JSY_2ND_DEL_INST_RURAL(GroupName.JSY), + JSY_3RD_DEL_ANC_RURAL(GroupName.JSY), + JSY_3RD_DEL_INST_RURAL(GroupName.JSY), + JSY_4TH_DEL_ANC_RURAL(GroupName.JSY), + JSY_4TH_DEL_INST_RURAL(GroupName.JSY), + JSY_ANC_URBAN(GroupName.JSY), + JSY_INST_URBAN(GroupName.JSY), + + // ---------------- FAMILY PLANNING ---------------- + FP_ANC_MPA1(GroupName.FAMILY_PLANNING), + FP_ANC_MPA2(GroupName.FAMILY_PLANNING), + FP_ANC_MPA3(GroupName.FAMILY_PLANNING), + FP_ANC_MPA4(GroupName.FAMILY_PLANNING), + FP_ANC_MPA5(GroupName.FAMILY_PLANNING), + FIRST_SECOND_CHILD_GAP(GroupName.FAMILY_PLANNING), + FP_DELAY_2Y(GroupName.FAMILY_PLANNING), + FP_LIMIT_2CHILD(GroupName.FAMILY_PLANNING), + FP_PPIUCD(GroupName.FAMILY_PLANNING), + FP_PAIUCD(GroupName.FAMILY_PLANNING), + FP_CONDOM(GroupName.FAMILY_PLANNING), + FP_ORALPILLS(GroupName.FAMILY_PLANNING), + FP_EC(GroupName.FAMILY_PLANNING), + FP_FEMALE_STER(GroupName.FAMILY_PLANNING), + FP_PPS(GroupName.FAMILY_PLANNING), + FP_MINILAP(GroupName.FAMILY_PLANNING), + FP_MALE_STER(GroupName.FAMILY_PLANNING), + FP_EC_SURVEY(GroupName.FAMILY_PLANNING), + FP_SAAS_BAHU(GroupName.FAMILY_PLANNING), + FP_NP_KIT(GroupName.FAMILY_PLANNING), + + // ---------------- ADOLESCENT HEALTH ---------------- + AH_SANITARY(GroupName.ADOLESCENT_HEALTH), + AH_PEER_ED(GroupName.ADOLESCENT_HEALTH), + AH_MOBILIZE(GroupName.ADOLESCENT_HEALTH), + + // ---------------- ASHA ROUTINE ---------------- + ASHA_MONTHLY_ROUTINE(GroupName.ASHA_MONTHLY_ROUTINE), + + // ---------------- UMBRELLA PROGRAMMES ---------------- + NPCB_GOVT_CATARACT(GroupName.UMBRELLA_PROGRAMMES), + NPCB_PRIVATE_CATARACT(GroupName.UMBRELLA_PROGRAMMES), + DSTB_TREATMENT(GroupName.UMBRELLA_PROGRAMMES), + DRTB_TREATMENT(GroupName.UMBRELLA_PROGRAMMES), + INFORMANT_INCENTIVE(GroupName.UMBRELLA_PROGRAMMES), + TPT_PROVIDING(GroupName.UMBRELLA_PROGRAMMES), + BANK_ACCOUNT_NPY(GroupName.UMBRELLA_PROGRAMMES), + HOUSE_TO_HOUSE_SURVEY(GroupName.UMBRELLA_PROGRAMMES), + NLEP_TRAINING(GroupName.UMBRELLA_PROGRAMMES), + NLEP_CASE_DETECTION(GroupName.UMBRELLA_PROGRAMMES), + NLEP_PB_TREATMENT(GroupName.UMBRELLA_PROGRAMMES), + NLEP_MB_TREATMENT(GroupName.UMBRELLA_PROGRAMMES), + LEPROSY_PARTIAL_ASHA(GroupName.UMBRELLA_PROGRAMMES), + NVBDCP_SLIDE_COLLECTION(GroupName.UMBRELLA_PROGRAMMES), + NVBDCP_MALARIA_TREATMENT(GroupName.UMBRELLA_PROGRAMMES), + AES_JE_REFERRAL(GroupName.UMBRELLA_PROGRAMMES), + DENGUE_CHIKUNGUNYA(GroupName.UMBRELLA_PROGRAMMES), + NIDDCP_SALT_TEST(GroupName.UMBRELLA_PROGRAMMES), + + // ---------------- NCD ---------------- + NCD_POP_ENUMERATION(GroupName.NCD), + NCD_FOLLOWUP_TREATMENT(GroupName.NCD), + NCD_NEW_PATIENT_MEDICATION_SUPPORT(GroupName.NCD), + + // ---------------- ADDITIONAL INCENTIVE ---------------- + ADDITIONAL_ASHA_INCENTIVE(GroupName.ADDITIONAL_INCENTIVE), + + // ---------------- OTHER INCENTIVES ---------------- + ABHA_ID_CREATION(GroupName.OTHER_INCENTIVES), + MOBILE_BILL_REIMB(GroupName.OTHER_INCENTIVES), + + // ---------------- ACTIVITY ---------------- + ANC_FOUR_CHECKUPS_SUPPORT(GroupName.ACTIVITY), + INST_DELIVERY_ESCORT(GroupName.ACTIVITY), + FILARIASIS_MEDICINE_DISTRIBUTION(GroupName.ACTIVITY), + VHND_PARTICIPATION(GroupName.ACTIVITY), + CLUSTER_MEETING(GroupName.ACTIVITY), + VHSNC_MEETING(GroupName.ACTIVITY), + MITANIN_REGISTER(GroupName.ACTIVITY), + HWC_REFERRAL_10_CASES(GroupName.ACTIVITY), + LACTATING_MOTHERS_HOME_VISIT(GroupName.ACTIVITY), + MITANIN_REGISTER_5_INFO_FILL(GroupName.ACTIVITY), + HIGH_RISK_POSTPARTUM_HEALTH_CHECK(GroupName.ACTIVITY), + MOSQUITO_NET_DISTRIBUTION_MOBILIZATION(GroupName.ACTIVITY), + HIGH_RISK_POSTPARTUM_CARE(GroupName.ACTIVITY), + MONTHLY_HONORARIUM(GroupName.ACTIVITY), + FULL_ANC_45(GroupName.ACTIVITY), + MH_MOTIVATE_INST_DEL_46(GroupName.ACTIVITY); + + private final GroupName groupName; + + IncentiveName(GroupName groupName) { + this.groupName = groupName; + } + + public GroupName getGroupName() { + return groupName; + } +} 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 43a9eb1fe..1ceb626a8 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -11,6 +11,7 @@ import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.ChildCareService; import com.iemr.flw.utils.JwtUtil; +import jakarta.persistence.EntityNotFoundException; import org.aspectj.weaver.ast.Or; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -75,6 +76,8 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private OrsDistributionRepo orsDistributionRepo; + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; @Override @@ -544,7 +547,8 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque try { List followUpDates = mapper.readValue( entity.getFollowUpVisitDate(), - new TypeReference>() {}); + new TypeReference>() { + }); dto.setFollowUpVisitDate(followUpDates); } catch (JsonProcessingException e) { throw new RuntimeException(e); @@ -559,7 +563,6 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque } - return samResponseListDTO; } @@ -576,25 +579,25 @@ public String saveOrsDistributionDetails(List orsDistributio 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)); + orsDistribution.setVisitDate(LocalDate.parse(orsDistributionDTO.getFields().getVisit_date(), formatter)); orsDistributionList.add(orsDistribution); }); - logger.info("orsList"+orsDistributionList.size()); - if(!orsDistributionList.isEmpty()){ + 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); + } catch (Exception e) { + logger.error("ORS Error" + e); } - return null ; + return null; } @@ -603,7 +606,7 @@ public List getOrdDistrubtion(GetBenRequestHandler r List entities = orsDistributionRepo.findByUserId(request.getAshaId()); List orsDistributionResponseDTOSList = new ArrayList<>(); - for(OrsDistribution orsDistribution: entities){ + for (OrsDistribution orsDistribution : entities) { OrsDistributionResponseDTO orsDistributionResponseDTO = new OrsDistributionResponseDTO(); OrsDistributionResponseListDTO orsDistributionResponseListDTO = new OrsDistributionResponseListDTO(); @@ -617,9 +620,8 @@ public List getOrdDistrubtion(GetBenRequestHandler r orsDistributionResponseDTOSList.add(orsDistributionResponseDTO); - } - return orsDistributionResponseDTOSList; + return orsDistributionResponseDTOSList; } @@ -633,11 +635,13 @@ private LocalDate parseDate(String dateStr) { for (DateTimeFormatter f : formatters) { try { return LocalDate.parse(dateStr, f); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } throw new DateTimeParseException("Invalid date format: " + dateStr, dateStr, 0); } + @Override public List saveAllIfa(List dtoList) { return dtoList.stream() @@ -647,16 +651,16 @@ public List saveAllIfa(List dtoList) { } - @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"); + final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); IfaDistributionDTO dto = new IfaDistributionDTO(); @@ -707,20 +711,20 @@ private IfaDistribution mapToEntity(IfaDistributionDTO dto) { return entity; } - private void checkAndAddSamVisitNRCReferalIncentive(List samVisits){ + 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()); + 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()); + if (samreferralnrcActivityCH != null) { + if (samVisit.getIsChildReferredNrc().equals("Yes")) { + createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityCH, jwtUtil.getUserNameFromStorage()); } } @@ -728,20 +732,21 @@ private void checkAndAddSamVisitNRCReferalIncentive(List samVisits){ }); } - private void checkAndAddOrdDistributionIncentive(List orsDistributionList){ + + 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); + 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); + if (orsPacketActivityCH != null) { + if (orsDistribution.getNumOrsPackets() != null) { + createIncentiveRecordforOrsDistribution(orsDistribution, orsDistribution.getBeneficiaryId(), orsPacketActivityCH, userRepo.getUserNamedByUserId(orsDistribution.getUserId()), true); } } @@ -772,9 +777,6 @@ private void checkAndAddHbyncIncentives(List hbycList) { } - - - if (hbyncOrsPacketActivityCH != null) { if (hbyc.getOrs_given()) { createIncentiveRecordforHbyncOrsDistribution(hbyc, hbyc.getBeneficiaryId(), hbyncOrsPacketActivityCH, hbyc.getCreated_by()); @@ -806,7 +808,7 @@ private void checkAndAddHbncIncentives(List hbncVisits) { } 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) { + 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()); @@ -923,11 +925,67 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(hbncVisit.getCreatedBy()); record.setBenId(benId); record.setAshaId(hbncVisit.getAshaId()); + if (hbncVisit.getDischarge_summary_upload() == null || hbncVisit.getDischarge_summary_upload().isEmpty()) { + record.setIsEligible(false); + } else { + record.setIsEligible(false); + updatePendingActivity(hbncVisit.getAshaId(),hbncVisit.getId(),record.getActivityId(),immunizationActivity.getId()); + + } record.setAmount(Long.valueOf(immunizationActivity.getRate())); recordRepo.save(record); } } + private void updatePendingActivity(Integer userId, Long recordId, Long activityId, Long mIncentiveId) { + IncentivePendingActivity incentivePendingActivity = new IncentivePendingActivity(); + incentivePendingActivity.setActivityId(activityId); + incentivePendingActivity.setRecordId(recordId); + incentivePendingActivity.setUserId(userId); + incentivePendingActivity.setMincentiveId(mIncentiveId); + if (incentivePendingActivity != null) { + incentivePendingActivityRepository.save(incentivePendingActivity); + } + + } + public HbncVisit updateHbncFromFileUpload(MultipartFile[] dischargeSncuImage,Long incentiveRecordId,Long id) throws JsonProcessingException { + HbncVisit existingHbncVisit = hbncVisitRepo.findById(id) + .orElseThrow(() -> new EntityNotFoundException("Meeting not found: " + id)); + + + // Images - only if provided + if (dischargeSncuImage != null && dischargeSncuImage.length > 0) { + List base64Images = Arrays.stream(dischargeSncuImage) + .filter(file -> file != null && !file.isEmpty()) + .map(this::convertToBase64) + .collect(Collectors.toList()); + existingHbncVisit.setDischarge_summary_upload(mapper.writeValueAsString(base64Images)); + } + + if (existingHbncVisit.getDischarge_summary_upload() != null) { + updateIncentive(incentiveRecordId); + + } + return hbncVisitRepo.save(existingHbncVisit); + } + private void updateIncentive(Long id) { + + Optional optionalRecord = recordRepo.findById(id); + + if (optionalRecord.isPresent()) { + IncentiveActivityRecord record = optionalRecord.get(); + record.setIsEligible(true); + recordRepo.save(record); + } + } + + 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); + } + } private void createIncentiveRecordforHbyncVisit(HbycChildVisit data, Long benId, IncentiveActivity immunizationActivity, String createdBy) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -987,40 +1045,40 @@ record = new IncentiveActivityRecord(); } } - 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 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()); + + } } @@ -1046,8 +1104,8 @@ record = new IncentiveActivityRecord(); record.setAmount((long) incentiveActivity.getRate()); recordRepo.save(record); } - }catch (Exception e){ - logger.error("Exp"+e.getMessage()); + } catch (Exception e) { + logger.error("Exp" + e.getMessage()); } 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 ed3cc0b37..94f28e6e7 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -10,6 +10,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.IncentiveName; import com.iemr.flw.masterEnum.StateCode; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; @@ -59,6 +60,9 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private MaaMeetingService maaMeetingService; + @Autowired + private ChildCareServiceImpl childCareService; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -78,7 +82,7 @@ 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) { } @@ -90,10 +94,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { try { List incs = new ArrayList<>(); - if(incentiveRequestDTO.getState()==StateCode.CG.getStateCode()){ + if (incentiveRequestDTO.getState() == StateCode.CG.getStateCode()) { incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); - }else { + } else { incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> !incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); } @@ -102,40 +106,38 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { // Fetch language mapping IncentiveActivityLangMapping mapping = incentiveActivityLangMappingRepo - .findByIdAndName(inc.getId(),inc.getName()); - + .findByIdAndName(inc.getId(), inc.getName()); if (mapping != null) { dto.setName(mapping.getName()); dto.setGroupName(mapping.getGroup()); - if(Objects.equals(incentiveRequestDTO.getLangCode(), "en")){ + if (Objects.equals(incentiveRequestDTO.getLangCode(), "en")) { dto.setDescription(inc.getDescription()); + } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "as")) { - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "as")){ - - if(mapping.getAssameActivityDescription()!=null){ + if (mapping.getAssameActivityDescription() != null) { dto.setDescription(mapping.getAssameActivityDescription()); - }else { + } else { dto.setDescription(mapping.getDescription()); } - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "hi")){ - if(mapping.getHindiActivityDescription()!=null){ + } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "hi")) { + if (mapping.getHindiActivityDescription() != null) { dto.setDescription(mapping.getHindiActivityDescription()); - }else { + } else { dto.setDescription(mapping.getDescription()); } } - }else { + } else { dto.setGroupName(inc.getGroup()); } @@ -156,30 +158,30 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { - if(request.getVillageID()!= StateCode.CG.getStateCode()){ + if (request.getVillageID() != StateCode.CG.getStateCode()) { checkMonthlyAshaIncentive(request.getAshaId()); } List dtos = new ArrayList<>(); List entities = recordRepo.findRecordsByAsha(request.getAshaId()); - if(request.getVillageID()==StateCode.CG.getStateCode()){ - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),true)!=null).collect(Collectors.toList()); + if (request.getVillageID() == StateCode.CG.getStateCode()) { + entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), true) != null).collect(Collectors.toList()); - }else { - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),false)!=null).collect(Collectors.toList()); + } else { + entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), false) != null).collect(Collectors.toList()); } entities.forEach(entry -> { - if(entry.getName()==null){ - if(entry.getBenId()!=0 && entry.getBenId()>0L){ + if (entry.getName() == null) { + if (entry.getBenId() != 0 && entry.getBenId() > 0L) { Long regId = beneficiaryRepo.getBenRegIdFromBenId(entry.getBenId()); - logger.info("rmnchBeneficiaryDetailsRmnch"+regId); + logger.info("rmnchBeneficiaryDetailsRmnch" + regId); BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(regId)).getBenDetailsId(); RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); - String beneName = rmnchBeneficiaryDetails.getFirstName()+" "+rmnchBeneficiaryDetails.getLastName(); + String beneName = rmnchBeneficiaryDetails.getFirstName() + " " + rmnchBeneficiaryDetails.getLastName(); entry.setName(beneName); - }else{ + } else { entry.setName(""); } @@ -196,49 +198,115 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { - IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup(pendingActivityDTO.getName(), pendingActivityDTO.getModuleName()); - if (incentiveActivity != null) { - Optional incentivePendingActivity = incentivePendingActivityRepository.findByMincentiveIdAndActivityId(pendingActivityDTO.getId(), incentiveActivity.getId()); - if (incentivePendingActivity.isPresent()) { - IncentivePendingActivity existingIncentivePendingActivity = incentivePendingActivity.get(); - if (existingIncentivePendingActivity.getActivityId().equals(pendingActivityDTO.getId())) { - if (pendingActivityDTO.getImages() != null) { - try { - MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); - maaMeetingRequestDTO.setMeetingImages(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - maaMeetingService.updateMeetingFromFileUpload(maaMeetingRequestDTO,pendingActivityDTO.getId()); - - } catch (Exception e) { - return e.getMessage(); - } - } + if (pendingActivityDTO == null) { + return "Invalid request"; + } + + IncentiveName incentiveName; + try { + incentiveName = IncentiveName.valueOf(pendingActivityDTO.getName()); + } catch (IllegalArgumentException e) { + return "Invalid incentive name"; + } + + IncentiveActivity incentiveActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + pendingActivityDTO.getName(), + pendingActivityDTO.getModuleName() + ); + + if (incentiveActivity == null) { + return null; + } + + Optional optionalPendingActivity = + incentivePendingActivityRepository + .findByMincentiveIdAndActivityId( + pendingActivityDTO.getId(), + incentiveActivity.getId() + ); + + if (!optionalPendingActivity.isPresent()) { + return null; + } + + IncentivePendingActivity existingActivity = optionalPendingActivity.get(); + + if (!existingActivity.getActivityId().equals(pendingActivityDTO.getId())) { + return null; + } + + if (pendingActivityDTO.getImages() == null || pendingActivityDTO.getImages().isEmpty()) { + return null; + } + + try { + MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); + maaMeetingRequestDTO.setMeetingImages( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]) + ); + + // ✅ ENUM BASED CHECK + if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ + if (incentiveName == IncentiveName.MAA_QUARTERLY_MEETING) { + + maaMeetingService.updateMeetingFromFileUpload( + maaMeetingRequestDTO, + pendingActivityDTO.getId() + ); + } + }else { + if (incentiveName == IncentiveName.MAA_QUARTERLY_MEETING) { + + maaMeetingService.updateMeetingFromFileUpload( + maaMeetingRequestDTO, + pendingActivityDTO.getId() + ); + } + + if (incentiveName == IncentiveName.HBNC_0_42_DAYS) { + + childCareService.updateHbncFromFileUpload( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]), + pendingActivityDTO.getId(), + existingActivity.getRecordId() + + ); } + + } + + + + + } catch (Exception e) { + return e.getMessage(); } - return null; + return null; } - private void checkMonthlyAshaIncentive(Integer ashaId){ + private void checkMonthlyAshaIncentive(Integer 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); + if (MOBILEBILLREIMB_ACTIVITY != null) { + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId); } - if(ADDITIONAL_ASHA_INCENTIVE!=null){ - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE,ashaId); + if (ADDITIONAL_ASHA_INCENTIVE != null) { + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId); } - if(ASHA_MONTHLY_ROUTINE!=null){ - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE,ashaId); + if (ASHA_MONTHLY_ROUTINE != null) { + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId); } } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId){ + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId) { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); From 3593e4520a948d5cd755eea2946014fb8b4774dd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 17:36:40 +0530 Subject: [PATCH 124/450] implement check on pending doc for incentive review --- .../flw/repo/iemr/IncentivePendingActivityRepository.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java index 89b2bed5c..295d447bb 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivePendingActivityRepository.java @@ -9,11 +9,5 @@ @Repository public interface IncentivePendingActivityRepository extends JpaRepository { - Optional - findByUserIdAndModuleNameAndActivityId( - Integer userId, - String moduleName, - Long activityId - ); Optional findByMincentiveIdAndActivityId(Long mIncentiveId,Long activityId); } From 13fedf9b30fc5d18003155ef7fec1847e638fd64 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 17:49:50 +0530 Subject: [PATCH 125/450] implement check on pending doc for incentive review --- src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java | 2 +- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java index b85ffc9fc..5fcdd5375 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -11,5 +11,5 @@ public class PendingActivityDTO { private Integer userId; private List images; private String moduleName; - private String name; + private String activityName; } 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 94f28e6e7..c6a779641 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -205,14 +205,14 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { IncentiveName incentiveName; try { - incentiveName = IncentiveName.valueOf(pendingActivityDTO.getName()); + incentiveName = IncentiveName.valueOf(pendingActivityDTO.getActivityName()); } catch (IllegalArgumentException e) { return "Invalid incentive name"; } IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup( - pendingActivityDTO.getName(), + pendingActivityDTO.getActivityName(), pendingActivityDTO.getModuleName() ); From 1cb9e1416974333a993c45ba4423be6b31203aca Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Feb 2026 18:04:48 +0530 Subject: [PATCH 126/450] implement check on pending doc for incentive review --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 c6a779641..1c39b5c66 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -257,7 +257,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { ); } }else { - if (incentiveName == IncentiveName.MAA_QUARTERLY_MEETING) { + if (incentiveName.name().equals(IncentiveName.MAA_QUARTERLY_MEETING.name())) { maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, @@ -265,7 +265,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { ); } - if (incentiveName == IncentiveName.HBNC_0_42_DAYS) { + if (incentiveName.name().equals(IncentiveName.HBNC_0_42_DAYS.name())) { childCareService.updateHbncFromFileUpload( pendingActivityDTO.getImages().toArray(new MultipartFile[0]), From aa46e6b5c06938c29332ecbb0cbd85335052c034 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Feb 2026 12:15:48 +0530 Subject: [PATCH 127/450] implement check on pending doc for incentive review --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1c39b5c66..4438e2cba 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -249,7 +249,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { // ✅ ENUM BASED CHECK if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ - if (incentiveName == IncentiveName.MAA_QUARTERLY_MEETING) { + if (incentiveName.name() == IncentiveName.MAA_QUARTERLY_MEETING.name()) { maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, From 655f6a3b9f907e05e09106134fe9a0451eddb174 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Feb 2026 12:24:24 +0530 Subject: [PATCH 128/450] implement check on pending doc for incentive review --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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 4438e2cba..33f8ac1d2 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -246,6 +246,8 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { maaMeetingRequestDTO.setMeetingImages( pendingActivityDTO.getImages().toArray(new MultipartFile[0]) ); + logger.info("Activity Name from request:"+incentiveName.name()); + logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); // ✅ ENUM BASED CHECK if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ From 2ad53c11d271223a43eebe31cb6513988c8c989b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 13:41:51 +0530 Subject: [PATCH 129/450] optmiz code of get all Beneficiary --- .../service/impl/BeneficiaryServiceImpl.java | 835 ++++++++---------- 1 file changed, 371 insertions(+), 464 deletions(-) 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 f5a757854..b4e388ace 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -1,8 +1,6 @@ package com.iemr.flw.service.impl; 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; @@ -14,10 +12,8 @@ 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; @@ -25,7 +21,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @@ -35,8 +30,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializer; import com.iemr.flw.domain.identity.BenHealthIDDetails; import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; import com.iemr.flw.domain.identity.RMNCHBornBirthDetails; @@ -52,36 +45,45 @@ import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.identity.HouseHoldRepo; import com.iemr.flw.service.BeneficiaryService; -import com.iemr.flw.utils.config.ConfigProperties; import com.iemr.flw.utils.http.HttpUtils; @Service @Qualifier("rmnchServiceImpl") - public class BeneficiaryServiceImpl implements BeneficiaryService { - private final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); + private static final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + private static final Gson GSON = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + + // Map keys as constants to avoid typos and magic strings + private static final String KEY_HOUSEHOLD_DETAILS = "householdDetails"; + private static final String KEY_BORN_BIRTH_DETAILS = "bornBirthDetails"; + private static final String KEY_BENEFICIARY_DETAILS = "beneficiaryDetails"; + private static final String KEY_ABHA_HEALTH_DETAILS = "abhaHealthDetails"; + @Value("${door-to-door-page-size}") - private String door_to_door_page_size; + private String doorToDoorPageSize; @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; + private IncentivesRepo incentivesRepo; @Autowired - IncentiveRecordRepo recordRepo; + private IncentiveRecordRepo recordRepo; @Autowired private EyeCheckUpVisitRepo eyeCheckUpVisitRepo; @@ -92,497 +94,402 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Autowired private UserServiceRoleRepo userRepo; - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - + // Single shared HttpUtils instance — avoid creating one per request + private final HttpUtils httpUtils = new HttpUtils(); + // ------------------------------------------------------------------------- + // Public API + // ------------------------------------------------------------------------- @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { - String outputResponse = null; - int totalPage = 0; + if (request == null || request.getAshaId() == null) { + throw new Exception("Invalid/missing village details"); + } + if (request.getPageNo() == null) { + throw new Exception("Invalid page no"); + } - try { - if (request != null && request.getAshaId() != null) { - List resultSet; - Integer pageSize = Integer.valueOf(door_to_door_page_size); - if (request.getPageNo() != null) { - String userName = beneficiaryRepo.getUserName(request.getAshaId()); - if (userName == null || userName.isEmpty()) - throw new Exception("Asha details not found, please contact administrator"); - - request.setUserName(userName); - - PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); - if (request.getFromDate() != null && request.getToDate() != null) { - Page p = beneficiaryRepo.getBenDataWithinDates( - request.getUserName(), request.getFromDate(), request.getToDate(), pr); - resultSet = p.getContent(); - totalPage = p.getTotalPages(); - } else { - Page p = beneficiaryRepo.getBenDataByUser(request.getUserName(), - pr); - resultSet = p.getContent(); - totalPage = p.getTotalPages(); - } - if (resultSet != null && resultSet.size() > 0) { - outputResponse = getMappingsForAddressIDs(resultSet, totalPage, authorisation); - } - } else { - // page no not invalid - throw new Exception("Invalid page no"); - } - } else - throw new Exception("Invalid/missing village details"); - } catch (Exception e) { - throw new Exception(e.getMessage()); + String userName = beneficiaryRepo.getUserName(request.getAshaId()); + if (userName == null || userName.isEmpty()) { + throw new Exception("Asha details not found, please contact administrator"); + } + request.setUserName(userName); + + int pageSize = Integer.parseInt(doorToDoorPageSize); + PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); + + Page page; + if (request.getFromDate() != null && request.getToDate() != null) { + page = beneficiaryRepo.getBenDataWithinDates( + request.getUserName(), request.getFromDate(), request.getToDate(), pr); + } else { + page = beneficiaryRepo.getBenDataByUser(request.getUserName(), pr); + } + + List resultSet = page.getContent(); + if (resultSet.isEmpty()) { + Map emptyResponse = new HashMap<>(); + emptyResponse.put("data", new ArrayList<>()); + emptyResponse.put("pageSize", pageSize); + emptyResponse.put("totalPage", 0); + return GSON.toJson(emptyResponse); } - return outputResponse; + return buildBeneficiaryResponse(resultSet, page.getTotalPages(), authorisation); } - private String getMappingsForAddressIDs(List addressList, int totalPage, - String authorisation) { - RMNCHHouseHoldDetails benHouseHoldRMNCH_ROBJ; - RMNCHBeneficiaryDetailsRmnch benDetailsRMNCH_OBJ; - RMNCHBornBirthDetails benBotnBirthRMNCH_ROBJ; + @Override + public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS) { + if (eyeCheckupRequestDTOS == null || eyeCheckupRequestDTOS.isEmpty()) { + throw new IllegalArgumentException("Eye checkup list must not be empty"); + } - RMNCHMBeneficiarydetail benDetailsOBJ; - RMNCHMBeneficiaryAccount benAccountOBJ; - RMNCHMBeneficiaryImage benImageOBJ; - RMNCHMBeneficiaryaddress benAddressOBJ; - RMNCHMBeneficiarycontact benContactOBJ; + // Resolve userId once — same ASHA for the whole batch + Integer userId = userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage()); + + List visitsToSave = eyeCheckupRequestDTOS.stream().map(dto -> { + EyeCheckupListDTO f = dto.getFields(); + EyeCheckupVisit visit = new EyeCheckupVisit(); + visit.setBeneficiaryId(dto.getBeneficiaryId()); + visit.setHouseholdId(dto.getHouseHoldId()); + visit.setUserId(userId); + visit.setCreatedBy(dto.getUserName()); + visit.setVisitDate(LocalDate.parse(f.getVisit_date(), FORMATTER)); + visit.setSymptomsObserved(f.getSymptoms_observed()); + visit.setEyeAffected(f.getEye_affected()); + visit.setReferredTo(f.getReferred_to()); + // No-op StringBuilder removed; just use the value directly + visit.setDischargeSummaryUpload(f.getDischarge_summary_upload()); + visit.setFollowUpStatus(f.getFollow_up_status()); + visit.setDateOfSurgery(f.getDate_of_surgery()); + return visit; + }).collect(Collectors.toList()); - Map resultMap; - ArrayList> resultList = new ArrayList<>(); + // Batch save instead of one-by-one + eyeCheckUpVisitRepo.saveAll(visitsToSave); + return "Eye checkup data saved successfully."; + } - for (RMNCHMBeneficiaryaddress a : addressList) { - // exception by-passing + @Override + public List getEyeCheckUpVisit(GetBenRequestHandler request) { + List visits = eyeCheckUpVisitRepo.findByUserId(request.getAshaId()); + return visits.stream().map(this::mapVisitToDto).collect(Collectors.toList()); + } + + // ------------------------------------------------------------------------- + // Private helpers + // ------------------------------------------------------------------------- + + private String buildBeneficiaryResponse(List addressList, + int totalPage, String authorisation) { + List> resultList = new ArrayList<>(addressList.size()); + + for (RMNCHMBeneficiaryaddress address : addressList) { try { - RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); - if (m != null) { - benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); - - benDetailsOBJ = new RMNCHMBeneficiarydetail(); - benAccountOBJ = new RMNCHMBeneficiaryAccount(); - benImageOBJ = new RMNCHMBeneficiaryImage(); - benAddressOBJ = new RMNCHMBeneficiaryaddress(); - benContactOBJ = new RMNCHMBeneficiarycontact(); - Map healthDetails = getBenHealthDetails(m.getBenRegId()); - if (m.getBenDetailsId() != null) { - benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); - } - if (m.getBenAccountID() != null) { - benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); - } - if (m.getBenImageId() != null) { - benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); - } - if (m.getBenAddressId() != null) { - benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); - } - if (m.getBenContactsId() != null) { - benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); - } - - BigInteger benID = null; - if (m.getBenRegId() != null) - benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); - - if (m.getBenRegId() != null) { - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()); - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); - - if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()); - - } - if (benDetailsRMNCH_OBJ == null) - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - - // new mapping 30-06-2021 - if (benDetailsOBJ.getMotherName() != null) - benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); - if (benDetailsOBJ.getLiteracyStatus() != null) - benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); - - // bank - if (benAccountOBJ.getNameOfBank() != null) - benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); - if (benAccountOBJ.getBranchName() != null) - benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); - if (benAccountOBJ.getIfscCode() != null) - benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); - if (benAccountOBJ.getBankAccount() != null) - benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); - - // location - if (benAddressOBJ.getCountyid() != null) - benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); - if (benAddressOBJ.getPermCountry() != null) - benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); - - if (benAddressOBJ.getStatePerm() != null) - benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); - if (benAddressOBJ.getPermState() != null) - benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); - - if (benAddressOBJ.getDistrictidPerm() != null) { - benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); - - } - if (benAddressOBJ.getDistrictnamePerm() != null) { - benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); - - } - - if (benAddressOBJ.getPermSubDistrictId() != null) - benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); - if (benAddressOBJ.getPermSubDistrict() != null) - benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); - - if (benAddressOBJ.getVillageidPerm() != null) - benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); - if (benAddressOBJ.getVillagenamePerm() != null) - benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); - - if (benAddressOBJ.getPermServicePointId() != null) - benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); - if (benAddressOBJ.getPermServicePoint() != null) - benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); - - if (benAddressOBJ.getPermZoneID() != null) - benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); - if (benAddressOBJ.getPermZone() != null) - benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); - - if (benAddressOBJ.getPermAddrLine1() != null) - benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); - if (benAddressOBJ.getPermAddrLine2() != null) - benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); - if (benAddressOBJ.getPermAddrLine3() != null) - benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); - - // ----------------------------------------------------------------------------- - - // related benids - if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { - - String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); - Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; - int pointer = 0; - for (String s : relatedBenIDsString) { - relatedBenIDs[pointer] = Long.valueOf(s); - pointer++; - } - - benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); - } - // ------------------------------------------------------------------------------ - - if (benDetailsOBJ.getCommunity() != null) - benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); - if (benDetailsOBJ.getCommunityId() != null) - benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); - if (benContactOBJ.getPreferredPhoneNum() != null) - benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); - - if (benDetailsOBJ.getDob() != null) - benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); - if (benDetailsOBJ.getFatherName() != null) - benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); - if (benDetailsOBJ.getFirstName() != null) - benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); - if (benDetailsOBJ.getGender() != null) - benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); - if (benDetailsOBJ.getGenderId() != null) - benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); - - if (benDetailsOBJ.getMaritalstatus() != null) - benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); - if (benDetailsOBJ.getMaritalstatusId() != null) - benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); - if (benDetailsOBJ.getMarriageDate() != null) - benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); - - if (benDetailsOBJ.getReligion() != null) - benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); - if (benDetailsOBJ.getReligionID() != null) - benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); - if (benDetailsOBJ.getSpousename() != null) - benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); - - if (benImageOBJ != null && benImageOBJ.getUser_image() != null) - benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); - - // new fields -// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); - if (benID != null) - benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - - if (benDetailsOBJ.getLastName() != null) - benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - - if (benDetailsRMNCH_OBJ.getCreatedBy() == null) - if (benDetailsOBJ.getCreatedBy() != null) - benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - - // age calculation - String ageDetails = ""; - int age_val = 0; - String ageUnit = null; - if (benDetailsOBJ.getDob() != null) { - - Date date = new Date(benDetailsOBJ.getDob().getTime()); - Calendar cal = Calendar.getInstance(); - - cal.setTime(date); - - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - - java.time.LocalDate todayDate = java.time.LocalDate.now(); - java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); - Period p = Period.between(birthdate, todayDate); - - int d = p.getDays(); - int mo = p.getMonths(); - int y = p.getYears(); - - if (y > 0) { - ageDetails = y + " years - " + mo + " months"; - age_val = y; - ageUnit = (age_val > 1) ? "Years" : "Year"; - } else { - if (mo > 0) { - ageDetails = mo + " months - " + d + " days"; - age_val = mo; - ageUnit = (age_val > 1) ? "Months" : "Month"; - } else { - ageDetails = d + " days"; - age_val = d; - ageUnit = (age_val > 1) ? "Days" : "Day"; - } - } - - } - - benDetailsRMNCH_OBJ.setAgeFull(ageDetails); - benDetailsRMNCH_OBJ.setAge(age_val); - if (ageUnit != null) - benDetailsRMNCH_OBJ.setAge_unit(ageUnit); - - resultMap = new HashMap<>(); - if (benHouseHoldRMNCH_ROBJ != null) - resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); - else - resultMap.put("householdDetails", new HashMap()); - - if (benBotnBirthRMNCH_ROBJ != null) - resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); - else - resultMap.put("bornbirthDeatils", new HashMap()); - - resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); - 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 - if (benAddressOBJ.getCreatedBy() != null) { - Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); - if (userID != null && userID > 0) - resultMap.put("ashaId", userID); - } - // get HealthID of ben - if (m.getBenRegId() != null) { - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); - } - - resultList.add(resultMap); - - } else { - // mapping not available - } + RMNCHMBeneficiarymapping mapping = beneficiaryRepo.getByAddressID(address.getId()); + if (mapping == null) continue; + + Map resultMap = buildResultMap(mapping, authorisation); + resultList.add(resultMap); } catch (Exception e) { - logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); + logger.error("Error processing addressID: {} vanID: {} — {}", + address.getId(), address.getVanID(), e.getMessage(), e); } } Map response = new HashMap<>(); response.put("data", resultList); - response.put("pageSize", Integer.parseInt(door_to_door_page_size)); + response.put("pageSize", Integer.parseInt(doorToDoorPageSize)); response.put("totalPage", totalPage); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(response); + return GSON.toJson(response); } - - private Map getBenHealthDetails(BigInteger benRegId) { - Map healthDetails = new HashMap<>(); - if (null != benRegId) { - Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); - if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { - Object[] healthData = (Object[]) benHealthIdNumber[0]; - String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; - String healthId = healthData[1] != null ? healthData[1].toString() : null; - - if (null != healthIdNumber) { - List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); - if (health != null && !health.isEmpty()) { - for (Object[] objects : health) { - healthDetails.put("HealthID", objects[0]); - healthDetails.put("HealthIdNumber", objects[1]); - healthDetails.put("isNewAbha", objects[2]); - } - } else { - healthDetails.put("HealthIdNumber", healthIdNumber); - healthDetails.put("HealthID", healthId); - healthDetails.put("isNewAbha", null); - } - } - } - } - 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]); + /** + * Builds the complete result map for one beneficiary mapping. + * All sub-fetches are grouped here so the flow is easy to follow. + */ + private Map buildResultMap(RMNCHMBeneficiarymapping m, String authorisation) { + // ---- Fetch sub-objects (null-safe defaults) ---- + RMNCHMBeneficiarydetail benDetail = fetchOrDefault(m.getBenDetailsId(), + beneficiaryRepo::getDetailsById, new RMNCHMBeneficiarydetail()); + RMNCHMBeneficiaryAccount benAccount = fetchOrDefault(m.getBenAccountID(), + beneficiaryRepo::getAccountById, new RMNCHMBeneficiaryAccount()); + RMNCHMBeneficiaryImage benImage = m.getBenImageId() != null + ? beneficiaryRepo.getImageById(m.getBenImageId().longValue()) : new RMNCHMBeneficiaryImage(); + RMNCHMBeneficiaryaddress benAddress = fetchOrDefault(m.getBenAddressId(), + beneficiaryRepo::getAddressById, new RMNCHMBeneficiaryaddress()); + RMNCHMBeneficiarycontact benContact = fetchOrDefault(m.getBenContactsId(), + beneficiaryRepo::getContactById, new RMNCHMBeneficiarycontact()); + + BigInteger benID = m.getBenRegId() != null + ? beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()) : null; + + RMNCHBeneficiaryDetailsRmnch benDetailsRMNCH = new RMNCHBeneficiaryDetailsRmnch(); + RMNCHHouseHoldDetails householdDetails = new RMNCHHouseHoldDetails(); + RMNCHBornBirthDetails bornBirthDetails = new RMNCHBornBirthDetails(); + + if (m.getBenRegId() != null) { + RMNCHBeneficiaryDetailsRmnch fetched = + beneficiaryRepo.getDetailsByRegID(m.getBenRegId().longValue()); + if (fetched != null) { + benDetailsRMNCH = fetched; + if (benDetailsRMNCH.getHouseoldId() != null) { + householdDetails = houseHoldRepo.getByHouseHoldID(benDetailsRMNCH.getHouseoldId()); } } + RMNCHBornBirthDetails birth = beneficiaryRepo.getBornBirthByRegID(m.getBenRegId().longValue()); + if (birth != null) bornBirthDetails = birth; } - return healthDetails; - } - public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { - Map requestMap = new HashMap(); - requestMap.put("beneficiaryRegID", benRegID); - requestMap.put("beneficiaryID", null); - JsonParser jsnParser = new JsonParser(); - HttpUtils utils = new HttpUtils(); - List result = null; - try { - HashMap header = new HashMap(); - header.put("Authorization", authorization); - String responseStr = utils.post(fhirUrl + "/" - + getHealthID, new Gson().toJson(requestMap), header); - JsonElement jsnElmnt = jsnParser.parse(responseStr); - JsonObject jsnOBJ = new JsonObject(); - jsnOBJ = jsnElmnt.getAsJsonObject(); - if (jsnOBJ.get("data") != null && jsnOBJ.get("data").getAsJsonObject().get("BenHealthDetails") != null) { - result = new ArrayList(); - BenHealthIDDetails[] ben = InputMapper.gson().fromJson( - new Gson().toJson(jsnOBJ.get("data").getAsJsonObject().get("BenHealthDetails")), - BenHealthIDDetails[].class); - for (BenHealthIDDetails value : ben) { - if (value.getHealthId() != null) - resultMap.put("healthId", value.getHealthId()); - if (value.getHealthIdNumber() != null) - resultMap.put("healthIdNumber", value.getHealthIdNumber()); - } - } + // ---- Merge fields into benDetailsRMNCH ---- + mergeDetailFields(benDetailsRMNCH, benDetail, benAccount, benAddress, benContact, benImage, benID); + + // ---- Age calculation ---- + applyAgeCalculation(benDetailsRMNCH, benDetail); + + // ---- Health details ---- + Map healthDetails = getBenHealthDetails(m.getBenRegId()); + + // ---- Assemble result map ---- + Map resultMap = new HashMap<>(); + resultMap.put(KEY_HOUSEHOLD_DETAILS, householdDetails != null ? householdDetails : new HashMap<>()); + resultMap.put(KEY_BORN_BIRTH_DETAILS, bornBirthDetails); + resultMap.put(KEY_BENEFICIARY_DETAILS, benDetailsRMNCH); + resultMap.put(KEY_ABHA_HEALTH_DETAILS, healthDetails); + resultMap.put("houseoldId", benDetailsRMNCH.getHouseoldId()); + resultMap.put("benficieryid", benDetailsRMNCH.getBenficieryid()); + resultMap.put("isDeath", benDetailsRMNCH.getIsDeath()); + resultMap.put("isDeathValue", benDetailsRMNCH.getIsDeathValue()); + resultMap.put("dateOfDeath", benDetailsRMNCH.getDateOfDeath()); + resultMap.put("timeOfDeath", benDetailsRMNCH.getTimeOfDeath()); + resultMap.put("reasonOfDeath", benDetailsRMNCH.getReasonOfDeath()); + resultMap.put("reasonOfDeathId", benDetailsRMNCH.getReasonOfDeathId()); + resultMap.put("placeOfDeath", benDetailsRMNCH.getPlaceOfDeath()); + resultMap.put("placeOfDeathId", benDetailsRMNCH.getPlaceOfDeathId()); + resultMap.put("isSpouseAdded", benDetailsRMNCH.getIsSpouseAdded()); + resultMap.put("isChildrenAdded", benDetailsRMNCH.getIsChildrenAdded()); + resultMap.put("noOfchildren", benDetailsRMNCH.getNoOfchildren()); + resultMap.put("isMarried", benDetailsRMNCH.getIsMarried()); + resultMap.put("doYouHavechildren", benDetailsRMNCH.getDoYouHavechildren()); + resultMap.put("noofAlivechildren", benDetailsRMNCH.getNoofAlivechildren()); // typo fixed (no trailing spaces) + resultMap.put("BenRegId", m.getBenRegId()); + + // ASHA id from address creator + if (benAddress.getCreatedBy() != null) { + Integer userID = beneficiaryRepo.getUserIDByUserName(benAddress.getCreatedBy()); + if (userID != null && userID > 0) resultMap.put("ashaId", userID); + } - } catch (Exception e) { - logger.info("Error while fetching ABHA" + e.getMessage()); -// return null; + // External ABHA fetch + if (m.getBenRegId() != null) { + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); } -// return result; + return resultMap; + } + /** Copies all mergeable fields from sub-objects into the RMNCH details object. */ + private void mergeDetailFields(RMNCHBeneficiaryDetailsRmnch dest, + RMNCHMBeneficiarydetail detail, + RMNCHMBeneficiaryAccount account, + RMNCHMBeneficiaryaddress address, + RMNCHMBeneficiarycontact contact, + RMNCHMBeneficiaryImage image, + BigInteger benID) { + // Personal + setIfNotNull(detail.getFirstName(), dest::setFirstName); + setIfNotNull(detail.getLastName(), dest::setLastName); + setIfNotNull(detail.getMotherName(), dest::setMotherName); + setIfNotNull(detail.getFatherName(), dest::setFatherName); + setIfNotNull(detail.getSpousename(), dest::setSpousename); + setIfNotNull(detail.getDob(), dest::setDob); + setIfNotNull(detail.getGender(), dest::setGender); + setIfNotNull(detail.getGenderId(), dest::setGenderId); + setIfNotNull(detail.getMaritalstatus(), dest::setMaritalstatus); + setIfNotNull(detail.getMaritalstatusId(),dest::setMaritalstatusId); + setIfNotNull(detail.getMarriageDate(), dest::setMarriageDate); + setIfNotNull(detail.getLiteracyStatus(), dest::setLiteracyStatus); + setIfNotNull(detail.getCommunity(), dest::setCommunity); + setIfNotNull(detail.getCommunityId(), dest::setCommunityId); + setIfNotNull(detail.getReligion(), dest::setReligion); + setIfNotNull(detail.getReligionID(), dest::setReligionID); + if (dest.getCreatedBy() == null) setIfNotNull(detail.getCreatedBy(), dest::setCreatedBy); + + // Bank + setIfNotNull(account.getNameOfBank(), dest::setNameOfBank); + setIfNotNull(account.getBranchName(), dest::setBranchName); + setIfNotNull(account.getIfscCode(), dest::setIfscCode); + setIfNotNull(account.getBankAccount(), dest::setBankAccount); + + // Address + setIfNotNull(address.getCountyid(), dest::setCountryId); + setIfNotNull(address.getPermCountry(), dest::setCountryName); + setIfNotNull(address.getStatePerm(), dest::setStateId); + setIfNotNull(address.getPermState(), dest::setStateName); + setIfNotNull(address.getDistrictidPerm(), dest::setDistrictid); + setIfNotNull(address.getDistrictnamePerm(), dest::setDistrictname); + setIfNotNull(address.getPermSubDistrictId(), dest::setBlockId); + setIfNotNull(address.getPermSubDistrict(), dest::setBlockName); + setIfNotNull(address.getVillageidPerm(), dest::setVillageId); + setIfNotNull(address.getVillagenamePerm(), dest::setVillageName); + setIfNotNull(address.getPermServicePointId(), dest::setServicePointID); + setIfNotNull(address.getPermServicePoint(), dest::setServicePointName); + setIfNotNull(address.getPermZoneID(), dest::setZoneID); + setIfNotNull(address.getPermZone(), dest::setZoneName); + setIfNotNull(address.getPermAddrLine1(), dest::setAddressLine1); + setIfNotNull(address.getPermAddrLine2(), dest::setAddressLine2); + setIfNotNull(address.getPermAddrLine3(), dest::setAddressLine3); + + // Contact + setIfNotNull(contact.getPreferredPhoneNum(), dest::setContact_number); + + // Image + if (image != null) setIfNotNull(image.getUser_image(), dest::setUser_image); + + // Ben ID + if (benID != null) dest.setBenficieryid(benID.longValue()); + + // Related beneficiary IDs + if (dest.getRelatedBeneficiaryIdsDB() != null) { + String[] parts = dest.getRelatedBeneficiaryIdsDB().split(","); + Long[] ids = new Long[parts.length]; + for (int i = 0; i < parts.length; i++) ids[i] = Long.valueOf(parts[i].trim()); + dest.setRelatedBeneficiaryIds(ids); + } } + /** Calculates age from DOB and sets ageFull, age, and age_unit on the destination object. */ + private void applyAgeCalculation(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBeneficiarydetail detail) { + if (detail.getDob() == null) return; + + Calendar cal = Calendar.getInstance(); + cal.setTime(detail.getDob()); + LocalDate birthDate = LocalDate.of( + cal.get(Calendar.YEAR), + cal.get(Calendar.MONTH) + 1, + cal.get(Calendar.DAY_OF_MONTH)); + + Period p = Period.between(birthDate, LocalDate.now()); + int years = p.getYears(); + int months = p.getMonths(); + int days = p.getDays(); + + String ageFull; + int ageVal; + String ageUnit; + + if (years > 0) { + ageFull = years + " years - " + months + " months"; + ageVal = years; + ageUnit = years > 1 ? "Years" : "Year"; + } else if (months > 0) { + ageFull = months + " months - " + days + " days"; + ageVal = months; + ageUnit = months > 1 ? "Months" : "Month"; + } else { + ageFull = days + " days"; + ageVal = days; + ageUnit = days > 1 ? "Days" : "Day"; + } - @Override - public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS) { + dest.setAgeFull(ageFull); + dest.setAge(ageVal); + dest.setAge_unit(ageUnit); + } + + private Map getBenHealthDetails(BigInteger benRegId) { + Map healthDetails = new HashMap<>(); + if (benRegId == null) return healthDetails; + + Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); + if (benHealthIdNumber == null || benHealthIdNumber.length == 0) return healthDetails; + + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + + if (healthIdNumber == null) return healthDetails; + + List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); + if (health != null && !health.isEmpty()) { + Object[] row = health.get(0); // last writer wins anyway; just use first + healthDetails.put("HealthID", row[0]); + healthDetails.put("HealthIdNumber", row[1]); + healthDetails.put("isNewAbha", row[2]); + } else { + healthDetails.put("HealthIdNumber", healthIdNumber); + healthDetails.put("HealthID", healthId); + healthDetails.put("isNewAbha", null); + } + return healthDetails; + } + + public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { + Map requestBody = new HashMap<>(); + requestBody.put("beneficiaryRegID", benRegID); + requestBody.put("beneficiaryID", null); try { - for (EyeCheckupRequestDTO dto : eyeCheckupRequestDTOS) { - EyeCheckupVisit visit = new EyeCheckupVisit(); - - visit.setBeneficiaryId(dto.getBeneficiaryId()); - visit.setHouseholdId(dto.getHouseHoldId()); - visit.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); // cache se lena hai - 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); + HashMap headers = new HashMap<>(); + headers.put("Authorization", authorization); + String responseStr = httpUtils.post(fhirUrl + "/" + getHealthID, GSON.toJson(requestBody), headers); + + JsonElement element = JsonParser.parseString(responseStr); // non-deprecated API + if (!element.isJsonObject()) return; + + JsonObject root = element.getAsJsonObject(); + if (root.get("data") == null) return; + + JsonObject data = root.getAsJsonObject("data"); + if (data.get("BenHealthDetails") == null) return; + + BenHealthIDDetails[] details = InputMapper.gson().fromJson( + GSON.toJson(data.get("BenHealthDetails")), BenHealthIDDetails[].class); + + for (BenHealthIDDetails d : details) { + if (d.getHealthId() != null) resultMap.put("healthId", d.getHealthId()); + if (d.getHealthIdNumber() != null) resultMap.put("healthIdNumber", d.getHealthIdNumber()); } - return "Eye checkup data saved successfully."; } catch (Exception e) { - e.printStackTrace(); - + logger.warn("Failed to fetch ABHA for benRegID {}: {}", benRegID, e.getMessage()); } - return null ; } - @Override - public List getEyeCheckUpVisit(GetBenRequestHandler request) { - List visits = eyeCheckUpVisitRepo.findByUserId(request.getAshaId()); - - 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()); + private EyeCheckupRequestDTO mapVisitToDto(EyeCheckupVisit 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; } + // ------------------------------------------------------------------------- + // Generic utilities + // ------------------------------------------------------------------------- + + /** Calls setter only when value is non-null — replaces the repetitive if-blocks. */ + private void setIfNotNull(T value, java.util.function.Consumer setter) { + if (value != null) setter.accept(value); + } -} + /** Fetches an entity by ID; returns defaultValue when ID is null. */ + private T fetchOrDefault(ID id, java.util.function.Function fetcher, T defaultValue) { + if (id == null) return defaultValue; + T result = fetcher.apply(id); + return result != null ? result : defaultValue; + } +} \ No newline at end of file From 3da48c327289718d7f025a3afdb8d7d6601eac32 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 15:20:16 +0530 Subject: [PATCH 130/450] optmiz code of get all Beneficiary --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 b4e388ace..7fc6d1270 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -259,6 +259,7 @@ private Map buildResultMap(RMNCHMBeneficiarymapping m, String au resultMap.put(KEY_ABHA_HEALTH_DETAILS, healthDetails); resultMap.put("houseoldId", benDetailsRMNCH.getHouseoldId()); resultMap.put("benficieryid", benDetailsRMNCH.getBenficieryid()); + resultMap.put("BenRegId", m.getBenRegId()); resultMap.put("isDeath", benDetailsRMNCH.getIsDeath()); resultMap.put("isDeathValue", benDetailsRMNCH.getIsDeathValue()); resultMap.put("dateOfDeath", benDetailsRMNCH.getDateOfDeath()); @@ -273,7 +274,6 @@ private Map buildResultMap(RMNCHMBeneficiarymapping m, String au resultMap.put("isMarried", benDetailsRMNCH.getIsMarried()); resultMap.put("doYouHavechildren", benDetailsRMNCH.getDoYouHavechildren()); resultMap.put("noofAlivechildren", benDetailsRMNCH.getNoofAlivechildren()); // typo fixed (no trailing spaces) - resultMap.put("BenRegId", m.getBenRegId()); // ASHA id from address creator if (benAddress.getCreatedBy() != null) { @@ -420,7 +420,7 @@ private Map getBenHealthDetails(BigInteger benRegId) { } else { healthDetails.put("HealthIdNumber", healthIdNumber); healthDetails.put("HealthID", healthId); - healthDetails.put("isNewAbha", null); + healthDetails.put("isNewAbha", false); } return healthDetails; } From 79b564e04df6b805d255c8288c5757ce2ff5043c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 15:31:19 +0530 Subject: [PATCH 131/450] optmiz code of get all Beneficiary --- .../service/impl/BeneficiaryServiceImpl.java | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) 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 7fc6d1270..0e9f97fb8 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -400,27 +400,28 @@ private void applyAgeCalculation(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBenefi private Map getBenHealthDetails(BigInteger benRegId) { Map healthDetails = new HashMap<>(); - if (benRegId == null) return healthDetails; - - Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); - if (benHealthIdNumber == null || benHealthIdNumber.length == 0) return healthDetails; - - Object[] healthData = (Object[]) benHealthIdNumber[0]; - String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; - String healthId = healthData[1] != null ? healthData[1].toString() : null; - - if (healthIdNumber == null) return healthDetails; - - List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); - if (health != null && !health.isEmpty()) { - Object[] row = health.get(0); // last writer wins anyway; just use first - healthDetails.put("HealthID", row[0]); - healthDetails.put("HealthIdNumber", row[1]); - healthDetails.put("isNewAbha", row[2]); - } else { - healthDetails.put("HealthIdNumber", healthIdNumber); - healthDetails.put("HealthID", healthId); - healthDetails.put("isNewAbha", false); + if (null != benRegId) { + Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + + if (null != healthIdNumber) { + List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); + if (health != null && !health.isEmpty()) { + for (Object[] objects : health) { + healthDetails.put("HealthID", objects[0]); + healthDetails.put("HealthIdNumber", objects[1]); + healthDetails.put("isNewAbha", objects[2]); + } + } else { + healthDetails.put("HealthIdNumber", healthIdNumber); + healthDetails.put("HealthID", healthId); + healthDetails.put("isNewAbha", null); + } + } + } } return healthDetails; } From 95c51378fd2183f1492bae073e9de3e34f4d65bd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 16:06:18 +0530 Subject: [PATCH 132/450] optmiz code of get all Beneficiary --- .../service/impl/BeneficiaryServiceImpl.java | 643 ++++++++++-------- 1 file changed, 344 insertions(+), 299 deletions(-) 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 0e9f97fb8..29a3da48e 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -1,6 +1,8 @@ package com.iemr.flw.service.impl; 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; @@ -12,8 +14,10 @@ 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; @@ -21,6 +25,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @@ -30,6 +35,8 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializer; import com.iemr.flw.domain.identity.BenHealthIDDetails; import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; import com.iemr.flw.domain.identity.RMNCHBornBirthDetails; @@ -45,45 +52,40 @@ import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.identity.HouseHoldRepo; import com.iemr.flw.service.BeneficiaryService; +import com.iemr.flw.utils.config.ConfigProperties; import com.iemr.flw.utils.http.HttpUtils; @Service @Qualifier("rmnchServiceImpl") + public class BeneficiaryServiceImpl implements BeneficiaryService { - private static final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - private static final Gson GSON = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + private final Logger logger = LoggerFactory.getLogger(BeneficiaryServiceImpl.class); + @Value("${door-to-door-page-size}") + private String door_to_door_page_size; - // Map keys as constants to avoid typos and magic strings - private static final String KEY_HOUSEHOLD_DETAILS = "householdDetails"; - private static final String KEY_BORN_BIRTH_DETAILS = "bornBirthDetails"; - private static final String KEY_BENEFICIARY_DETAILS = "beneficiaryDetails"; - private static final String KEY_ABHA_HEALTH_DETAILS = "abhaHealthDetails"; - @Value("${door-to-door-page-size}") - private String doorToDoorPageSize; + private static final Gson GSON = new GsonBuilder() + .setDateFormat("MMM dd, yyyy h:mm:ss a").create(); @Value("${fhir-url}") private String fhirUrl; @Value("${getHealthID}") private String getHealthID; - @Autowired private BeneficiaryRepo beneficiaryRepo; @Autowired private HouseHoldRepo houseHoldRepo; - @Autowired private GeneralOpdRepo generalOpdRepo; @Autowired - private IncentivesRepo incentivesRepo; + IncentivesRepo incentivesRepo; @Autowired - private IncentiveRecordRepo recordRepo; + IncentiveRecordRepo recordRepo; @Autowired private EyeCheckUpVisitRepo eyeCheckUpVisitRepo; @@ -94,303 +96,286 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Autowired private UserServiceRoleRepo userRepo; - // Single shared HttpUtils instance — avoid creating one per request - private final HttpUtils httpUtils = new HttpUtils(); + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + - // ------------------------------------------------------------------------- - // Public API - // ------------------------------------------------------------------------- @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { - if (request == null || request.getAshaId() == null) { + + // ✅ Early validation — no nested if/else pyramid + if (request == null || request.getAshaId() == null) throw new Exception("Invalid/missing village details"); - } - if (request.getPageNo() == null) { + if (request.getPageNo() == null) throw new Exception("Invalid page no"); - } String userName = beneficiaryRepo.getUserName(request.getAshaId()); - if (userName == null || userName.isEmpty()) { + if (userName == null || userName.isEmpty()) throw new Exception("Asha details not found, please contact administrator"); - } + request.setUserName(userName); - int pageSize = Integer.parseInt(doorToDoorPageSize); + int pageSize = Integer.parseInt(door_to_door_page_size); // ✅ parse once PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); - Page page; - if (request.getFromDate() != null && request.getToDate() != null) { - page = beneficiaryRepo.getBenDataWithinDates( - request.getUserName(), request.getFromDate(), request.getToDate(), pr); - } else { - page = beneficiaryRepo.getBenDataByUser(request.getUserName(), pr); - } + // ✅ Ternary to pick query — removes duplicate Page<> variable declarations + Page page = + (request.getFromDate() != null && request.getToDate() != null) + ? beneficiaryRepo.getBenDataWithinDates( + request.getUserName(), request.getFromDate(), request.getToDate(), pr) + : beneficiaryRepo.getBenDataByUser(request.getUserName(), pr); List resultSet = page.getContent(); - if (resultSet.isEmpty()) { - Map emptyResponse = new HashMap<>(); - emptyResponse.put("data", new ArrayList<>()); - emptyResponse.put("pageSize", pageSize); - emptyResponse.put("totalPage", 0); - return GSON.toJson(emptyResponse); - } - return buildBeneficiaryResponse(resultSet, page.getTotalPages(), authorisation); - } - - @Override - public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS) { - if (eyeCheckupRequestDTOS == null || eyeCheckupRequestDTOS.isEmpty()) { - throw new IllegalArgumentException("Eye checkup list must not be empty"); + // ✅ isEmpty() instead of size() > 0 + if (resultSet == null || resultSet.isEmpty()) { + // Return empty response instead of null + Map empty = new HashMap<>(); + empty.put("data", new ArrayList<>()); + empty.put("pageSize", pageSize); + empty.put("totalPage", 0); + return GSON.toJson(empty); } - // Resolve userId once — same ASHA for the whole batch - Integer userId = userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage()); - - List visitsToSave = eyeCheckupRequestDTOS.stream().map(dto -> { - EyeCheckupListDTO f = dto.getFields(); - EyeCheckupVisit visit = new EyeCheckupVisit(); - visit.setBeneficiaryId(dto.getBeneficiaryId()); - visit.setHouseholdId(dto.getHouseHoldId()); - visit.setUserId(userId); - visit.setCreatedBy(dto.getUserName()); - visit.setVisitDate(LocalDate.parse(f.getVisit_date(), FORMATTER)); - visit.setSymptomsObserved(f.getSymptoms_observed()); - visit.setEyeAffected(f.getEye_affected()); - visit.setReferredTo(f.getReferred_to()); - // No-op StringBuilder removed; just use the value directly - visit.setDischargeSummaryUpload(f.getDischarge_summary_upload()); - visit.setFollowUpStatus(f.getFollow_up_status()); - visit.setDateOfSurgery(f.getDate_of_surgery()); - return visit; - }).collect(Collectors.toList()); - - // Batch save instead of one-by-one - eyeCheckUpVisitRepo.saveAll(visitsToSave); - return "Eye checkup data saved successfully."; + return getMappingsForAddressIDs(resultSet, page.getTotalPages(), authorisation); } - @Override - public List getEyeCheckUpVisit(GetBenRequestHandler request) { - List visits = eyeCheckUpVisitRepo.findByUserId(request.getAshaId()); - return visits.stream().map(this::mapVisitToDto).collect(Collectors.toList()); - } +// --------------------------------------------------------------- +// PRIVATE METHOD +// --------------------------------------------------------------- - // ------------------------------------------------------------------------- - // Private helpers - // ------------------------------------------------------------------------- - - private String buildBeneficiaryResponse(List addressList, + private String getMappingsForAddressIDs(List addressList, int totalPage, String authorisation) { - List> resultList = new ArrayList<>(addressList.size()); - for (RMNCHMBeneficiaryaddress address : addressList) { + List> resultList = new ArrayList<>(addressList.size()); // ✅ pre-sized + + for (RMNCHMBeneficiaryaddress a : addressList) { try { - RMNCHMBeneficiarymapping mapping = beneficiaryRepo.getByAddressID(address.getId()); - if (mapping == null) continue; + RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); + if (m == null) continue; // ✅ skip instead of deeply nested if block - Map resultMap = buildResultMap(mapping, authorisation); + Map resultMap = buildResultMap(m, authorisation); resultList.add(resultMap); + } catch (Exception e) { - logger.error("Error processing addressID: {} vanID: {} — {}", - address.getId(), address.getVanID(), e.getMessage(), e); + // ✅ Fixed log format — message was concatenated before addressID making it unreadable + logger.error("Error processing addressID: {}, vanID: {}, reason: {}", + a.getId(), a.getVanID(), e.getMessage()); } } Map response = new HashMap<>(); response.put("data", resultList); - response.put("pageSize", Integer.parseInt(doorToDoorPageSize)); + response.put("pageSize", Integer.parseInt(door_to_door_page_size)); response.put("totalPage", totalPage); - return GSON.toJson(response); + return GSON.toJson(response); // ✅ reuse static GSON instance } - /** - * Builds the complete result map for one beneficiary mapping. - * All sub-fetches are grouped here so the flow is easy to follow. - */ +// --------------------------------------------------------------- +// EXTRACTED: build one beneficiary's result map +// --------------------------------------------------------------- + private Map buildResultMap(RMNCHMBeneficiarymapping m, String authorisation) { + // ---- Fetch sub-objects (null-safe defaults) ---- - RMNCHMBeneficiarydetail benDetail = fetchOrDefault(m.getBenDetailsId(), - beneficiaryRepo::getDetailsById, new RMNCHMBeneficiarydetail()); - RMNCHMBeneficiaryAccount benAccount = fetchOrDefault(m.getBenAccountID(), - beneficiaryRepo::getAccountById, new RMNCHMBeneficiaryAccount()); - RMNCHMBeneficiaryImage benImage = m.getBenImageId() != null + RMNCHMBeneficiarydetail benDetail = m.getBenDetailsId() != null + ? beneficiaryRepo.getDetailsById(m.getBenDetailsId()) : new RMNCHMBeneficiarydetail(); + RMNCHMBeneficiaryAccount benAccount = m.getBenAccountID() != null + ? beneficiaryRepo.getAccountById(m.getBenAccountID()) : new RMNCHMBeneficiaryAccount(); + RMNCHMBeneficiaryImage benImage = m.getBenImageId() != null ? beneficiaryRepo.getImageById(m.getBenImageId().longValue()) : new RMNCHMBeneficiaryImage(); - RMNCHMBeneficiaryaddress benAddress = fetchOrDefault(m.getBenAddressId(), - beneficiaryRepo::getAddressById, new RMNCHMBeneficiaryaddress()); - RMNCHMBeneficiarycontact benContact = fetchOrDefault(m.getBenContactsId(), - beneficiaryRepo::getContactById, new RMNCHMBeneficiarycontact()); + RMNCHMBeneficiaryaddress benAddress = m.getBenAddressId() != null + ? beneficiaryRepo.getAddressById(m.getBenAddressId()) : new RMNCHMBeneficiaryaddress(); + RMNCHMBeneficiarycontact benContact = m.getBenContactsId() != null + ? beneficiaryRepo.getContactById(m.getBenContactsId()) : new RMNCHMBeneficiarycontact(); + + // ---- Protect against null returns from repo ---- + if (benDetail == null) benDetail = new RMNCHMBeneficiarydetail(); + if (benAccount == null) benAccount = new RMNCHMBeneficiaryAccount(); + if (benAddress == null) benAddress = new RMNCHMBeneficiaryaddress(); + if (benContact == null) benContact = new RMNCHMBeneficiarycontact(); BigInteger benID = m.getBenRegId() != null ? beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()) : null; - RMNCHBeneficiaryDetailsRmnch benDetailsRMNCH = new RMNCHBeneficiaryDetailsRmnch(); - RMNCHHouseHoldDetails householdDetails = new RMNCHHouseHoldDetails(); - RMNCHBornBirthDetails bornBirthDetails = new RMNCHBornBirthDetails(); + // ---- RMNCH details + household + birth ---- + RMNCHBeneficiaryDetailsRmnch benRMNCH = new RMNCHBeneficiaryDetailsRmnch(); + RMNCHHouseHoldDetails household = new RMNCHHouseHoldDetails(); + RMNCHBornBirthDetails bornBirth = new RMNCHBornBirthDetails(); if (m.getBenRegId() != null) { RMNCHBeneficiaryDetailsRmnch fetched = beneficiaryRepo.getDetailsByRegID(m.getBenRegId().longValue()); if (fetched != null) { - benDetailsRMNCH = fetched; - if (benDetailsRMNCH.getHouseoldId() != null) { - householdDetails = houseHoldRepo.getByHouseHoldID(benDetailsRMNCH.getHouseoldId()); - } + benRMNCH = fetched; + if (benRMNCH.getHouseoldId() != null) + household = houseHoldRepo.getByHouseHoldID(benRMNCH.getHouseoldId()); } RMNCHBornBirthDetails birth = beneficiaryRepo.getBornBirthByRegID(m.getBenRegId().longValue()); - if (birth != null) bornBirthDetails = birth; + if (birth != null) bornBirth = birth; } - // ---- Merge fields into benDetailsRMNCH ---- - mergeDetailFields(benDetailsRMNCH, benDetail, benAccount, benAddress, benContact, benImage, benID); + // ---- Merge all sub-object fields into benRMNCH ---- + mergeFields(benRMNCH, benDetail, benAccount, benAddress, benContact, benImage, benID); - // ---- Age calculation ---- - applyAgeCalculation(benDetailsRMNCH, benDetail); + // ---- Age ---- + applyAge(benRMNCH, benDetail); - // ---- Health details ---- + // ---- Health details from local DB ---- Map healthDetails = getBenHealthDetails(m.getBenRegId()); - // ---- Assemble result map ---- - Map resultMap = new HashMap<>(); - resultMap.put(KEY_HOUSEHOLD_DETAILS, householdDetails != null ? householdDetails : new HashMap<>()); - resultMap.put(KEY_BORN_BIRTH_DETAILS, bornBirthDetails); - resultMap.put(KEY_BENEFICIARY_DETAILS, benDetailsRMNCH); - resultMap.put(KEY_ABHA_HEALTH_DETAILS, healthDetails); - resultMap.put("houseoldId", benDetailsRMNCH.getHouseoldId()); - resultMap.put("benficieryid", benDetailsRMNCH.getBenficieryid()); - resultMap.put("BenRegId", m.getBenRegId()); - resultMap.put("isDeath", benDetailsRMNCH.getIsDeath()); - resultMap.put("isDeathValue", benDetailsRMNCH.getIsDeathValue()); - resultMap.put("dateOfDeath", benDetailsRMNCH.getDateOfDeath()); - resultMap.put("timeOfDeath", benDetailsRMNCH.getTimeOfDeath()); - resultMap.put("reasonOfDeath", benDetailsRMNCH.getReasonOfDeath()); - resultMap.put("reasonOfDeathId", benDetailsRMNCH.getReasonOfDeathId()); - resultMap.put("placeOfDeath", benDetailsRMNCH.getPlaceOfDeath()); - resultMap.put("placeOfDeathId", benDetailsRMNCH.getPlaceOfDeathId()); - resultMap.put("isSpouseAdded", benDetailsRMNCH.getIsSpouseAdded()); - resultMap.put("isChildrenAdded", benDetailsRMNCH.getIsChildrenAdded()); - resultMap.put("noOfchildren", benDetailsRMNCH.getNoOfchildren()); - resultMap.put("isMarried", benDetailsRMNCH.getIsMarried()); - resultMap.put("doYouHavechildren", benDetailsRMNCH.getDoYouHavechildren()); - resultMap.put("noofAlivechildren", benDetailsRMNCH.getNoofAlivechildren()); // typo fixed (no trailing spaces) - - // ASHA id from address creator + // ---- Build result map ---- + Map map = new HashMap<>(); + map.put("householdDetails", household != null ? household : new HashMap<>()); + map.put("bornbirthDeatils", bornBirth != null ? bornBirth : new HashMap<>()); // key kept as-is for backward compat + map.put("beneficiaryDetails", benRMNCH); + map.put("abhaHealthDetails", healthDetails); + map.put("houseoldId", benRMNCH.getHouseoldId()); + map.put("benficieryid", benRMNCH.getBenficieryid()); + map.put("isDeath", benRMNCH.getIsDeath()); + map.put("isDeathValue", benRMNCH.getIsDeathValue()); + map.put("dateOfDeath", benRMNCH.getDateOfDeath()); + map.put("timeOfDeath", benRMNCH.getTimeOfDeath()); + map.put("reasonOfDeath", benRMNCH.getReasonOfDeath()); + map.put("reasonOfDeathId", benRMNCH.getReasonOfDeathId()); + map.put("placeOfDeath", benRMNCH.getPlaceOfDeath()); + map.put("placeOfDeathId", benRMNCH.getPlaceOfDeathId()); + map.put("isSpouseAdded", benRMNCH.getIsSpouseAdded()); + map.put("isChildrenAdded", benRMNCH.getIsChildrenAdded()); + map.put("noOfchildren", benRMNCH.getNoOfchildren()); + map.put("isMarried", benRMNCH.getIsMarried()); + map.put("doYouHavechildren", benRMNCH.getDoYouHavechildren()); + map.put("noofAlivechildren", benRMNCH.getNoofAlivechildren()); // ✅ trailing spaces removed + map.put("isDeactivate", benRMNCH.getIsDeactivate()); + map.put("BenRegId", m.getBenRegId()); + + // ✅ ASHA id lookup if (benAddress.getCreatedBy() != null) { Integer userID = beneficiaryRepo.getUserIDByUserName(benAddress.getCreatedBy()); - if (userID != null && userID > 0) resultMap.put("ashaId", userID); + if (userID != null && userID > 0) map.put("ashaId", userID); } - // External ABHA fetch - if (m.getBenRegId() != null) { - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); - } + // ✅ External ABHA fetch + if (m.getBenRegId() != null) + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, map); - return resultMap; + return map; } - /** Copies all mergeable fields from sub-objects into the RMNCH details object. */ - private void mergeDetailFields(RMNCHBeneficiaryDetailsRmnch dest, - RMNCHMBeneficiarydetail detail, - RMNCHMBeneficiaryAccount account, - RMNCHMBeneficiaryaddress address, - RMNCHMBeneficiarycontact contact, - RMNCHMBeneficiaryImage image, - BigInteger benID) { - // Personal - setIfNotNull(detail.getFirstName(), dest::setFirstName); - setIfNotNull(detail.getLastName(), dest::setLastName); - setIfNotNull(detail.getMotherName(), dest::setMotherName); - setIfNotNull(detail.getFatherName(), dest::setFatherName); - setIfNotNull(detail.getSpousename(), dest::setSpousename); - setIfNotNull(detail.getDob(), dest::setDob); - setIfNotNull(detail.getGender(), dest::setGender); - setIfNotNull(detail.getGenderId(), dest::setGenderId); - setIfNotNull(detail.getMaritalstatus(), dest::setMaritalstatus); - setIfNotNull(detail.getMaritalstatusId(),dest::setMaritalstatusId); - setIfNotNull(detail.getMarriageDate(), dest::setMarriageDate); - setIfNotNull(detail.getLiteracyStatus(), dest::setLiteracyStatus); - setIfNotNull(detail.getCommunity(), dest::setCommunity); - setIfNotNull(detail.getCommunityId(), dest::setCommunityId); - setIfNotNull(detail.getReligion(), dest::setReligion); - setIfNotNull(detail.getReligionID(), dest::setReligionID); - if (dest.getCreatedBy() == null) setIfNotNull(detail.getCreatedBy(), dest::setCreatedBy); - - // Bank - setIfNotNull(account.getNameOfBank(), dest::setNameOfBank); - setIfNotNull(account.getBranchName(), dest::setBranchName); - setIfNotNull(account.getIfscCode(), dest::setIfscCode); - setIfNotNull(account.getBankAccount(), dest::setBankAccount); - - // Address - setIfNotNull(address.getCountyid(), dest::setCountryId); - setIfNotNull(address.getPermCountry(), dest::setCountryName); - setIfNotNull(address.getStatePerm(), dest::setStateId); - setIfNotNull(address.getPermState(), dest::setStateName); - setIfNotNull(address.getDistrictidPerm(), dest::setDistrictid); - setIfNotNull(address.getDistrictnamePerm(), dest::setDistrictname); - setIfNotNull(address.getPermSubDistrictId(), dest::setBlockId); - setIfNotNull(address.getPermSubDistrict(), dest::setBlockName); - setIfNotNull(address.getVillageidPerm(), dest::setVillageId); - setIfNotNull(address.getVillagenamePerm(), dest::setVillageName); - setIfNotNull(address.getPermServicePointId(), dest::setServicePointID); - setIfNotNull(address.getPermServicePoint(), dest::setServicePointName); - setIfNotNull(address.getPermZoneID(), dest::setZoneID); - setIfNotNull(address.getPermZone(), dest::setZoneName); - setIfNotNull(address.getPermAddrLine1(), dest::setAddressLine1); - setIfNotNull(address.getPermAddrLine2(), dest::setAddressLine2); - setIfNotNull(address.getPermAddrLine3(), dest::setAddressLine3); +// --------------------------------------------------------------- +// EXTRACTED: merge all sub-object fields into RMNCH object +// replaces ~50 repetitive if (x != null) dest.setX(x) blocks +// --------------------------------------------------------------- + + private void mergeFields(RMNCHBeneficiaryDetailsRmnch d, + RMNCHMBeneficiarydetail detail, + RMNCHMBeneficiaryAccount account, + RMNCHMBeneficiaryaddress address, + RMNCHMBeneficiarycontact contact, + RMNCHMBeneficiaryImage image, + BigInteger benID) { + + // Personal details + ifNotNull(detail.getFirstName(), d::setFirstName); + ifNotNull(detail.getLastName(), d::setLastName); + ifNotNull(detail.getMotherName(), d::setMotherName); + ifNotNull(detail.getFatherName(), d::setFatherName); + ifNotNull(detail.getSpousename(), d::setSpousename); + ifNotNull(detail.getDob(), d::setDob); + ifNotNull(detail.getGender(), d::setGender); + ifNotNull(detail.getGenderId(), d::setGenderId); + ifNotNull(detail.getMaritalstatus(), d::setMaritalstatus); + ifNotNull(detail.getMaritalstatusId(), d::setMaritalstatusId); + ifNotNull(detail.getMarriageDate(), d::setMarriageDate); + ifNotNull(detail.getLiteracyStatus(), d::setLiteracyStatus); + ifNotNull(detail.getCommunity(), d::setCommunity); + ifNotNull(detail.getCommunityId(), d::setCommunityId); + ifNotNull(detail.getReligion(), d::setReligion); + ifNotNull(detail.getReligionID(), d::setReligionID); + // createdBy — only set if not already populated from RMNCH fetch + if (d.getCreatedBy() == null) ifNotNull(detail.getCreatedBy(), d::setCreatedBy); + + // Bank details + ifNotNull(account.getNameOfBank(), d::setNameOfBank); + ifNotNull(account.getBranchName(), d::setBranchName); + ifNotNull(account.getIfscCode(), d::setIfscCode); + ifNotNull(account.getBankAccount(), d::setBankAccount); + + // Address / location + ifNotNull(address.getCountyid(), d::setCountryId); + ifNotNull(address.getPermCountry(), d::setCountryName); + ifNotNull(address.getStatePerm(), d::setStateId); + ifNotNull(address.getPermState(), d::setStateName); + ifNotNull(address.getDistrictidPerm(), d::setDistrictid); + ifNotNull(address.getDistrictnamePerm(), d::setDistrictname); + ifNotNull(address.getPermSubDistrictId(), d::setBlockId); + ifNotNull(address.getPermSubDistrict(), d::setBlockName); + ifNotNull(address.getVillageidPerm(), d::setVillageId); + ifNotNull(address.getVillagenamePerm(), d::setVillageName); + ifNotNull(address.getPermServicePointId(), d::setServicePointID); + ifNotNull(address.getPermServicePoint(), d::setServicePointName); + ifNotNull(address.getPermZoneID(), d::setZoneID); + ifNotNull(address.getPermZone(), d::setZoneName); + ifNotNull(address.getPermAddrLine1(), d::setAddressLine1); + ifNotNull(address.getPermAddrLine2(), d::setAddressLine2); + ifNotNull(address.getPermAddrLine3(), d::setAddressLine3); // Contact - setIfNotNull(contact.getPreferredPhoneNum(), dest::setContact_number); + ifNotNull(contact.getPreferredPhoneNum(), d::setContact_number); // Image - if (image != null) setIfNotNull(image.getUser_image(), dest::setUser_image); + if (image != null) ifNotNull(image.getUser_image(), d::setUser_image); // Ben ID - if (benID != null) dest.setBenficieryid(benID.longValue()); + if (benID != null) d.setBenficieryid(benID.longValue()); - // Related beneficiary IDs - if (dest.getRelatedBeneficiaryIdsDB() != null) { - String[] parts = dest.getRelatedBeneficiaryIdsDB().split(","); + // Related beneficiary IDs — split CSV string into Long[] + if (d.getRelatedBeneficiaryIdsDB() != null) { + String[] parts = d.getRelatedBeneficiaryIdsDB().split(","); Long[] ids = new Long[parts.length]; - for (int i = 0; i < parts.length; i++) ids[i] = Long.valueOf(parts[i].trim()); - dest.setRelatedBeneficiaryIds(ids); + for (int i = 0; i < parts.length; i++) + ids[i] = Long.valueOf(parts[i].trim()); + d.setRelatedBeneficiaryIds(ids); } } - /** Calculates age from DOB and sets ageFull, age, and age_unit on the destination object. */ - private void applyAgeCalculation(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBeneficiarydetail detail) { - if (detail.getDob() == null) return; +// --------------------------------------------------------------- +// EXTRACTED: age calculation +// --------------------------------------------------------------- + + private void applyAge(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBeneficiarydetail detail) { + if (detail.getDob() == null) { + dest.setAgeFull(""); + dest.setAge(0); + return; + } Calendar cal = Calendar.getInstance(); cal.setTime(detail.getDob()); - LocalDate birthDate = LocalDate.of( + LocalDate birth = LocalDate.of( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH)); - Period p = Period.between(birthDate, LocalDate.now()); - int years = p.getYears(); - int months = p.getMonths(); - int days = p.getDays(); + Period p = Period.between(birth, LocalDate.now()); + int y = p.getYears(), mo = p.getMonths(), d = p.getDays(); String ageFull; int ageVal; String ageUnit; - if (years > 0) { - ageFull = years + " years - " + months + " months"; - ageVal = years; - ageUnit = years > 1 ? "Years" : "Year"; - } else if (months > 0) { - ageFull = months + " months - " + days + " days"; - ageVal = months; - ageUnit = months > 1 ? "Months" : "Month"; + if (y > 0) { + ageFull = y + " years - " + mo + " months"; + ageVal = y; + ageUnit = y > 1 ? "Years" : "Year"; + } else if (mo > 0) { + ageFull = mo + " months - " + d + " days"; + ageVal = mo; + ageUnit = mo > 1 ? "Months" : "Month"; } else { - ageFull = days + " days"; - ageVal = days; - ageUnit = days > 1 ? "Days" : "Day"; + ageFull = d + " days"; + ageVal = d; + ageUnit = d > 1 ? "Days" : "Day"; } dest.setAgeFull(ageFull); @@ -398,99 +383,159 @@ private void applyAgeCalculation(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBenefi dest.setAge_unit(ageUnit); } - private Map getBenHealthDetails(BigInteger benRegId) { +// --------------------------------------------------------------- +// UTILITY: replaces 50+ repetitive if-not-null setter blocks +// --------------------------------------------------------------- + + private void ifNotNull(T value, java.util.function.Consumer setter) { + if (value != null) setter.accept(value); + } + + private Map getBenHealthDetails(BigInteger benRegId) { + Map healthDetails = new HashMap<>(); + if (null != benRegId) { + Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + + if (null != healthIdNumber) { + List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); + if (health != null && !health.isEmpty()) { + for (Object[] objects : health) { + healthDetails.put("HealthID", objects[0]); + healthDetails.put("HealthIdNumber", objects[1]); + healthDetails.put("isNewAbha", objects[2]); + } + } else { + healthDetails.put("HealthIdNumber", healthIdNumber); + healthDetails.put("HealthID", healthId); + healthDetails.put("isNewAbha", null); + } + } + } + } + return healthDetails; + } + + private Map getBenBenVisitDetails(BigInteger benRegId) { Map healthDetails = new HashMap<>(); if (null != benRegId) { - Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); - if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { - Object[] healthData = (Object[]) benHealthIdNumber[0]; - String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; - String healthId = healthData[1] != null ? healthData[1].toString() : null; - - if (null != healthIdNumber) { - List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); - if (health != null && !health.isEmpty()) { - for (Object[] objects : health) { - healthDetails.put("HealthID", objects[0]); - healthDetails.put("HealthIdNumber", objects[1]); - healthDetails.put("isNewAbha", objects[2]); - } - } else { - healthDetails.put("HealthIdNumber", healthIdNumber); - healthDetails.put("HealthID", healthId); - healthDetails.put("isNewAbha", null); - } + 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 requestBody = new HashMap<>(); - requestBody.put("beneficiaryRegID", benRegID); - requestBody.put("beneficiaryID", null); - + public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { + Map requestMap = new HashMap(); + requestMap.put("beneficiaryRegID", benRegID); + requestMap.put("beneficiaryID", null); + JsonParser jsnParser = new JsonParser(); + HttpUtils utils = new HttpUtils(); + List result = null; try { - HashMap headers = new HashMap<>(); - headers.put("Authorization", authorization); - String responseStr = httpUtils.post(fhirUrl + "/" + getHealthID, GSON.toJson(requestBody), headers); + HashMap header = new HashMap(); + header.put("Authorization", authorization); + String responseStr = utils.post(fhirUrl + "/" + + getHealthID, new Gson().toJson(requestMap), header); + JsonElement jsnElmnt = jsnParser.parse(responseStr); + JsonObject jsnOBJ = new JsonObject(); + jsnOBJ = jsnElmnt.getAsJsonObject(); + if (jsnOBJ.get("data") != null && jsnOBJ.get("data").getAsJsonObject().get("BenHealthDetails") != null) { + result = new ArrayList(); + BenHealthIDDetails[] ben = InputMapper.gson().fromJson( + new Gson().toJson(jsnOBJ.get("data").getAsJsonObject().get("BenHealthDetails")), + BenHealthIDDetails[].class); + for (BenHealthIDDetails value : ben) { + if (value.getHealthId() != null) + resultMap.put("healthId", value.getHealthId()); + if (value.getHealthIdNumber() != null) + resultMap.put("healthIdNumber", value.getHealthIdNumber()); + } + } + + } catch (Exception e) { + logger.info("Error while fetching ABHA" + e.getMessage()); +// return null; + } - JsonElement element = JsonParser.parseString(responseStr); // non-deprecated API - if (!element.isJsonObject()) return; +// return result; - JsonObject root = element.getAsJsonObject(); - if (root.get("data") == null) return; + } - JsonObject data = root.getAsJsonObject("data"); - if (data.get("BenHealthDetails") == null) return; - BenHealthIDDetails[] details = InputMapper.gson().fromJson( - GSON.toJson(data.get("BenHealthDetails")), BenHealthIDDetails[].class); + @Override + public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS) { - for (BenHealthIDDetails d : details) { - if (d.getHealthId() != null) resultMap.put("healthId", d.getHealthId()); - if (d.getHealthIdNumber() != null) resultMap.put("healthIdNumber", d.getHealthIdNumber()); + try { + for (EyeCheckupRequestDTO dto : eyeCheckupRequestDTOS) { + EyeCheckupVisit visit = new EyeCheckupVisit(); + + visit.setBeneficiaryId(dto.getBeneficiaryId()); + visit.setHouseholdId(dto.getHouseHoldId()); + visit.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); // cache se lena hai + 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) { - logger.warn("Failed to fetch ABHA for benRegID {}: {}", benRegID, e.getMessage()); - } - } + e.printStackTrace(); - private EyeCheckupRequestDTO mapVisitToDto(EyeCheckupVisit 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; + } + return null ; } - // ------------------------------------------------------------------------- - // Generic utilities - // ------------------------------------------------------------------------- + @Override + public List getEyeCheckUpVisit(GetBenRequestHandler request) { + List visits = eyeCheckUpVisitRepo.findByUserId(request.getAshaId()); - /** Calls setter only when value is non-null — replaces the repetitive if-blocks. */ - private void setIfNotNull(T value, java.util.function.Consumer setter) { - if (value != null) setter.accept(value); + 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()); } - /** Fetches an entity by ID; returns defaultValue when ID is null. */ - private T fetchOrDefault(ID id, java.util.function.Function fetcher, T defaultValue) { - if (id == null) return defaultValue; - T result = fetcher.apply(id); - return result != null ? result : defaultValue; - } -} \ No newline at end of file + +} From 3a226a8afee30c18bb1c9f3d41ed00c327bc9c9c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 16:28:47 +0530 Subject: [PATCH 133/450] optmiz code of get all Beneficiary --- .../java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java | 7 ++++--- .../java/com/iemr/flw/utils/JwtAuthenticationUtil.java | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) 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 d3ac8edfb..9e45788a6 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java @@ -1,12 +1,13 @@ 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.M_User; @Repository public interface EmployeeMasterRepo extends JpaRepository { - M_User findByUserID(Integer userID); - - M_User getUserByUserID(Integer parseLong); + @Query("SELECT u FROM User u WHERE u.userID = :userID and u.deleted=false and u.statusID in (1, 2)") + M_User findUserByUserID(@Param("userID") Integer userID); } diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 9144ca3be..042e3839b 100644 --- a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java @@ -109,7 +109,7 @@ private M_User fetchUserFromDB(String userId) { String redisKey = "user_" + userId; // Redis key format // Fetch user from DB - M_User user = userLoginRepo.getUserByUserID(Integer.parseInt(userId)); + M_User user = userLoginRepo.findUserByUserID(Integer.parseInt(userId)); if (user != null) { M_User userHash = new M_User(); From 10ab15f79bae36403dbde991411b513d909cd71a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 16:32:39 +0530 Subject: [PATCH 134/450] optmiz code of get all Beneficiary --- src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9e45788a6..2db2b2005 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java @@ -8,6 +8,6 @@ import com.iemr.flw.domain.iemr.M_User; @Repository public interface EmployeeMasterRepo extends JpaRepository { - @Query("SELECT u FROM User u WHERE u.userID = :userID and u.deleted=false and u.statusID in (1, 2)") + @Query("SELECT u FROM M_User u WHERE u.userID = :userID and u.deleted=false and u.statusID in (1, 2)") M_User findUserByUserID(@Param("userID") Integer userID); } From c1ec40d7d6924f16863c9de40428658285fb6e48 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 16:35:48 +0530 Subject: [PATCH 135/450] optmiz code of get all Beneficiary --- src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 042e3839b..46b35eb41 100644 --- a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java @@ -81,7 +81,7 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { user = fetchUserFromDB(userId); } if (user == null) { - throw new IEMRException("Invalid User ID."); + throw new IEMRException("Invalid User ID or user is deactivated please contact to admin."); } return true; // Valid userId and JWT token From 7fd16447611ca5490a1845e9b5a1a403c0cee8b7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 16:47:45 +0530 Subject: [PATCH 136/450] optmiz code of get all Beneficiary --- .../flw/controller/AshaProfileController.java | 14 -------------- .../flw/domain/iemr/{M_User.java => User.java} | 17 ++++------------- .../iemr/flw/repo/iemr/EmployeeMasterRepo.java | 9 +++++---- .../iemr/flw/service/EmployeeMasterInter.java | 6 +++--- .../iemr/flw/service/impl/AshaProfileImpl.java | 12 ++---------- .../flw/service/impl/EmployeeMasterImpl.java | 8 ++++---- .../impl/NotificationSchedulerService.java | 10 ++-------- .../flw/service/impl/SmsSchedulerService.java | 11 ++--------- .../iemr/flw/utils/JwtAuthenticationUtil.java | 14 +++++++------- .../com/iemr/flw/utils/redis/RedisConfig.java | 4 ++-- 10 files changed, 31 insertions(+), 74 deletions(-) rename src/main/java/com/iemr/flw/domain/iemr/{M_User.java => User.java} (91%) diff --git a/src/main/java/com/iemr/flw/controller/AshaProfileController.java b/src/main/java/com/iemr/flw/controller/AshaProfileController.java index 1bda44990..cedfcda06 100644 --- a/src/main/java/com/iemr/flw/controller/AshaProfileController.java +++ b/src/main/java/com/iemr/flw/controller/AshaProfileController.java @@ -1,35 +1,21 @@ 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") diff --git a/src/main/java/com/iemr/flw/domain/iemr/M_User.java b/src/main/java/com/iemr/flw/domain/iemr/User.java similarity index 91% rename from src/main/java/com/iemr/flw/domain/iemr/M_User.java rename to src/main/java/com/iemr/flw/domain/iemr/User.java index 0187a6134..d422f9262 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/M_User.java +++ b/src/main/java/com/iemr/flw/domain/iemr/User.java @@ -1,7 +1,6 @@ package com.iemr.flw.domain.iemr; import java.sql.Timestamp; -import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.Expose; @@ -14,18 +13,10 @@ 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 { - +public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Expose @@ -144,11 +135,11 @@ public class M_User { @Column(name = "failed_attempt", insertable = false) private Integer failedAttempt; - public M_User() { + public User() { // TODO Auto-generated constructor stub } - public M_User(Integer userID, String userName) { + public User(Integer userID, String userName) { // TODO Auto-generated constructor stub this.userID = userID; this.userName = userName; 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 2db2b2005..943b43b12 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EmployeeMasterRepo.java @@ -2,12 +2,13 @@ import org.springframework.data.jpa.repository.JpaRepository; 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 com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.User; @Repository -public interface EmployeeMasterRepo extends JpaRepository { - @Query("SELECT u FROM M_User u WHERE u.userID = :userID and u.deleted=false and u.statusID in (1, 2)") - M_User findUserByUserID(@Param("userID") Integer userID); +public interface EmployeeMasterRepo extends JpaRepository { + @Query("SELECT u FROM User u WHERE u.userID = :userID and u.deleted=false and u.statusID in (1, 2)") + User findUserByUserID(@Param("userID") Integer userID); } diff --git a/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java b/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java index 1c4369dac..4e81445ce 100644 --- a/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java +++ b/src/main/java/com/iemr/flw/service/EmployeeMasterInter.java @@ -1,13 +1,13 @@ package com.iemr.flw.service; -import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.User; import org.springframework.stereotype.Service; import java.util.List; @Service public interface EmployeeMasterInter { - public M_User getUserDetails(Integer userID); + public User getUserDetails(Integer userID); - List getAllUsers(); + List getAllUsers(); } diff --git a/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java index 29ca30da1..df86d7ec7 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java @@ -1,19 +1,15 @@ 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.domain.iemr.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; @@ -24,10 +20,6 @@ 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 { @@ -96,7 +88,7 @@ public AshaWorker getProfileData(Integer userId) { private AshaWorker getDetails(Integer userID) { try { - M_User m_user = Objects.requireNonNull(employeeMasterInter.getUserDetails(userID), "User details not found for ID: " + userID); + 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 diff --git a/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java b/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java index 2f67fc2b3..acf7836c5 100644 --- a/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/EmployeeMasterImpl.java @@ -1,6 +1,6 @@ package com.iemr.flw.service.impl; -import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.User; import com.iemr.flw.repo.iemr.EmployeeMasterRepo; import com.iemr.flw.service.EmployeeMasterInter; @@ -19,13 +19,13 @@ public class EmployeeMasterImpl implements EmployeeMasterInter { @Override - public M_User getUserDetails(Integer userID) { + public 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); + return employeeMasterRepo.findUserByUserID(userID); } catch (Exception e) { logger.error("Error fetching user details for userID: {}", userID, e); throw e; @@ -33,7 +33,7 @@ public M_User getUserDetails(Integer userID) { } @Override - public List getAllUsers() { + public List getAllUsers() { return employeeMasterRepo.findAll(); } } diff --git a/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java b/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java index a5b6dd779..21d0da458 100644 --- a/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java +++ b/src/main/java/com/iemr/flw/service/impl/NotificationSchedulerService.java @@ -1,19 +1,13 @@ package com.iemr.flw.service.impl; -import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.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 { @@ -61,7 +55,7 @@ public void triggerAncRemindersForAllAsha() { @Scheduled(cron = "0 0 9 * * *") public void trigerTomorrowImmunizationReminders() { - for(M_User m_user: employeeMasterInter.getAllUsers()){ + for(User m_user: employeeMasterInter.getAllUsers()){ childCareService.getTomorrowImmunizationReminders(m_user.getUserID()); } diff --git a/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java b/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java index 637d011a2..90b57fdd3 100644 --- a/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java +++ b/src/main/java/com/iemr/flw/service/impl/SmsSchedulerService.java @@ -2,22 +2,16 @@ 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.domain.iemr.User; 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; @@ -25,7 +19,6 @@ import java.time.ZoneId; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; @Service public class SmsSchedulerService { @@ -94,7 +87,7 @@ public void sendAncReminders() { @Scheduled(cron = "0 0 9 * * *") public void trigerTomorrowImmunizationReminders() { - for (M_User m_user : employeeMasterInter.getAllUsers()) { + for (User m_user : employeeMasterInter.getAllUsers()) { childCareService.getTomorrowImmunizationReminders(m_user.getUserID()); } diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 46b35eb41..5a9f76bf8 100644 --- a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java @@ -11,7 +11,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.User; import com.iemr.flw.repo.iemr.EmployeeMasterRepo; import com.iemr.flw.utils.exception.IEMRException; @@ -75,7 +75,7 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { String userId = claims.get("userId", String.class); // Check if user data is present in Redis - M_User user = getUserFromCache(userId); + User user = getUserFromCache(userId); if (user == null) { // If not in Redis, fetch from DB and cache the result user = fetchUserFromDB(userId); @@ -91,9 +91,9 @@ public boolean validateUserIdAndJwtToken(String jwtToken) throws IEMRException { } } - private M_User getUserFromCache(String userId) { + private User getUserFromCache(String userId) { String redisKey = "user_" + userId; // The Redis key format - M_User user = (M_User) redisTemplate.opsForValue().get(redisKey); + User user = (User) redisTemplate.opsForValue().get(redisKey); if (user == null) { logger.warn("User not found in Redis. Will try to fetch from DB."); @@ -104,15 +104,15 @@ private M_User getUserFromCache(String userId) { return user; // Returns null if not found } - private M_User fetchUserFromDB(String userId) { + private User fetchUserFromDB(String userId) { // This method will only be called if the user is not found in Redis. String redisKey = "user_" + userId; // Redis key format // Fetch user from DB - M_User user = userLoginRepo.findUserByUserID(Integer.parseInt(userId)); + User user = userLoginRepo.findUserByUserID(Integer.parseInt(userId)); if (user != null) { - M_User userHash = new M_User(); + User userHash = new User(); userHash.setUserID(user.getUserID()); userHash.setUserName(user.getUserName()); 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 0a2793198..98acde7ac 100644 --- a/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java +++ b/src/main/java/com/iemr/flw/utils/redis/RedisConfig.java @@ -7,7 +7,7 @@ import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; -import com.iemr.flw.domain.iemr.M_User; +import com.iemr.flw.domain.iemr.User; @Configuration public class RedisConfig { @@ -20,7 +20,7 @@ public RedisTemplate redisTemplate(RedisConnectionFactory factor template.setKeySerializer(new StringRedisSerializer()); // Use Jackson2JsonRedisSerializer for values (Users objects) - Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(M_User.class); + Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(User.class); template.setValueSerializer(serializer); return template; From e4da85aa2b8deca848d9fee1cf94e4e99f6da360 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 17:55:39 +0530 Subject: [PATCH 137/450] optmiz code of get all Beneficiary --- .../flw/service/impl/IncentiveServiceImpl.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) 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 33f8ac1d2..480b51748 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -198,10 +198,12 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { + logger.info("run--1"); if (pendingActivityDTO == null) { return "Invalid request"; } + logger.info("run--2"); IncentiveName incentiveName; try { @@ -209,12 +211,16 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } catch (IllegalArgumentException e) { return "Invalid incentive name"; } + logger.info("run--3"); + IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup( pendingActivityDTO.getActivityName(), pendingActivityDTO.getModuleName() ); + logger.info("run--3"); + if (incentiveActivity == null) { return null; @@ -226,20 +232,24 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { pendingActivityDTO.getId(), incentiveActivity.getId() ); + logger.info("run--4"); if (!optionalPendingActivity.isPresent()) { return null; } + logger.info("run--5"); IncentivePendingActivity existingActivity = optionalPendingActivity.get(); if (!existingActivity.getActivityId().equals(pendingActivityDTO.getId())) { return null; } + logger.info("run--6"); if (pendingActivityDTO.getImages() == null || pendingActivityDTO.getImages().isEmpty()) { return null; } + logger.info("run--7"); try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); @@ -251,7 +261,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { // ✅ ENUM BASED CHECK if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ - if (incentiveName.name() == IncentiveName.MAA_QUARTERLY_MEETING.name()) { + if (Objects.equals(incentiveName.name(), IncentiveName.MAA_QUARTERLY_MEETING.name())) { maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, @@ -284,6 +294,8 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } catch (Exception e) { + logger.info("run--last"+e.getMessage()); + return e.getMessage(); } From 3ca37275f853b9189020d96011730071fb9d787b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 18:06:19 +0530 Subject: [PATCH 138/450] optmiz code of get all Beneficiary --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 480b51748..5266eaa25 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -229,8 +229,8 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { Optional optionalPendingActivity = incentivePendingActivityRepository .findByMincentiveIdAndActivityId( - pendingActivityDTO.getId(), - incentiveActivity.getId() + incentiveActivity.getId(), + pendingActivityDTO.getId() ); logger.info("run--4"); From 56d7e9c5705e9a2c75632bc963b59d4849de2bd8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 18:14:40 +0530 Subject: [PATCH 139/450] optmiz code of get all Beneficiary --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 + 1 file changed, 1 insertion(+) 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 5266eaa25..aac6f3e6e 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -253,6 +253,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); + maaMeetingRequestDTO.setId(existingActivity.getRecordId()); maaMeetingRequestDTO.setMeetingImages( pendingActivityDTO.getImages().toArray(new MultipartFile[0]) ); From e324e00fcf1e34a61ff12f68343459f24952cd7f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 18:22:24 +0530 Subject: [PATCH 140/450] optmiz code of get all Beneficiary --- .../service/impl/IncentiveServiceImpl.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) 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 aac6f3e6e..e1a5ed3e7 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -3,10 +3,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; -import com.iemr.flw.domain.iemr.IncentiveActivity; -import com.iemr.flw.domain.iemr.IncentiveActivityLangMapping; -import com.iemr.flw.domain.iemr.IncentiveActivityRecord; -import com.iemr.flw.domain.iemr.IncentivePendingActivity; +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; @@ -264,28 +261,38 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ if (Objects.equals(incentiveName.name(), IncentiveName.MAA_QUARTERLY_MEETING.name())) { - maaMeetingService.updateMeetingFromFileUpload( + MaaMeeting meeting= maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, pendingActivityDTO.getId() ); + if(meeting!=null){ + return "Incentive update successfully"; + } } }else { if (incentiveName.name().equals(IncentiveName.MAA_QUARTERLY_MEETING.name())) { - maaMeetingService.updateMeetingFromFileUpload( + MaaMeeting meeting = maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, pendingActivityDTO.getId() ); + if(meeting!=null){ + return "Incentive update successfully"; + } + } if (incentiveName.name().equals(IncentiveName.HBNC_0_42_DAYS.name())) { - childCareService.updateHbncFromFileUpload( + HbncVisit hbncVisit= childCareService.updateHbncFromFileUpload( pendingActivityDTO.getImages().toArray(new MultipartFile[0]), pendingActivityDTO.getId(), existingActivity.getRecordId() ); + if(hbncVisit!=null){ + return "Incentive update successfully"; + } } From d61625e8391087e3e36e4d59fca8ebc16840cf67 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Feb 2026 18:29:36 +0530 Subject: [PATCH 141/450] optmiz code of get all Beneficiary --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 e1a5ed3e7..8ee38dc2d 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -172,7 +172,6 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { if (entry.getName() == null) { if (entry.getBenId() != 0 && entry.getBenId() > 0L) { Long regId = beneficiaryRepo.getBenRegIdFromBenId(entry.getBenId()); - logger.info("rmnchBeneficiaryDetailsRmnch" + regId); BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(regId)).getBenDetailsId(); RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); String beneName = rmnchBeneficiaryDetails.getFirstName() + " " + rmnchBeneficiaryDetails.getLastName(); From ed03ce073a711c93c80a675f8abe31d2fe774eb1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 15:11:23 +0530 Subject: [PATCH 142/450] optmiz code of get all Beneficiary --- src/main/java/com/iemr/flw/repo/iemr/DeliveryOutcomeRepo.java | 2 ++ .../com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/DeliveryOutcomeRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DeliveryOutcomeRepo.java index 643d7c9ab..cf09f625d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/DeliveryOutcomeRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/DeliveryOutcomeRepo.java @@ -16,5 +16,7 @@ public interface DeliveryOutcomeRepo extends JpaRepository getDeliveryOutcomeByAshaId(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + List findByCreatedBy(String userName); + DeliveryOutcome findDeliveryOutcomeByBenIdAndIsActive(Long benId, Boolean isActive); } 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 0e329f4bf..63f86c9a0 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -109,7 +109,7 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT public List getDeliveryOutcome(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user, dto.getFromDate(), dto.getToDate()); + List deliveryOutcomeList = deliveryOutcomeRepo.findByCreatedBy(user); return deliveryOutcomeList.stream() .map(deliveryOutcome -> mapper.convertValue(deliveryOutcome, DeliveryOutcomeDTO.class)) .collect(Collectors.toList()); From 94e4aff80b233292723babd123ae4f5803d331d8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 15:29:02 +0530 Subject: [PATCH 143/450] optmiz code of get all Beneficiary --- src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java index eb8b0107f..d6bcd7b6c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java @@ -45,7 +45,7 @@ public class ScreeningKalaAzar { @Column(name = "house_hold_details_Id",nullable = false) private Long houseHoldDetailsId; - @Column(name = "userID") + @Column(name = "user_id") private Integer userId; @Temporal(TemporalType.DATE) @@ -97,7 +97,7 @@ public class ScreeningKalaAzar { @Column(name = "created_by") private String createdBy; - @Column(name = "diseaseTypeID") + @Column(name = "disease_type_id") private Integer diseaseTypeId; @Column(name = "refer_to_name") From d8f3a0d03703bfaf77114cbd6614bd8a3ede0b45 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 22:55:27 +0530 Subject: [PATCH 144/450] fix DeliveryOutcome data issue --- .../service/impl/BeneficiaryServiceImpl.java | 641 ++++++++++-------- 1 file changed, 344 insertions(+), 297 deletions(-) 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 29a3da48e..dbbe40e74 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -64,10 +64,6 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Value("${door-to-door-page-size}") private String door_to_door_page_size; - - private static final Gson GSON = new GsonBuilder() - .setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - @Value("${fhir-url}") private String fhirUrl; @@ -102,65 +98,334 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { + String outputResponse = null; + int totalPage = 0; - // ✅ Early validation — no nested if/else pyramid - if (request == null || request.getAshaId() == null) - throw new Exception("Invalid/missing village details"); - if (request.getPageNo() == null) - throw new Exception("Invalid page no"); - - String userName = beneficiaryRepo.getUserName(request.getAshaId()); - if (userName == null || userName.isEmpty()) - throw new Exception("Asha details not found, please contact administrator"); - - request.setUserName(userName); - - int pageSize = Integer.parseInt(door_to_door_page_size); // ✅ parse once - PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); - - // ✅ Ternary to pick query — removes duplicate Page<> variable declarations - Page page = - (request.getFromDate() != null && request.getToDate() != null) - ? beneficiaryRepo.getBenDataWithinDates( - request.getUserName(), request.getFromDate(), request.getToDate(), pr) - : beneficiaryRepo.getBenDataByUser(request.getUserName(), pr); - - List resultSet = page.getContent(); - - // ✅ isEmpty() instead of size() > 0 - if (resultSet == null || resultSet.isEmpty()) { - // Return empty response instead of null - Map empty = new HashMap<>(); - empty.put("data", new ArrayList<>()); - empty.put("pageSize", pageSize); - empty.put("totalPage", 0); - return GSON.toJson(empty); + try { + if (request != null && request.getAshaId() != null) { + List resultSet; + Integer pageSize = Integer.valueOf(door_to_door_page_size); + if (request.getPageNo() != null) { + String userName = beneficiaryRepo.getUserName(request.getAshaId()); + if (userName == null || userName.isEmpty()) + throw new Exception("Asha details not found, please contact administrator"); + + request.setUserName(userName); + + PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); + if (request.getFromDate() != null && request.getToDate() != null) { + Page p = beneficiaryRepo.getBenDataWithinDates( + request.getUserName(), request.getFromDate(), request.getToDate(), pr); + resultSet = p.getContent(); + totalPage = p.getTotalPages(); + } else { + Page p = beneficiaryRepo.getBenDataByUser(request.getUserName(), + pr); + resultSet = p.getContent(); + totalPage = p.getTotalPages(); + } + if (resultSet != null && resultSet.size() > 0) { + outputResponse = getMappingsForAddressIDs(resultSet, totalPage, authorisation); + } + } else { + // page no not invalid + throw new Exception("Invalid page no"); + } + } else + throw new Exception("Invalid/missing village details"); + } catch (Exception e) { + throw new Exception(e.getMessage()); } - return getMappingsForAddressIDs(resultSet, page.getTotalPages(), authorisation); + return outputResponse; } -// --------------------------------------------------------------- -// PRIVATE METHOD -// --------------------------------------------------------------- + private String getMappingsForAddressIDs(List addressList, int totalPage, + String authorisation) { + RMNCHHouseHoldDetails benHouseHoldRMNCH_ROBJ; + RMNCHBeneficiaryDetailsRmnch benDetailsRMNCH_OBJ; + RMNCHBornBirthDetails benBotnBirthRMNCH_ROBJ; - private String getMappingsForAddressIDs(List addressList, - int totalPage, String authorisation) { + RMNCHMBeneficiarydetail benDetailsOBJ; + RMNCHMBeneficiaryAccount benAccountOBJ; + RMNCHMBeneficiaryImage benImageOBJ; + RMNCHMBeneficiaryaddress benAddressOBJ; + RMNCHMBeneficiarycontact benContactOBJ; - List> resultList = new ArrayList<>(addressList.size()); // ✅ pre-sized + Map resultMap; + ArrayList> resultList = new ArrayList<>(); for (RMNCHMBeneficiaryaddress a : addressList) { + // exception by-passing try { RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); - if (m == null) continue; // ✅ skip instead of deeply nested if block - - Map resultMap = buildResultMap(m, authorisation); - resultList.add(resultMap); - + if (m != null) { + benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); + + benDetailsOBJ = new RMNCHMBeneficiarydetail(); + benAccountOBJ = new RMNCHMBeneficiaryAccount(); + benImageOBJ = new RMNCHMBeneficiaryImage(); + benAddressOBJ = new RMNCHMBeneficiaryaddress(); + benContactOBJ = new RMNCHMBeneficiarycontact(); + Map healthDetails = getBenHealthDetails(m.getBenRegId()); + if (m.getBenDetailsId() != null) { + benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); + } + if (m.getBenAccountID() != null) { + benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); + } + if (m.getBenImageId() != null) { + benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); + } + if (m.getBenAddressId() != null) { + benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); + } + if (m.getBenContactsId() != null) { + benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); + } + + BigInteger benID = null; + if (m.getBenRegId() != null) + benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + + if (m.getBenRegId() != null) { + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()); + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + + if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()); + + } + if (benDetailsRMNCH_OBJ == null) + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + + // new mapping 30-06-2021 + if (benDetailsOBJ.getMotherName() != null) + benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); + if (benDetailsOBJ.getLiteracyStatus() != null) + benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); + + // bank + if (benAccountOBJ.getNameOfBank() != null) + benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); + if (benAccountOBJ.getBranchName() != null) + benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); + if (benAccountOBJ.getIfscCode() != null) + benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); + if (benAccountOBJ.getBankAccount() != null) + benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); + + // location + if (benAddressOBJ.getCountyid() != null) + benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); + if (benAddressOBJ.getPermCountry() != null) + benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); + + if (benAddressOBJ.getStatePerm() != null) + benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); + if (benAddressOBJ.getPermState() != null) + benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); + + if (benAddressOBJ.getDistrictidPerm() != null) { + benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); + + } + if (benAddressOBJ.getDistrictnamePerm() != null) { + benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); + + } + + if (benAddressOBJ.getPermSubDistrictId() != null) + benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); + if (benAddressOBJ.getPermSubDistrict() != null) + benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); + + if (benAddressOBJ.getVillageidPerm() != null) + benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); + if (benAddressOBJ.getVillagenamePerm() != null) + benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); + + if (benAddressOBJ.getPermServicePointId() != null) + benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); + if (benAddressOBJ.getPermServicePoint() != null) + benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); + + if (benAddressOBJ.getPermZoneID() != null) + benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); + if (benAddressOBJ.getPermZone() != null) + benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); + + if (benAddressOBJ.getPermAddrLine1() != null) + benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); + if (benAddressOBJ.getPermAddrLine2() != null) + benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); + if (benAddressOBJ.getPermAddrLine3() != null) + benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); + + // ----------------------------------------------------------------------------- + + // related benids + if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { + + String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); + Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; + int pointer = 0; + for (String s : relatedBenIDsString) { + relatedBenIDs[pointer] = Long.valueOf(s); + pointer++; + } + + benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); + } + // ------------------------------------------------------------------------------ + + if (benDetailsOBJ.getCommunity() != null) + benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); + if (benDetailsOBJ.getCommunityId() != null) + benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); + if (benContactOBJ.getPreferredPhoneNum() != null) + benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); + + if (benDetailsOBJ.getDob() != null) + benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); + if (benDetailsOBJ.getFatherName() != null) + benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); + if (benDetailsOBJ.getFirstName() != null) + benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); + if (benDetailsOBJ.getGender() != null) + benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); + if (benDetailsOBJ.getGenderId() != null) + benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); + + if (benDetailsOBJ.getMaritalstatus() != null) + benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); + if (benDetailsOBJ.getMaritalstatusId() != null) + benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); + if (benDetailsOBJ.getMarriageDate() != null) + benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); + + if (benDetailsOBJ.getReligion() != null) + benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); + if (benDetailsOBJ.getReligionID() != null) + benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); + if (benDetailsOBJ.getSpousename() != null) + benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); + + if (benImageOBJ != null && benImageOBJ.getUser_image() != null) + benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); + + // new fields +// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); + if (benID != null) + benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); + + if (benDetailsOBJ.getLastName() != null) + benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); + + if (benDetailsRMNCH_OBJ.getCreatedBy() == null) + if (benDetailsOBJ.getCreatedBy() != null) + benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); + + // age calculation + String ageDetails = ""; + int age_val = 0; + String ageUnit = null; + if (benDetailsOBJ.getDob() != null) { + + Date date = new Date(benDetailsOBJ.getDob().getTime()); + Calendar cal = Calendar.getInstance(); + + cal.setTime(date); + + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + + java.time.LocalDate todayDate = java.time.LocalDate.now(); + java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); + Period p = Period.between(birthdate, todayDate); + + int d = p.getDays(); + int mo = p.getMonths(); + int y = p.getYears(); + + if (y > 0) { + ageDetails = y + " years - " + mo + " months"; + age_val = y; + ageUnit = (age_val > 1) ? "Years" : "Year"; + } else { + if (mo > 0) { + ageDetails = mo + " months - " + d + " days"; + age_val = mo; + ageUnit = (age_val > 1) ? "Months" : "Month"; + } else { + ageDetails = d + " days"; + age_val = d; + ageUnit = (age_val > 1) ? "Days" : "Day"; + } + } + + } + + benDetailsRMNCH_OBJ.setAgeFull(ageDetails); + benDetailsRMNCH_OBJ.setAge(age_val); + if (ageUnit != null) + benDetailsRMNCH_OBJ.setAge_unit(ageUnit); + + resultMap = new HashMap<>(); + if (benHouseHoldRMNCH_ROBJ != null) + resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); + else + resultMap.put("householdDetails", new HashMap()); + + if (benBotnBirthRMNCH_ROBJ != null) + resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); + else + resultMap.put("bornbirthDeatils", new HashMap()); + + resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); + 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 + if (benAddressOBJ.getCreatedBy() != null) { + Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); + if (userID != null && userID > 0) + resultMap.put("ashaId", userID); + } + // get HealthID of ben + if (m.getBenRegId() != null) { + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); + } + + resultList.add(resultMap); + + } else { + // mapping not available + } } catch (Exception e) { - // ✅ Fixed log format — message was concatenated before addressID making it unreadable - logger.error("Error processing addressID: {}, vanID: {}, reason: {}", - a.getId(), a.getVanID(), e.getMessage()); + logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } } @@ -168,257 +433,39 @@ private String getMappingsForAddressIDs(List addressLi response.put("data", resultList); response.put("pageSize", Integer.parseInt(door_to_door_page_size)); response.put("totalPage", totalPage); - return GSON.toJson(response); // ✅ reuse static GSON instance + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(response); } -// --------------------------------------------------------------- -// EXTRACTED: build one beneficiary's result map -// --------------------------------------------------------------- - - private Map buildResultMap(RMNCHMBeneficiarymapping m, String authorisation) { - - // ---- Fetch sub-objects (null-safe defaults) ---- - RMNCHMBeneficiarydetail benDetail = m.getBenDetailsId() != null - ? beneficiaryRepo.getDetailsById(m.getBenDetailsId()) : new RMNCHMBeneficiarydetail(); - RMNCHMBeneficiaryAccount benAccount = m.getBenAccountID() != null - ? beneficiaryRepo.getAccountById(m.getBenAccountID()) : new RMNCHMBeneficiaryAccount(); - RMNCHMBeneficiaryImage benImage = m.getBenImageId() != null - ? beneficiaryRepo.getImageById(m.getBenImageId().longValue()) : new RMNCHMBeneficiaryImage(); - RMNCHMBeneficiaryaddress benAddress = m.getBenAddressId() != null - ? beneficiaryRepo.getAddressById(m.getBenAddressId()) : new RMNCHMBeneficiaryaddress(); - RMNCHMBeneficiarycontact benContact = m.getBenContactsId() != null - ? beneficiaryRepo.getContactById(m.getBenContactsId()) : new RMNCHMBeneficiarycontact(); - - // ---- Protect against null returns from repo ---- - if (benDetail == null) benDetail = new RMNCHMBeneficiarydetail(); - if (benAccount == null) benAccount = new RMNCHMBeneficiaryAccount(); - if (benAddress == null) benAddress = new RMNCHMBeneficiaryaddress(); - if (benContact == null) benContact = new RMNCHMBeneficiarycontact(); - - BigInteger benID = m.getBenRegId() != null - ? beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()) : null; - - // ---- RMNCH details + household + birth ---- - RMNCHBeneficiaryDetailsRmnch benRMNCH = new RMNCHBeneficiaryDetailsRmnch(); - RMNCHHouseHoldDetails household = new RMNCHHouseHoldDetails(); - RMNCHBornBirthDetails bornBirth = new RMNCHBornBirthDetails(); - - if (m.getBenRegId() != null) { - RMNCHBeneficiaryDetailsRmnch fetched = - beneficiaryRepo.getDetailsByRegID(m.getBenRegId().longValue()); - if (fetched != null) { - benRMNCH = fetched; - if (benRMNCH.getHouseoldId() != null) - household = houseHoldRepo.getByHouseHoldID(benRMNCH.getHouseoldId()); - } - RMNCHBornBirthDetails birth = beneficiaryRepo.getBornBirthByRegID(m.getBenRegId().longValue()); - if (birth != null) bornBirth = birth; - } - - // ---- Merge all sub-object fields into benRMNCH ---- - mergeFields(benRMNCH, benDetail, benAccount, benAddress, benContact, benImage, benID); - - // ---- Age ---- - applyAge(benRMNCH, benDetail); - - // ---- Health details from local DB ---- - Map healthDetails = getBenHealthDetails(m.getBenRegId()); - - // ---- Build result map ---- - Map map = new HashMap<>(); - map.put("householdDetails", household != null ? household : new HashMap<>()); - map.put("bornbirthDeatils", bornBirth != null ? bornBirth : new HashMap<>()); // key kept as-is for backward compat - map.put("beneficiaryDetails", benRMNCH); - map.put("abhaHealthDetails", healthDetails); - map.put("houseoldId", benRMNCH.getHouseoldId()); - map.put("benficieryid", benRMNCH.getBenficieryid()); - map.put("isDeath", benRMNCH.getIsDeath()); - map.put("isDeathValue", benRMNCH.getIsDeathValue()); - map.put("dateOfDeath", benRMNCH.getDateOfDeath()); - map.put("timeOfDeath", benRMNCH.getTimeOfDeath()); - map.put("reasonOfDeath", benRMNCH.getReasonOfDeath()); - map.put("reasonOfDeathId", benRMNCH.getReasonOfDeathId()); - map.put("placeOfDeath", benRMNCH.getPlaceOfDeath()); - map.put("placeOfDeathId", benRMNCH.getPlaceOfDeathId()); - map.put("isSpouseAdded", benRMNCH.getIsSpouseAdded()); - map.put("isChildrenAdded", benRMNCH.getIsChildrenAdded()); - map.put("noOfchildren", benRMNCH.getNoOfchildren()); - map.put("isMarried", benRMNCH.getIsMarried()); - map.put("doYouHavechildren", benRMNCH.getDoYouHavechildren()); - map.put("noofAlivechildren", benRMNCH.getNoofAlivechildren()); // ✅ trailing spaces removed - map.put("isDeactivate", benRMNCH.getIsDeactivate()); - map.put("BenRegId", m.getBenRegId()); - - // ✅ ASHA id lookup - if (benAddress.getCreatedBy() != null) { - Integer userID = beneficiaryRepo.getUserIDByUserName(benAddress.getCreatedBy()); - if (userID != null && userID > 0) map.put("ashaId", userID); - } - // ✅ External ABHA fetch - if (m.getBenRegId() != null) - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, map); - - return map; - } - -// --------------------------------------------------------------- -// EXTRACTED: merge all sub-object fields into RMNCH object -// replaces ~50 repetitive if (x != null) dest.setX(x) blocks -// --------------------------------------------------------------- - - private void mergeFields(RMNCHBeneficiaryDetailsRmnch d, - RMNCHMBeneficiarydetail detail, - RMNCHMBeneficiaryAccount account, - RMNCHMBeneficiaryaddress address, - RMNCHMBeneficiarycontact contact, - RMNCHMBeneficiaryImage image, - BigInteger benID) { - - // Personal details - ifNotNull(detail.getFirstName(), d::setFirstName); - ifNotNull(detail.getLastName(), d::setLastName); - ifNotNull(detail.getMotherName(), d::setMotherName); - ifNotNull(detail.getFatherName(), d::setFatherName); - ifNotNull(detail.getSpousename(), d::setSpousename); - ifNotNull(detail.getDob(), d::setDob); - ifNotNull(detail.getGender(), d::setGender); - ifNotNull(detail.getGenderId(), d::setGenderId); - ifNotNull(detail.getMaritalstatus(), d::setMaritalstatus); - ifNotNull(detail.getMaritalstatusId(), d::setMaritalstatusId); - ifNotNull(detail.getMarriageDate(), d::setMarriageDate); - ifNotNull(detail.getLiteracyStatus(), d::setLiteracyStatus); - ifNotNull(detail.getCommunity(), d::setCommunity); - ifNotNull(detail.getCommunityId(), d::setCommunityId); - ifNotNull(detail.getReligion(), d::setReligion); - ifNotNull(detail.getReligionID(), d::setReligionID); - // createdBy — only set if not already populated from RMNCH fetch - if (d.getCreatedBy() == null) ifNotNull(detail.getCreatedBy(), d::setCreatedBy); - - // Bank details - ifNotNull(account.getNameOfBank(), d::setNameOfBank); - ifNotNull(account.getBranchName(), d::setBranchName); - ifNotNull(account.getIfscCode(), d::setIfscCode); - ifNotNull(account.getBankAccount(), d::setBankAccount); - - // Address / location - ifNotNull(address.getCountyid(), d::setCountryId); - ifNotNull(address.getPermCountry(), d::setCountryName); - ifNotNull(address.getStatePerm(), d::setStateId); - ifNotNull(address.getPermState(), d::setStateName); - ifNotNull(address.getDistrictidPerm(), d::setDistrictid); - ifNotNull(address.getDistrictnamePerm(), d::setDistrictname); - ifNotNull(address.getPermSubDistrictId(), d::setBlockId); - ifNotNull(address.getPermSubDistrict(), d::setBlockName); - ifNotNull(address.getVillageidPerm(), d::setVillageId); - ifNotNull(address.getVillagenamePerm(), d::setVillageName); - ifNotNull(address.getPermServicePointId(), d::setServicePointID); - ifNotNull(address.getPermServicePoint(), d::setServicePointName); - ifNotNull(address.getPermZoneID(), d::setZoneID); - ifNotNull(address.getPermZone(), d::setZoneName); - ifNotNull(address.getPermAddrLine1(), d::setAddressLine1); - ifNotNull(address.getPermAddrLine2(), d::setAddressLine2); - ifNotNull(address.getPermAddrLine3(), d::setAddressLine3); - - // Contact - ifNotNull(contact.getPreferredPhoneNum(), d::setContact_number); - - // Image - if (image != null) ifNotNull(image.getUser_image(), d::setUser_image); - - // Ben ID - if (benID != null) d.setBenficieryid(benID.longValue()); - - // Related beneficiary IDs — split CSV string into Long[] - if (d.getRelatedBeneficiaryIdsDB() != null) { - String[] parts = d.getRelatedBeneficiaryIdsDB().split(","); - Long[] ids = new Long[parts.length]; - for (int i = 0; i < parts.length; i++) - ids[i] = Long.valueOf(parts[i].trim()); - d.setRelatedBeneficiaryIds(ids); - } - } - -// --------------------------------------------------------------- -// EXTRACTED: age calculation -// --------------------------------------------------------------- - - private void applyAge(RMNCHBeneficiaryDetailsRmnch dest, RMNCHMBeneficiarydetail detail) { - if (detail.getDob() == null) { - dest.setAgeFull(""); - dest.setAge(0); - return; - } - - Calendar cal = Calendar.getInstance(); - cal.setTime(detail.getDob()); - LocalDate birth = LocalDate.of( - cal.get(Calendar.YEAR), - cal.get(Calendar.MONTH) + 1, - cal.get(Calendar.DAY_OF_MONTH)); - - Period p = Period.between(birth, LocalDate.now()); - int y = p.getYears(), mo = p.getMonths(), d = p.getDays(); - - String ageFull; - int ageVal; - String ageUnit; - - if (y > 0) { - ageFull = y + " years - " + mo + " months"; - ageVal = y; - ageUnit = y > 1 ? "Years" : "Year"; - } else if (mo > 0) { - ageFull = mo + " months - " + d + " days"; - ageVal = mo; - ageUnit = mo > 1 ? "Months" : "Month"; - } else { - ageFull = d + " days"; - ageVal = d; - ageUnit = d > 1 ? "Days" : "Day"; + private Map getBenHealthDetails(BigInteger benRegId) { + Map healthDetails = new HashMap<>(); + if (null != benRegId) { + Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + + if (null != healthIdNumber) { + List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); + if (health != null && !health.isEmpty()) { + for (Object[] objects : health) { + healthDetails.put("HealthID", objects[0]); + healthDetails.put("HealthIdNumber", objects[1]); + healthDetails.put("isNewAbha", objects[2]); + } + } else { + healthDetails.put("HealthIdNumber", healthIdNumber); + healthDetails.put("HealthID", healthId); + healthDetails.put("isNewAbha", null); + } + } + } } - - dest.setAgeFull(ageFull); - dest.setAge(ageVal); - dest.setAge_unit(ageUnit); - } - -// --------------------------------------------------------------- -// UTILITY: replaces 50+ repetitive if-not-null setter blocks -// --------------------------------------------------------------- - - private void ifNotNull(T value, java.util.function.Consumer setter) { - if (value != null) setter.accept(value); + return healthDetails; } - private Map getBenHealthDetails(BigInteger benRegId) { - Map healthDetails = new HashMap<>(); - if (null != benRegId) { - Object[] benHealthIdNumber = beneficiaryRepo.getBenHealthIdNumber(benRegId); - if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { - Object[] healthData = (Object[]) benHealthIdNumber[0]; - String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; - String healthId = healthData[1] != null ? healthData[1].toString() : null; - - if (null != healthIdNumber) { - List health = beneficiaryRepo.getBenHealthDetails(healthIdNumber); - if (health != null && !health.isEmpty()) { - for (Object[] objects : health) { - healthDetails.put("HealthID", objects[0]); - healthDetails.put("HealthIdNumber", objects[1]); - healthDetails.put("isNewAbha", objects[2]); - } - } else { - healthDetails.put("HealthIdNumber", healthIdNumber); - healthDetails.put("HealthID", healthId); - healthDetails.put("isNewAbha", null); - } - } - } - } - return healthDetails; - } - private Map getBenBenVisitDetails(BigInteger benRegId) { Map healthDetails = new HashMap<>(); if (null != benRegId) { @@ -435,7 +482,7 @@ private Map getBenBenVisitDetails(BigInteger benRegId) { return healthDetails; } - public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { + public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map resultMap) { Map requestMap = new HashMap(); requestMap.put("beneficiaryRegID", benRegID); requestMap.put("beneficiaryID", null); From aa412482fdef3f9f578f5bbc67120ae56ace41cc Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 23:42:55 +0530 Subject: [PATCH 145/450] fix DeliveryOutcome data issue --- .../com/iemr/flw/controller/DeathReportsController.java | 6 ++---- .../com/iemr/flw/controller/MaternalHealthController.java | 8 ++++---- src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java | 2 +- src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java | 2 +- .../iemr/flw/service/impl/DeathReportsServiceImpl.java | 4 ++-- .../iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java | 2 +- 6 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/DeathReportsController.java b/src/main/java/com/iemr/flw/controller/DeathReportsController.java index f5317a8bc..d8c3c745d 100644 --- a/src/main/java/com/iemr/flw/controller/DeathReportsController.java +++ b/src/main/java/com/iemr/flw/controller/DeathReportsController.java @@ -84,8 +84,7 @@ public String getCdrRecords(@RequestBody GetBenRequestHandler requestDTO, logger.info("fetching All CDR Details for user: " + requestDTO.getAshaId()); if (requestDTO != null) { List result = deathReportsService.getCdrRecords(requestDTO); - Gson gson = new GsonBuilder() - .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format + Gson gson = new GsonBuilder()// Set the desired date format .create(); String s = gson.toJson(result); if (s != null) @@ -111,8 +110,7 @@ public String getMdsrRecords(@RequestBody GetBenRequestHandler requestDTO, logger.info("fetching All MDSR Details for user: " + requestDTO.getAshaId()); if (requestDTO != null) { List result = deathReportsService.getMdsrRecords(requestDTO); - Gson gson = new GsonBuilder() - .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format + Gson gson = new GsonBuilder()// Set the desired date format .create(); String s = gson.toJson(result); if (s != null) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index e65eacda6..02a28b949 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -239,11 +239,11 @@ public String getDeliveryOutcome(@RequestBody GetBenRequestHandler requestDTO, logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); List result = deliveryOutcomeService.getDeliveryOutcome(requestDTO); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + Gson gson = new GsonBuilder().create(); String s = gson.toJson(result); - if (s != null) - response.setResponse(s); - else + if (result != null && !result.isEmpty()) { + response.setResponse(gson.toJson(result)); + }else response.setError(5000, "No record found"); } else response.setError(5000, "Invalid/NULL request obj"); diff --git a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java index d5e0e7112..f6ccf7fb5 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java @@ -14,7 +14,7 @@ public interface CdrRepo extends JpaRepository { CDR findCDRByBenId(Long benId); - @Query(" SELECT c FROM CDR c WHERE c.createdBy = :userId and c.createdDate >= :fromDate and c.createdDate <= :toDate") + @Query(" SELECT c FROM CDR c WHERE c.createdBy = :userId") List getAllCdrByBenId(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java index 532a62c91..687b1864d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java @@ -14,7 +14,7 @@ public interface MdsrRepo extends JpaRepository { MDSR findMDSRByBenId(Long benId); - @Query(" SELECT m FROM MDSR m WHERE m.createdBy = :userId and m.createdDate >= :fromDate and m.createdDate <= :toDate") + @Query(" SELECT m FROM MDSR m WHERE m.createdBy = :userId") List getAllMdsrByAshaId(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); } 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 82cee5d06..344ed422d 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -104,7 +104,7 @@ public String registerMDSR(List mdsrDTOs) { @Override public List getCdrRecords(GetBenRequestHandler dto) { try{ - String user = beneficiaryRepo.getUserName(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List cdrlist = cdrRepo.getAllCdrByBenId(user, dto.getFromDate(), dto.getToDate()); return cdrlist.stream() @@ -120,7 +120,7 @@ public List getCdrRecords(GetBenRequestHandler dto) { public List getMdsrRecords(GetBenRequestHandler dto) { try { - String user = beneficiaryRepo.getUserName(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List mdsrList = mdsrRepo.getAllMdsrByAshaId(user, dto.getFromDate(), dto.getToDate()); 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 63f86c9a0..737182f7b 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -108,7 +108,7 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT @Override public List getDeliveryOutcome(GetBenRequestHandler dto) { try { - String user = beneficiaryRepo.getUserName(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List deliveryOutcomeList = deliveryOutcomeRepo.findByCreatedBy(user); return deliveryOutcomeList.stream() .map(deliveryOutcome -> mapper.convertValue(deliveryOutcome, DeliveryOutcomeDTO.class)) From 9518f5e9243314eda71d9940d8cdc6a92dfabb5a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 23:45:08 +0530 Subject: [PATCH 146/450] fix DeliveryOutcome data issue --- src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java | 2 ++ src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java | 2 ++ .../com/iemr/flw/service/impl/DeathReportsServiceImpl.java | 4 ++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java index f6ccf7fb5..873eb0c1a 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java @@ -14,6 +14,8 @@ public interface CdrRepo extends JpaRepository { CDR findCDRByBenId(Long benId); + ListfindByCreatedBy(String userName); + @Query(" SELECT c FROM CDR c WHERE c.createdBy = :userId") List getAllCdrByBenId(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); diff --git a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java index 687b1864d..57a43883c 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java @@ -14,6 +14,8 @@ public interface MdsrRepo extends JpaRepository { MDSR findMDSRByBenId(Long benId); + List findByCreatedBy(String userName); + @Query(" SELECT m FROM MDSR m WHERE m.createdBy = :userId") List getAllMdsrByAshaId(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); 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 344ed422d..1feabe77f 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -106,7 +106,7 @@ public List getCdrRecords(GetBenRequestHandler dto) { try{ String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List cdrlist = - cdrRepo.getAllCdrByBenId(user, dto.getFromDate(), dto.getToDate()); + cdrRepo.findByCreatedBy(user); return cdrlist.stream() .map(cdr -> mapper.convertValue(cdr, CdrDTO.class)) .collect(Collectors.toList()); @@ -123,7 +123,7 @@ public List getMdsrRecords(GetBenRequestHandler dto) { String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List mdsrList = - mdsrRepo.getAllMdsrByAshaId(user, dto.getFromDate(), dto.getToDate()); + mdsrRepo.findByCreatedBy(user); return mdsrList.stream() .map(mdsr -> mapper.convertValue(mdsr, MdsrDTO.class)) .collect(Collectors.toList()); From af33afe4c10fff2fa6f70f656bc913df2c00d3e9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 23:49:01 +0530 Subject: [PATCH 147/450] fix DeliveryOutcome data issue --- src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java index 873eb0c1a..069362e8f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/CdrRepo.java @@ -15,8 +15,4 @@ public interface CdrRepo extends JpaRepository { CDR findCDRByBenId(Long benId); ListfindByCreatedBy(String userName); - - @Query(" SELECT c FROM CDR c WHERE c.createdBy = :userId") - List getAllCdrByBenId(@Param("userId") String userId, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); } From a7831ef35b082e7cf534e30c4fbd88ee94ae0eec Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Feb 2026 23:50:17 +0530 Subject: [PATCH 148/450] fix DeliveryOutcome data issue --- src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java index 57a43883c..127954c6f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/MdsrRepo.java @@ -16,7 +16,4 @@ public interface MdsrRepo extends JpaRepository { List findByCreatedBy(String userName); - @Query(" SELECT m FROM MDSR m WHERE m.createdBy = :userId") - List getAllMdsrByAshaId(@Param("userId") String userId, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); } From 12837a8f52dab58304a63f5bfc0be6ed9ec2213a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 11:39:39 +0530 Subject: [PATCH 149/450] fix DeliveryOutcome data issue --- .../com/iemr/flw/repo/identity/BeneficiaryRepo.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) 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 96301fb3c..94b1cd0e3 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -28,10 +28,15 @@ public interface BeneficiaryRepo extends JpaRepository 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); From a870b3cb4e5089743de7c1ddb12b7a98caaa2cac Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 12:22:27 +0530 Subject: [PATCH 150/450] optimize ben address query --- .../flw/repo/identity/BeneficiaryRepo.java | 1 + .../service/impl/BeneficiaryServiceImpl.java | 87 +++++++++++-------- 2 files changed, 51 insertions(+), 37 deletions(-) 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 94b1cd0e3..3af9cd6b9 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -13,6 +13,7 @@ import java.sql.Timestamp; import java.util.ArrayList; import java.util.Optional; +import java.util.stream.Stream; @Repository public interface BeneficiaryRepo extends JpaRepository { 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 dbbe40e74..8a60e271b 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; import com.iemr.flw.domain.iemr.EyeCheckupVisit; import com.iemr.flw.domain.iemr.IncentiveActivity; @@ -54,6 +55,7 @@ import com.iemr.flw.service.BeneficiaryService; import com.iemr.flw.utils.config.ConfigProperties; import com.iemr.flw.utils.http.HttpUtils; +import org.springframework.transaction.annotation.Transactional; @Service @Qualifier("rmnchServiceImpl") @@ -98,48 +100,59 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { - String outputResponse = null; - int totalPage = 0; - try { - if (request != null && request.getAshaId() != null) { - List resultSet; - Integer pageSize = Integer.valueOf(door_to_door_page_size); - if (request.getPageNo() != null) { - String userName = beneficiaryRepo.getUserName(request.getAshaId()); - if (userName == null || userName.isEmpty()) - throw new Exception("Asha details not found, please contact administrator"); - - request.setUserName(userName); - - PageRequest pr = PageRequest.of(request.getPageNo(), pageSize); - if (request.getFromDate() != null && request.getToDate() != null) { - Page p = beneficiaryRepo.getBenDataWithinDates( - request.getUserName(), request.getFromDate(), request.getToDate(), pr); - resultSet = p.getContent(); - totalPage = p.getTotalPages(); - } else { - Page p = beneficiaryRepo.getBenDataByUser(request.getUserName(), - pr); - resultSet = p.getContent(); - totalPage = p.getTotalPages(); - } - if (resultSet != null && resultSet.size() > 0) { - outputResponse = getMappingsForAddressIDs(resultSet, totalPage, authorisation); - } - } else { - // page no not invalid - throw new Exception("Invalid page no"); - } - } else - throw new Exception("Invalid/missing village details"); - } catch (Exception e) { - throw new Exception(e.getMessage()); + if (request == null || request.getAshaId() == null) { + throw new Exception("Invalid/missing asha details"); } - return outputResponse; + if (request.getPageNo() == null || request.getPageNo() < 0) { + throw new Exception("Invalid page number"); + } + + String userName = beneficiaryRepo.getUserName(request.getAshaId()); + + if (userName == null || userName.isEmpty()) { + throw new Exception("Asha details not found, please contact administrator"); + } + + request.setUserName(userName); + + int pageSize = Integer.parseInt(door_to_door_page_size); + PageRequest pageRequest = PageRequest.of(request.getPageNo(), pageSize); + + Page pageResult; + + // ✅ Date Filter Handling + if (request.getFromDate() != null && request.getToDate() != null) { + + if (request.getFromDate().after(request.getToDate())) { + throw new Exception("Invalid date range"); + } + + pageResult = beneficiaryRepo.getBenDataWithinDates( + userName, + request.getFromDate(), + request.getToDate(), + pageRequest + ); + + } else { + + pageResult = beneficiaryRepo.getBenDataByUser(userName, pageRequest); + } + + if (!pageResult.hasContent()) { + return null; + } + + return getMappingsForAddressIDs( + pageResult.getContent(), + pageResult.getTotalPages(), + authorisation + ); } + private String getMappingsForAddressIDs(List addressList, int totalPage, String authorisation) { RMNCHHouseHoldDetails benHouseHoldRMNCH_ROBJ; From 63a8d25151865e55a19ed11f5c06b67f42fe319c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 12:30:44 +0530 Subject: [PATCH 151/450] optimize ben address query --- .../com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 737182f7b..6d360b466 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -110,11 +110,12 @@ public List getDeliveryOutcome(GetBenRequestHandler dto) { try { String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List deliveryOutcomeList = deliveryOutcomeRepo.findByCreatedBy(user); + 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; } From 564b1dcf5d22e123740c9019a23567fac5ddef8d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 15:27:48 +0530 Subject: [PATCH 152/450] optimize ben address query --- .../java/com/iemr/flw/controller/MaternalHealthController.java | 2 +- src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java | 2 -- src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java | 1 + .../com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 02a28b949..5f664991e 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -26,7 +26,7 @@ import java.util.List; @RestController -@RequestMapping(value = "/maternalCare", headers = "Authorization", consumes = "application/json", produces = "application/json") +@RequestMapping(value = "/maternalCare", consumes = "application/json", produces = "application/json") public class MaternalHealthController { private final Logger logger = LoggerFactory.getLogger(CoupleController.class); 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 6050fab57..d3a1b56ce 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java @@ -17,7 +17,6 @@ public class DeliveryOutcome { @Column(name = "ben_id") private Long benId; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") @Column(name = "delivery_date") private Timestamp dateOfDelivery; @@ -54,7 +53,6 @@ public class DeliveryOutcome { @Column(name = "still_birth") private Integer stillBirth; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") @Column(name = "discharge_date") private Timestamp dateOfDischarge; 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 941721ca1..539bffb20 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -23,6 +23,7 @@ public class DeliveryOutcomeDTO { private Integer deliveryOutcome; private Integer liveBirth; private Integer stillBirth; + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") private Timestamp dateOfDischarge; private String timeOfDischarge; private Boolean isJSYBenificiary; 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 6d360b466..8c87202a7 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -115,7 +115,7 @@ public List getDeliveryOutcome(GetBenRequestHandler dto) { .map(deliveryOutcome -> mapper.convertValue(deliveryOutcome, DeliveryOutcomeDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error("DeliveryOutcome Exception:",e.getMessage()); + logger.error("DeliveryOutcome Exception:"+e.getMessage()); } return null; } From 00aa3e7f84b711d6f3ddb8d4f75bc801af80abb0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 15:48:36 +0530 Subject: [PATCH 153/450] optimize ben address query --- src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 539bffb20..85fc45901 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -23,7 +23,7 @@ public class DeliveryOutcomeDTO { private Integer deliveryOutcome; private Integer liveBirth; private Integer stillBirth; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy h:mm:ss a") private Timestamp dateOfDischarge; private String timeOfDischarge; private Boolean isJSYBenificiary; From de32d2b089417aa3b85f6e9afe61479d1b9d0e02 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 16:16:04 +0530 Subject: [PATCH 154/450] optimize ben address query --- .../com/iemr/flw/controller/DeathReportsController.java | 2 ++ .../com/iemr/flw/controller/MaternalHealthController.java | 2 +- src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java | 1 + .../java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java | 6 ++++-- src/main/java/com/iemr/flw/dto/iemr/MdsrDTO.java | 6 ++++++ .../com/iemr/flw/service/impl/DeathReportsServiceImpl.java | 7 +++++++ 6 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/DeathReportsController.java b/src/main/java/com/iemr/flw/controller/DeathReportsController.java index d8c3c745d..0839ec1f3 100644 --- a/src/main/java/com/iemr/flw/controller/DeathReportsController.java +++ b/src/main/java/com/iemr/flw/controller/DeathReportsController.java @@ -85,6 +85,7 @@ public String getCdrRecords(@RequestBody GetBenRequestHandler requestDTO, if (requestDTO != null) { List result = deathReportsService.getCdrRecords(requestDTO); Gson gson = new GsonBuilder()// Set the desired date format + .setDateFormat("MMM d yyyy h:mm:ss a") .create(); String s = gson.toJson(result); if (s != null) @@ -111,6 +112,7 @@ public String getMdsrRecords(@RequestBody GetBenRequestHandler requestDTO, if (requestDTO != null) { List result = deathReportsService.getMdsrRecords(requestDTO); Gson gson = new GsonBuilder()// Set the desired date format + .setDateFormat("MMM d yyyy h:mm:ss a") .create(); String s = gson.toJson(result); if (s != null) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index 5f664991e..e87a63743 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -239,7 +239,7 @@ public String getDeliveryOutcome(@RequestBody GetBenRequestHandler requestDTO, logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); List result = deliveryOutcomeService.getDeliveryOutcome(requestDTO); - Gson gson = new GsonBuilder().create(); + Gson gson = new GsonBuilder().setDateFormat("MMM d yyyy h:mm:ss a").create(); String s = gson.toJson(result); if (result != null && !result.isEmpty()) { response.setResponse(gson.toJson(result)); 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 122f652d8..18b5ca529 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java @@ -54,6 +54,7 @@ public class CdrDTO { private String deathCertImage1; private String deathCertImage2; + private String cdrImage; private Timestamp updatedDate; 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 85fc45901..cc4f4fe16 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -10,7 +10,7 @@ public class DeliveryOutcomeDTO { private Long id; private Long benId; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") + @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp dateOfDelivery; private String timeOfDelivery; private String placeOfDelivery; @@ -23,13 +23,15 @@ public class DeliveryOutcomeDTO { private Integer deliveryOutcome; private Integer liveBirth; private Integer stillBirth; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy h:mm:ss a") + @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp dateOfDischarge; private String timeOfDischarge; private Boolean isJSYBenificiary; private Boolean isActive; + @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp createdDate; private String createdBy; + @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp updatedDate; private String updatedBy; } 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 5b07e40a3..e59047aba 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/service/impl/DeathReportsServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java index 1feabe77f..43a6fa718 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -11,6 +11,8 @@ import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.DeathReportsService; import org.modelmapper.ModelMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -43,6 +45,7 @@ public class DeathReportsServiceImpl implements DeathReportsService { @Autowired private IncentiveRecordRepo recordRepo; + private final Logger logger = LoggerFactory.getLogger(DeathReportsServiceImpl.class); @Override public String registerCDR(List cdrDTOs) { @@ -111,6 +114,8 @@ public List getCdrRecords(GetBenRequestHandler dto) { .map(cdr -> mapper.convertValue(cdr, CdrDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { + logger.error("MDSR Exception:"+e.getMessage()); + // log } return null; @@ -128,6 +133,8 @@ public List getMdsrRecords(GetBenRequestHandler dto) { .map(mdsr -> mapper.convertValue(mdsr, MdsrDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { + logger.error("MDSR Exception:"+e.getMessage()); + // log } return null; From f41000045bd076f46f18c15341762d25930aaa81 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 16:35:28 +0530 Subject: [PATCH 155/450] optimize ben address query --- .../java/com/iemr/flw/controller/DeathReportsController.java | 4 ++-- .../com/iemr/flw/controller/MaternalHealthController.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/DeathReportsController.java b/src/main/java/com/iemr/flw/controller/DeathReportsController.java index 0839ec1f3..e8b50de90 100644 --- a/src/main/java/com/iemr/flw/controller/DeathReportsController.java +++ b/src/main/java/com/iemr/flw/controller/DeathReportsController.java @@ -85,7 +85,7 @@ public String getCdrRecords(@RequestBody GetBenRequestHandler requestDTO, if (requestDTO != null) { List result = deathReportsService.getCdrRecords(requestDTO); Gson gson = new GsonBuilder()// Set the desired date format - .setDateFormat("MMM d yyyy h:mm:ss a") + .setDateFormat("MMM dd, yyyy h:mm:ss a") .create(); String s = gson.toJson(result); if (s != null) @@ -112,7 +112,7 @@ public String getMdsrRecords(@RequestBody GetBenRequestHandler requestDTO, if (requestDTO != null) { List result = deathReportsService.getMdsrRecords(requestDTO); Gson gson = new GsonBuilder()// Set the desired date format - .setDateFormat("MMM d yyyy h:mm:ss a") + .setDateFormat("MMM dd, yyyy h:mm:ss a") .create(); String s = gson.toJson(result); if (s != null) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index e87a63743..f0955af6d 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -239,7 +239,7 @@ public String getDeliveryOutcome(@RequestBody GetBenRequestHandler requestDTO, logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + requestDTO); List result = deliveryOutcomeService.getDeliveryOutcome(requestDTO); - Gson gson = new GsonBuilder().setDateFormat("MMM d yyyy h:mm:ss a").create(); + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); String s = gson.toJson(result); if (result != null && !result.isEmpty()) { response.setResponse(gson.toJson(result)); From b0f74e9a0864efa962b2abe154344f945b8de2c8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 17:35:34 +0530 Subject: [PATCH 156/450] optimize ben address query --- .../com/iemr/flw/dto/iemr/TBScreeningDTO.java | 93 +------------------ .../impl/DiseaseControlServiceImpl.java | 8 +- .../service/impl/TBScreeningServiceImpl.java | 25 +++-- 3 files changed, 20 insertions(+), 106 deletions(-) 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 017d73af2..36f48dfc5 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -37,98 +37,7 @@ public class TBScreeningDTO { private Boolean bmi; private Boolean contactWithTBPatient; private Boolean historyOfTBInLastFiveYrs; - private String sympotomatic; + private String sympotomatic; private String asymptomatic; private String recommandateTest; - - - - - 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; - } } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 88932659c..3a2e9e5ba 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -463,7 +463,7 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Check if the list is empty if (filteredList.isEmpty()) { - return Collections.singletonMap("message", "No data found for Malaria."); + return filteredList; } // Map to DTOs @@ -551,7 +551,7 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) // Check if the list is empty if (filteredList.isEmpty()) { - return Collections.singletonMap("message", "No data found for Kala Azar."); + return filteredList; } // Map to DTOs @@ -590,7 +590,7 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) public Object getAllKalaAES(GetDiseaseRequestHandler getDiseaseRequestHandler) { if (diseaseAESJERepository.findAll().isEmpty()) { - return Collections.singletonMap("message", "No data found for AES."); + return diseaseAESJERepository.findAll(); } return diseaseAESJERepository.findAll().stream().filter(diseaseAesje -> Objects.equals(diseaseAesje.getUserId(), getDiseaseRequestHandler.getUserId())).collect(Collectors.toList()); @@ -641,7 +641,7 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Check if the list is empty if (filteredList.isEmpty()) { - return Collections.singletonMap("message", "No data found for Leprosy."); + return filteredList; } // Map to DTOs diff --git a/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java index b62101693..df70cd75b 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java @@ -55,16 +55,21 @@ public String save(TBScreeningRequestDTO requestDTO) throws Exception { @Override public String getByUserId(GetBenRequestHandler request) { - List dtos = new ArrayList<>(); - List tbScreeningList = tbScreeningRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); - tbScreeningList.forEach(tbScreening -> dtos.add(modelMapper.map(tbScreening, TBScreeningDTO.class))); - TBScreeningRequestDTO tbScreeningRequestDTO = new TBScreeningRequestDTO(); - tbScreeningRequestDTO.setTbScreeningList(dtos); - tbScreeningRequestDTO.setUserId(request.getAshaId()); - Gson gson = new GsonBuilder() - .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format - .create(); - return gson.toJson(tbScreeningRequestDTO); + try { + List dtos = new ArrayList<>(); + List tbScreeningList = tbScreeningRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); + tbScreeningList.forEach(tbScreening -> dtos.add(modelMapper.map(tbScreening, TBScreeningDTO.class))); + TBScreeningRequestDTO tbScreeningRequestDTO = new TBScreeningRequestDTO(); + tbScreeningRequestDTO.setTbScreeningList(dtos); + tbScreeningRequestDTO.setUserId(request.getAshaId()); + Gson gson = new GsonBuilder() + .setDateFormat("MMM dd, yyyy h:mm:ss a") // Set the desired date format + .create(); + return gson.toJson(tbScreeningRequestDTO); + }catch (Exception e){ + logger.error("TBScreening Exception:"+e.getMessage()); + } + return null; } } From cd595185c35bf4c27c097e01cc7b84fff2bdc92b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 17:45:24 +0530 Subject: [PATCH 157/450] optimize ben address query --- src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java | 4 ++-- .../com/iemr/flw/service/impl/TBScreeningServiceImpl.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java b/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java index e2f7fed00..61be2a57e 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java @@ -15,6 +15,6 @@ public interface TBScreeningRepo extends JpaRepository { @Query(value = "SELECT tbs FROM TBScreening tbs WHERE tbs.benId = :benId and tbs.userId = :userId") TBScreening getByUserIdAndBenId(@Param("benId") Long benId, @Param("userId") Integer userId); - @Query(value = "SELECT tbs FROM TBScreening tbs WHERE tbs.userId = :userId and tbs.visitDate >= :fromDate and tbs.visitDate <= :toDate") - List getByUserId(@Param("userId") Integer userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + @Query(value = "SELECT tbs FROM TBScreening tbs WHERE tbs.userId = :userId") + List getByUserId(@Param("userId") Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java index df70cd75b..a6c217b86 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBScreeningServiceImpl.java @@ -57,7 +57,7 @@ public String save(TBScreeningRequestDTO requestDTO) throws Exception { public String getByUserId(GetBenRequestHandler request) { try { List dtos = new ArrayList<>(); - List tbScreeningList = tbScreeningRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); + List tbScreeningList = tbScreeningRepo.getByUserId(request.getAshaId()); tbScreeningList.forEach(tbScreening -> dtos.add(modelMapper.map(tbScreening, TBScreeningDTO.class))); TBScreeningRequestDTO tbScreeningRequestDTO = new TBScreeningRequestDTO(); tbScreeningRequestDTO.setTbScreeningList(dtos); From fa117105418c3ddfa50a5bcbbbaf1cb4442a811c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 17:49:57 +0530 Subject: [PATCH 158/450] optimize ben address query --- src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java | 5 ++--- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java index 063a0795a..28675daad 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java @@ -12,9 +12,8 @@ @Repository public interface PNCVisitRepo extends JpaRepository { - @Query(value = "SELECT pnc FROM PNCVisit pnc WHERE pnc.createdBy = :userId and pnc.isActive = true and pnc.createdDate >= :fromDate and pnc.createdDate <= :toDate") - List getPNCForPW(@Param("userId") String userId, - @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + @Query(value = "SELECT pnc FROM PNCVisit pnc WHERE pnc.createdBy = :userId and pnc.isActive = true") + List getPNCForPW(@Param("userId") String userId); PNCVisit findPNCVisitByBenIdAndPncPeriodAndIsActive(Long benId, Integer pncVisit, Boolean isActive); } 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 52ff5e1d1..08bb264a3 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -309,7 +309,7 @@ record = new IncentiveActivityRecord(); public List getPNCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List pncVisits = pncVisitRepo.getPNCForPW(user, dto.getFromDate(), dto.getToDate()); + List pncVisits = pncVisitRepo.getPNCForPW(user); return pncVisits.stream() .map(pnc -> mapper.convertValue(pnc, PNCVisitDTO.class)) .collect(Collectors.toList()); From 896dae7d7de96c636297bee7ffe4a6fe19913230 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 17:53:02 +0530 Subject: [PATCH 159/450] optimize ben address query --- .../com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8c87202a7..3ccd99736 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -109,7 +109,7 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT public List getDeliveryOutcome(GetBenRequestHandler dto) { try { String user = userRepo.getUserNamedByUserId(dto.getAshaId()); - List deliveryOutcomeList = deliveryOutcomeRepo.findByCreatedBy(user); + List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user,dto.getFromDate(),dto.getToDate()); logger.info("DeliveryOutcome Response{}",deliveryOutcomeList); return deliveryOutcomeList.stream() .map(deliveryOutcome -> mapper.convertValue(deliveryOutcome, DeliveryOutcomeDTO.class)) From 44374882f7b935540f6b2a3c9006b69d3b063166 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 23:52:47 +0530 Subject: [PATCH 160/450] optimize ben address query --- .../iemr/flw/service/UwinSessionService.java | 2 + .../service/impl/IncentiveServiceImpl.java | 16 +++++++ .../UpdateIncentivePendindDocService.java | 48 +++++++++++++++++++ .../service/impl/UwinSessionServiceImpl.java | 45 +++++++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 src/main/java/com/iemr/flw/service/impl/UpdateIncentivePendindDocService.java diff --git a/src/main/java/com/iemr/flw/service/UwinSessionService.java b/src/main/java/com/iemr/flw/service/UwinSessionService.java index 3f6ddf0ac..ce4185c35 100644 --- a/src/main/java/com/iemr/flw/service/UwinSessionService.java +++ b/src/main/java/com/iemr/flw/service/UwinSessionService.java @@ -1,5 +1,6 @@ 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; @@ -7,5 +8,6 @@ public interface UwinSessionService { UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exception; + UwinSession updateSession(UwinSessionRequestDTO req, Long recordId,Long activityId) throws Exception; List getSessionsByAsha(Integer ashaId) throws Exception; } 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 8ee38dc2d..25e5f28fc 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -13,6 +13,7 @@ import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveService; import com.iemr.flw.service.MaaMeetingService; +import com.iemr.flw.service.UwinSessionService; import com.iemr.flw.utils.JwtUtil; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -60,6 +61,9 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private ChildCareServiceImpl childCareService; + @Autowired + private UwinSessionService uwinSessionService; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -268,6 +272,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { return "Incentive update successfully"; } } + }else { if (incentiveName.name().equals(IncentiveName.MAA_QUARTERLY_MEETING.name())) { @@ -293,6 +298,17 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { return "Incentive update successfully"; } } + if(incentiveName.name().equals(IncentiveName.CHILD_MOBILIZATION_SESSIONS.name())){ + UwinSessionRequestDTO uwinSessionRequestDTO = new UwinSessionRequestDTO(); + uwinSessionRequestDTO.setAttachments(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); + UwinSession uwinSession = uwinSessionService.updateSession(uwinSessionRequestDTO,existingActivity.getRecordId(),pendingActivityDTO.getId()); + if(uwinSession!=null){ + return "Incentive update successfully"; + + } + + + } } diff --git a/src/main/java/com/iemr/flw/service/impl/UpdateIncentivePendindDocService.java b/src/main/java/com/iemr/flw/service/impl/UpdateIncentivePendindDocService.java new file mode 100644 index 000000000..bfda259f4 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/UpdateIncentivePendindDocService.java @@ -0,0 +1,48 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.iemr.IncentivePendingActivity; +import com.iemr.flw.repo.iemr.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@Service +public class UpdateIncentivePendindDocService { + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private IncentiveRecordRepo recordRepo; + + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + + public void updateIncentive(Long id) { + + Optional optionalRecord = recordRepo.findById(id); + + if (optionalRecord.isPresent()) { + IncentiveActivityRecord record = optionalRecord.get(); + record.setIsEligible(true); + recordRepo.save(record); + } + } + + public void updatePendingActivity(Integer userId, Long recordId, Long activityId, Long mIncentiveId) { + IncentivePendingActivity incentivePendingActivity = new IncentivePendingActivity(); + incentivePendingActivity.setActivityId(activityId); + incentivePendingActivity.setRecordId(recordId); + incentivePendingActivity.setUserId(userId); + incentivePendingActivity.setMincentiveId(mIncentiveId); + if (incentivePendingActivity != null) { + incentivePendingActivityRepository.save(incentivePendingActivity); + } + + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index bb2a944c9..d1a9792af 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -40,6 +40,9 @@ public class UwinSessionServiceImpl implements UwinSessionService { @Autowired private IncentiveRecordRepo recordRepo; + @Autowired + private UpdateIncentivePendindDocService updateIncentivePendindDocService; + @Override public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exception { @@ -104,6 +107,36 @@ public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exce return dto; } + @Override + public UwinSession updateSession(UwinSessionRequestDTO req,Long recordId,Long activityId) throws Exception { + Optional optionalUwinSession = repo.findById(recordId); + if(optionalUwinSession.isPresent()){ + UwinSession session = new UwinSession(); + 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); + if(session.getAttachmentsJson()!=null){ + updateIncentivePendindDocService.updateIncentive(activityId); + } + } + + + return optionalUwinSession.get(); + } @Override public List getSessionsByAsha(Integer ashaId) throws Exception { @@ -146,6 +179,12 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(session.getCreatedBy()); record.setBenId(0L); record.setAshaId(session.getAshaId()); + if(session.getAttachmentsJson()!=null){ + record.setIsEligible(true); + }else { + record.setIsEligible(false); + updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),record.getId(),incentiveActivityAM.getId()); + } record.setAmount(Long.valueOf(incentiveActivityAM.getRate())); recordRepo.save(record); } @@ -166,6 +205,12 @@ record = new IncentiveActivityRecord(); record.setBenId(0L); record.setAshaId(session.getAshaId()); record.setAmount(Long.valueOf(incentiveActivityCH.getRate())); + if(session.getAttachmentsJson()!=null){ + record.setIsEligible(true); + }else { + record.setIsEligible(false); + updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),record.getId(),incentiveActivityCH.getId()); + } recordRepo.save(record); } } From df1182b548abcb8346d83bcd7ec777eb70c35cea Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Feb 2026 23:57:44 +0530 Subject: [PATCH 161/450] optimize ben address query --- .../service/impl/IncentiveServiceImpl.java | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) 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 25e5f28fc..8b35c4db9 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -252,17 +252,18 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { logger.info("run--7"); try { - MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); - maaMeetingRequestDTO.setId(existingActivity.getRecordId()); - maaMeetingRequestDTO.setMeetingImages( - pendingActivityDTO.getImages().toArray(new MultipartFile[0]) - ); - logger.info("Activity Name from request:"+incentiveName.name()); - logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); // ✅ ENUM BASED CHECK if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ if (Objects.equals(incentiveName.name(), IncentiveName.MAA_QUARTERLY_MEETING.name())) { + MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); + maaMeetingRequestDTO.setId(existingActivity.getRecordId()); + maaMeetingRequestDTO.setMeetingImages( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]) + ); + logger.info("Activity Name from request:"+incentiveName.name()); + logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); + MaaMeeting meeting= maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, @@ -275,8 +276,16 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { }else { if (incentiveName.name().equals(IncentiveName.MAA_QUARTERLY_MEETING.name())) { + MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); + maaMeetingRequestDTO.setId(existingActivity.getRecordId()); + maaMeetingRequestDTO.setMeetingImages( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]) + ); + logger.info("Activity Name from request:"+incentiveName.name()); + logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); + - MaaMeeting meeting = maaMeetingService.updateMeetingFromFileUpload( + MaaMeeting meeting = maaMeetingService.updateMeetingFromFileUpload( maaMeetingRequestDTO, pendingActivityDTO.getId() ); From 167004fa210aed64efc311a6cf28abdd10cd03cf Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 26 Feb 2026 00:07:11 +0530 Subject: [PATCH 162/450] optimize ben address query --- .../iemr/flw/service/MaaMeetingService.java | 15 ++-- .../flw/service/impl/SammelanServiceImpl.java | 71 +++++++++++-------- .../service/impl/UwinSessionServiceImpl.java | 12 +++- 3 files changed, 61 insertions(+), 37 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index 24b1447e5..d8fdd82b5 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -111,7 +111,7 @@ public MaaMeeting updateMeeting(MaaMeetingRequestDTO req) throws JsonProcessingE return repository.save(existingMeeting); } - public MaaMeeting updateMeetingFromFileUpload(MaaMeetingRequestDTO req,Long incentiveRecordId) throws JsonProcessingException { + public MaaMeeting updateMeetingFromFileUpload(MaaMeetingRequestDTO req, Long incentiveRecordId) throws JsonProcessingException { MaaMeeting existingMeeting = repository.findById(req.getId()) .orElseThrow(() -> new EntityNotFoundException("Meeting not found: " + req.getId())); @@ -238,15 +238,21 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(meeting.getCreatedBy()); record.setBenId(0L); record.setAshaId(meeting.getAshaId()); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + if (meeting.getMeetingImagesJson() != null) { record.setIsEligible(true); + recordRepo.save(record); + } else { record.setIsEligible(false); - updatePendingActivity(meeting.getAshaId(), meeting.getId(), record.getId(),incentiveActivity.getId()); + IncentiveActivityRecord activityRecord = recordRepo.save(record); + if (activityRecord != null) { + updatePendingActivity(meeting.getAshaId(), meeting.getId(), activityRecord.getId(), incentiveActivity.getId()); + + } } - record.setAmount(Long.valueOf(incentiveActivity.getRate())); - recordRepo.save(record); } } @@ -263,5 +269,4 @@ private void updateIncentive(Long id) { } - } diff --git a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java index 53497981a..b9d035a7a 100644 --- a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java @@ -51,6 +51,8 @@ public class SammelanServiceImpl implements SammelanService { @Autowired private IncentivesRepo incentivesRepo; + @Autowired + private UpdateIncentivePendindDocService updateIncentivePendindDocService; @Override @@ -62,36 +64,36 @@ public SammelanResponseDTO submitSammelan(SammelanRequestDTO sammelanRequestDTO) // Save Sammelan record record = new SammelanRecord(); record.setAshaId(sammelanRequestDTO.getAshaId()); - logger.info("Meeting Date:"+sammelanRequestDTO.getDate()); + 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 (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()); - if(record!=null){ - record = recordRepo.save(record); - checkIncentive(record); + String imagesJson = objectMapper.writeValueAsString(base64Images); + record.setAttachments(imagesJson); + } + + if (record != null) { + record = recordRepo.save(record); + checkIncentive(record); - } - // Prepare Response DTO + } + // Prepare Response DTO response.setId(record.getId()); response.setAshaId(record.getAshaId()); Timestamp ts = Timestamp.valueOf(record.getMeetingDate().toLocalDateTime()); @@ -103,7 +105,7 @@ record = recordRepo.save(record); } catch (Exception e) { - logger.info("SammelanRecord Exception: "+e.getMessage()); + logger.info("SammelanRecord Exception: " + e.getMessage()); } return response; @@ -112,14 +114,14 @@ record = recordRepo.save(record); 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); + 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()); + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), record.getMeetingDate(), 0L, record.getAshaId()); try { if (incentiveActivityRecord == null) { incentiveActivityRecord = new IncentiveActivityRecord(); @@ -133,10 +135,21 @@ private void addSammelanIncentive(IncentiveActivity incentiveActivity, SammelanR incentiveActivityRecord.setBenId(0L); incentiveActivityRecord.setAshaId(record.getAshaId()); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivity.getRate())); - incentiveRecordRepo.save(incentiveActivityRecord); + if (record.getAttachments() != null) { + incentiveActivityRecord.setIsEligible(true); + incentiveRecordRepo.save(incentiveActivityRecord); + + } else { + incentiveActivityRecord.setIsEligible(false); + IncentiveActivityRecord activityRecord = incentiveRecordRepo.save(incentiveActivityRecord); + if (activityRecord != null) { + updateIncentivePendindDocService.updatePendingActivity(record.getAshaId(), record.getId(), activityRecord.getActivityId(), incentiveActivity.getId()); + + } + } } - }catch (Exception e){ - logger.info("SammelanRecord save Record: ",e); + } catch (Exception e) { + logger.info("SammelanRecord save Record: ", e); } diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index d1a9792af..86f62659c 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -179,14 +179,20 @@ record = new IncentiveActivityRecord(); 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); - updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),record.getId(),incentiveActivityAM.getId()); + IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); + if(incentiveActivityRecord!=null){ + updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),incentiveActivityRecord.getId(),incentiveActivityAM.getId()); + + } } - record.setAmount(Long.valueOf(incentiveActivityAM.getRate())); - recordRepo.save(record); + } } From 3e4f8c7e93e6bf0f26fe71483316ccd5c8cbfe4b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 26 Feb 2026 11:03:32 +0530 Subject: [PATCH 163/450] optimize ben address query --- .../service/impl/UwinSessionServiceImpl.java | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index 86f62659c..b63afb0ff 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -107,11 +107,19 @@ public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exce return dto; } - @Override - public UwinSession updateSession(UwinSessionRequestDTO req,Long recordId,Long activityId) throws Exception { + @Override + public UwinSession updateSession(UwinSessionRequestDTO req, Long recordId, Long activityId) throws Exception { Optional optionalUwinSession = repo.findById(recordId); - if(optionalUwinSession.isPresent()){ - UwinSession session = new UwinSession(); + + if (optionalUwinSession.isPresent()) { + UwinSession session = optionalUwinSession.get(); // ✅ Use existing session + + // Update fields if present in request + if (req.getPlace() != null) session.setPlace(req.getPlace()); + if (req.getParticipants() != null) session.setParticipants(req.getParticipants()); + if (req.getDate() != null) session.setDate(req.getDate()); + + // Update attachments if present if (req.getAttachments() != null && req.getAttachments().length > 0) { List base64Images = Arrays.stream(req.getAttachments()) .filter(file -> !file.isEmpty()) @@ -126,16 +134,16 @@ public UwinSession updateSession(UwinSessionRequestDTO req,Long recordId,Long ac String imagesJson = objectMapper.writeValueAsString(base64Images); session.setAttachmentsJson(imagesJson); - } - repo.save(session); - if(session.getAttachmentsJson()!=null){ + // Trigger incentive update if attachments exist updateIncentivePendindDocService.updateIncentive(activityId); } - } - - return optionalUwinSession.get(); + repo.save(session); // ✅ Save updated session + return session; + } else { + throw new RuntimeException("Session not found for id: " + recordId); + } } @Override From 3920c9efaa7623185ecc437fe5545ca10ac57881 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 26 Feb 2026 12:40:45 +0530 Subject: [PATCH 164/450] fix logic of upload file for death reporting --- .../service/impl/DeathReportsServiceImpl.java | 140 ++++++++++++++++-- .../service/impl/IncentiveServiceImpl.java | 59 ++++++++ 2 files changed, 183 insertions(+), 16 deletions(-) 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 43a6fa718..15d7fc1a9 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -7,6 +7,7 @@ import com.iemr.flw.dto.iemr.CdrDTO; import com.iemr.flw.dto.iemr.MdsrDTO; 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.DeathReportsService; @@ -18,6 +19,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @Service @@ -45,17 +47,20 @@ public class DeathReportsServiceImpl implements DeathReportsService { @Autowired private IncentiveRecordRepo recordRepo; + @Autowired + private UpdateIncentivePendindDocService pendindDocService; + private final Logger logger = LoggerFactory.getLogger(DeathReportsServiceImpl.class); @Override public String registerCDR(List cdrDTOs) { try { List cdrList = new ArrayList<>(); - cdrDTOs.forEach(it ->{ + cdrDTOs.forEach(it -> { CDR existingCDR = cdrRepo.findCDRByBenId(it.getBenId()); - if(existingCDR != null) { + if (existingCDR != null) { Long id = existingCDR.getId(); modelMapper.map(it, existingCDR); existingCDR.setId(id); @@ -76,15 +81,47 @@ public String registerCDR(List cdrDTOs) { } } + public String updateCDRUploadFiles(CdrDTO cdrDTOs, Long incentiveActivityId) { + try { + Optional cdrOptional = cdrRepo.findById(cdrDTOs.getId()); + CDR cdr = new CDR(); + if (cdrOptional.isPresent()) { + cdr = cdrOptional.get(); + if (cdrDTOs.getCdrImage() != null && !cdrDTOs.getCdrImage().isEmpty()) { + cdr.setCdrImage(cdrDTOs.getCdrImage()); + } + + if (cdrDTOs.getCdrImage2() != null && !cdrDTOs.getCdrImage2().isEmpty()) { + cdr.setCdrImage2(cdrDTOs.getCdrImage2()); + } + + if (cdrDTOs.getDeathCertImage1() != null && !cdrDTOs.getDeathCertImage1().isEmpty()) { + cdr.setDeathCertImage1(cdrDTOs.getDeathCertImage1()); + } + + if (cdrDTOs.getDeathCertImage2() != null && !cdrDTOs.getDeathCertImage2().isEmpty()) { + cdr.setDeathCertImage2(cdrDTOs.getDeathCertImage2()); + } + } + cdrRepo.save(cdr); + + pendindDocService.updateIncentive(incentiveActivityId); + + return "no of cdr details update: "; + } catch (Exception e) { + return "error while saving cdr details: " + e.getMessage(); + } + } + @Override public String registerMDSR(List mdsrDTOs) { try { List mdsrList = new ArrayList<>(); - mdsrDTOs.forEach(it ->{ + mdsrDTOs.forEach(it -> { MDSR mdsr = mdsrRepo.findMDSRByBenId(it.getBenId()); - if(mdsr != null) { + if (mdsr != null) { Long id = mdsr.getId(); modelMapper.map(it, mdsr); mdsr.setId(id); @@ -104,9 +141,47 @@ public String registerMDSR(List mdsrDTOs) { } } + public String updateMDSR(MdsrDTO mdsrDTO, Long incentiveActivityId) { + try { + + Optional mdsrOptional = mdsrRepo.findById(mdsrDTO.getId()); + MDSR mdsr = new MDSR(); + + if (mdsrOptional.isPresent()) { + + mdsr = mdsrOptional.get(); + + if (mdsrDTO.getMdsr1File() != null && !mdsrDTO.getMdsr1File().isEmpty()) { + mdsr.setMdsr1File(mdsrDTO.getMdsr1File()); + } + + if (mdsrDTO.getMdsr2File() != null && !mdsrDTO.getMdsr2File().isEmpty()) { + mdsr.setMdsr2File(mdsrDTO.getMdsr2File()); + } + + if (mdsrDTO.getMdsrDeathCertFile() != null && !mdsrDTO.getMdsrDeathCertFile().isEmpty()) { + mdsr.setMdsrDeathCertFile(mdsrDTO.getMdsrDeathCertFile()); + } + + } else { + return "MDSR record not found with id: " + mdsrDTO.getId(); + } + + mdsrRepo.save(mdsr); + + // incentive update + pendindDocService.updateIncentive(incentiveActivityId); + + return "MDSR updated successfully for id: " + mdsrDTO.getId(); + + } catch (Exception e) { + return "error while updating mdsr details: " + e.getMessage(); + } + } + @Override public List getCdrRecords(GetBenRequestHandler dto) { - try{ + try { String user = userRepo.getUserNamedByUserId(dto.getAshaId()); List cdrlist = cdrRepo.findByCreatedBy(user); @@ -114,7 +189,7 @@ public List getCdrRecords(GetBenRequestHandler dto) { .map(cdr -> mapper.convertValue(cdr, CdrDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error("MDSR Exception:"+e.getMessage()); + logger.error("MDSR Exception:" + e.getMessage()); // log } @@ -133,7 +208,7 @@ public List getMdsrRecords(GetBenRequestHandler dto) { .map(mdsr -> mapper.convertValue(mdsr, MdsrDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error("MDSR Exception:"+e.getMessage()); + logger.error("MDSR Exception:" + e.getMessage()); // log } @@ -142,11 +217,11 @@ public List getMdsrRecords(GetBenRequestHandler dto) { private void checkAndAddIncentives(List cdrList) { - cdrList.forEach( cdr -> { + cdrList.forEach(cdr -> { Integer userId = userRepo.getUserIdByName(cdr.getCreatedBy()); IncentiveActivity immunizationActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); - createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); + createIncentiveRecord(cdr, cdr.getBenId(), userId, immunizationActivity); }); } @@ -154,17 +229,16 @@ private void checkAndAddIncentives(List cdrList) { private void checkAndAddIncentivesMdsr(List mdsrList) { - mdsrList.forEach( mdsr -> { + mdsrList.forEach(mdsr -> { Integer userId = userRepo.getUserIdByName(mdsr.getCreatedBy()); IncentiveActivity immunizationActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MATERNAL_DEATH_REPORT", GroupName.MATERNAL_HEALTH.getDisplayName()); - createIncentiveRecord(mdsr,mdsr.getBenId(),userId,immunizationActivity); + 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); @@ -180,7 +254,26 @@ record = new IncentiveActivityRecord(); record.setBenId(benId); record.setAshaId(userId); record.setAmount(Long.valueOf(immunizationActivity.getRate())); - recordRepo.save(record); + if (userRepo.getUserRole(userId).get(0).getStateId() == StateCode.AM.getStateCode()) { + if (cdr.getDeathCertImage1() != null && cdr.getCdrImage() != null && cdr.getCdrImage2() != null && cdr.getDeathCertImage2() != null) { + record.setIsEligible(true); + recordRepo.save(record); + + } else { + record.setIsEligible(false); + IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); + if (incentiveActivityRecord == null) { + recordRepo.save(record); + pendindDocService.updatePendingActivity(userId, cdr.getId(), record.getId(), immunizationActivity.getId()); + + } + + } + } else { + recordRepo.save(record); + + } + } } @@ -199,14 +292,29 @@ record = new IncentiveActivityRecord(); record.setBenId(benId); record.setAshaId(userId); record.setAmount(Long.valueOf(immunizationActivity.getRate())); - recordRepo.save(record); - } - } + if (userRepo.getUserRole(userId).get(0).getStateId() == StateCode.AM.getStateCode()) { + if (mdsr.getMdsrDeathCertFile() != null && mdsr.getMdsr1File() != null && mdsr.getMdsr2File() != null) { + record.setIsEligible(true); + recordRepo.save(record); + + } else { + record.setIsEligible(false); + IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); + if (incentiveActivityRecord == null) { + recordRepo.save(record); + pendindDocService.updatePendingActivity(userId, mdsr.getId(), record.getId(), immunizationActivity.getId()); + } + } + } else { + recordRepo.save(record); + } + } + } } 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 8b35c4db9..ea84e929f 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -1,5 +1,6 @@ package com.iemr.flw.service.impl; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; @@ -22,6 +23,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; import java.math.BigInteger; import java.sql.Timestamp; import java.time.LocalDate; @@ -64,6 +66,9 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private UwinSessionService uwinSessionService; + @Autowired + private DeathReportsServiceImpl deathReportsService; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -318,6 +323,52 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } + if (pendingActivityDTO != null + && incentiveName != null + && IncentiveName.CHILD_DEATH_REPORTING.name().equals(incentiveName.name())) { + + CdrDTO cdrDTO = new CdrDTO(); + List images = pendingActivityDTO.getImages(); + + if (images != null && !images.isEmpty()) { + + if (images.size() > 0 && images.get(0) != null && !images.get(0).isEmpty()) + cdrDTO.setCdrImage(convertAttachmentsToJson(images.get(0))); + + if (images.size() > 1 && images.get(1) != null && !images.get(1).isEmpty()) + cdrDTO.setCdrImage2(convertAttachmentsToJson(images.get(1))); + + if (images.size() > 2 && images.get(2) != null && !images.get(2).isEmpty()) + cdrDTO.setDeathCertImage1(convertAttachmentsToJson(images.get(2))); + + if (images.size() > 3 && images.get(3) != null && !images.get(3).isEmpty()) + cdrDTO.setDeathCertImage2(convertAttachmentsToJson(images.get(3))); + } + + deathReportsService.updateCDRUploadFiles(cdrDTO, pendingActivityDTO.getId()); + } + + if (pendingActivityDTO != null + && incentiveName != null + && IncentiveName.MATERNAL_DEATH_REPORT.name().equals(incentiveName.name())) { + + MdsrDTO mdsrDTO = new MdsrDTO(); + List images = pendingActivityDTO.getImages(); + + if (images != null && !images.isEmpty()) { + + if (images.size() > 0 && images.get(0) != null && !images.get(0).isEmpty()) + mdsrDTO.setMdsr1File(convertAttachmentsToJson(images.get(0))); + + if (images.size() > 1 && images.get(1) != null && !images.get(1).isEmpty()) + mdsrDTO.setMdsr2File(convertAttachmentsToJson(images.get(1))); + + if (images.size() > 2 && images.get(2) != null && !images.get(2).isEmpty()) + mdsrDTO.setMdsrDeathCertFile(convertAttachmentsToJson(images.get(2))); + } + deathReportsService.updateMDSR(mdsrDTO, pendingActivityDTO.getId()); + + } } @@ -334,6 +385,14 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { return null; } + public String convertAttachmentsToJson(MultipartFile file) { + try { + String base64 = Base64.getEncoder().encodeToString(file.getBytes()); + return new ObjectMapper().writeValueAsString(base64); + } catch (Exception e) { + throw new RuntimeException("Error converting file", e); + } + } private void checkMonthlyAshaIncentive(Integer 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()); From 9d2163de944722eacbcf954c5839f9bd71bc16ab Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 26 Feb 2026 12:49:12 +0530 Subject: [PATCH 165/450] fix logic of upload file for death reporting --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 ea84e929f..bbf28e4dd 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -328,6 +328,8 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { && IncentiveName.CHILD_DEATH_REPORTING.name().equals(incentiveName.name())) { CdrDTO cdrDTO = new CdrDTO(); + cdrDTO.setId(existingActivity.getRecordId()); + List images = pendingActivityDTO.getImages(); if (images != null && !images.isEmpty()) { @@ -354,7 +356,7 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { MdsrDTO mdsrDTO = new MdsrDTO(); List images = pendingActivityDTO.getImages(); - + mdsrDTO.setId(existingActivity.getRecordId()); if (images != null && !images.isEmpty()) { if (images.size() > 0 && images.get(0) != null && !images.get(0).isEmpty()) From 77ed884a9ad00cca8e6e98b4cf03c9b0ec1b9802 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 10:25:21 +0530 Subject: [PATCH 166/450] Add feature for asha supervisor for incentive approval --- .../AshaSupervisorIncentiveApproval.java | 47 +++ .../domain/iemr/AshaSupervisorMapping.java | 34 ++ .../domain/iemr/IncentiveActivityRecord.java | 3 + .../dto/iemr/AshaByFacilityRequestDTO.java | 10 + .../repo/iemr/AshaSupervisorLoginRepo.java | 42 +++ .../iemr/flw/repo/iemr/FacilityLoginRepo.java | 65 ++++ .../flw/repo/iemr/IncentiveRecordRepo.java | 8 + .../iemr/flw/repo/iemr/IncentivesRepo.java | 10 + .../impl/AshaSupervisorLoginService.java | 303 ++++++++++++++++++ 9 files changed, 522 insertions(+) create mode 100644 src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/AshaSupervisorMapping.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java create mode 100644 src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java new file mode 100644 index 000000000..1bbec7b77 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -0,0 +1,47 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.dto.iemr.AshaByFacilityRequestDTO; +import com.iemr.flw.service.impl.AshaSupervisorLoginService; +import org.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@RestController +@RequestMapping("/ashaSupervisor") +public class AshaSupervisorIncentiveApproval { + + @Autowired + private AshaSupervisorLoginService ashaSupervisorLoginService; + + @PostMapping("/getAshaList") + public ResponseEntity getAshaList(@RequestBody AshaByFacilityRequestDTO request) { + try { + List> result = ashaSupervisorLoginService.getAshasAtFacility( + request.getSuperVisorId(), + request.getFacilityId() + ); + + Map response = new HashMap<>(); + response.put("data", result); + response.put("statusCode", 200); + + return ResponseEntity.status(HttpStatus.OK).body(response); + + } catch (Exception e) { + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Server error: " + e.getMessage()); + } + } + +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/AshaSupervisorMapping.java b/src/main/java/com/iemr/flw/domain/iemr/AshaSupervisorMapping.java new file mode 100644 index 000000000..ee641db8b --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AshaSupervisorMapping.java @@ -0,0 +1,34 @@ +package com.iemr.flw.domain.iemr; + +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 lombok.Data; +import lombok.NoArgsConstructor; + +@Entity +@Table(name = "asha_supervisor_mapping") +@Data +@NoArgsConstructor +public class AshaSupervisorMapping { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private Long id; + + @Column(name = "supervisorUserID") + private Integer supervisorUserID; + + @Column(name = "ashaUserID") + private Integer ashaUserID; + + @Column(name = "facilityID") + private Integer facilityID; + + @Column(name = "deleted", insertable = false, updatable = true) + private Boolean deleted; +} \ No newline at end of file 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 f4adf8df3..d2392b24f 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -52,4 +52,7 @@ public class IncentiveActivityRecord { @Column(name = "is_default_activity") private Boolean isDefaultActivity; + + @Column(name = "approval_status") + Integer approvalStatus; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java new file mode 100644 index 000000000..1a99f83be --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java @@ -0,0 +1,10 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AshaByFacilityRequestDTO { + Integer userId; + Integer superVisorId; + Integer facilityId; +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java new file mode 100644 index 000000000..637281270 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -0,0 +1,42 @@ +package com.iemr.flw.repo.iemr; + +import java.util.ArrayList; +import java.util.List; + +import com.iemr.flw.domain.iemr.AshaSupervisorMapping; +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; + +@Repository +public interface AshaSupervisorLoginRepo extends CrudRepository { + + ArrayList findBySupervisorUserIDAndDeletedFalse(Integer supervisorUserID); + + // API 1: All ASHAs mapped to a supervisor with facility info + @Query(value = "SELECT DISTINCT asm.ashaUserID, u.FirstName, u.LastName, " + + "f.FacilityID, f.FacilityName, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.ashaUserID AND u.Deleted = false " + + "JOIN m_facility f ON f.FacilityID = asm.facilityID AND f.Deleted = false " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.deleted = false", nativeQuery = true) + List getAllMappedAshas(@Param("supervisorUserID") Integer supervisorUserID); + + // API 2: ASHAs at a specific facility for a supervisor with user details + @Query(value = "SELECT DISTINCT asm.ashaUserID, u.FirstName, u.LastName, " + + "COALESCE(u.AgentID,'') AS agentID, " + + "COALESCE(u.EmergencyContactNo,'') AS mobile, " + + "COALESCE(g.GenderName,'') AS gender " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.ashaUserID AND u.Deleted = false " + + "LEFT JOIN m_gender g ON g.GenderID = u.GenderID " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.facilityID = :facilityID " + + "AND asm.deleted = false", nativeQuery = true) + List getAshasAtFacility(@Param("supervisorUserID") Integer supervisorUserID, + @Param("facilityID") Integer facilityID); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java new file mode 100644 index 000000000..dd10196a2 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java @@ -0,0 +1,65 @@ +package com.iemr.flw.repo.iemr; + +import java.util.List; + +import com.iemr.flw.domain.iemr.AshaSupervisorMapping; +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; + + +@Repository +public interface FacilityLoginRepo extends CrudRepository { + + // Get user's facility IDs from m_UserServiceRoleMapping (for ANY user) + @Query(value = "SELECT DISTINCT usrm.FacilityID " + + "FROM m_UserServiceRoleMapping usrm " + + "WHERE usrm.UserID = :userID AND usrm.Deleted = false " + + "AND usrm.FacilityID IS NOT NULL", nativeQuery = true) + List getUserFacilityIDs(@Param("userID") Integer userID); + + // Get facility details with geo names and facilityType + @Query(value = "SELECT DISTINCT f.FacilityID, f.FacilityName, " + + "f.StateID, COALESCE(s.StateName,'') AS stateName, " + + "f.DistrictID, COALESCE(d.DistrictName,'') AS districtName, " + + "f.BlockID, COALESCE(b.BlockName,'') AS blockName, " + + "COALESCE(f.RuralUrban,'') AS ruralUrban, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "FROM m_facility f " + + "LEFT JOIN m_state s ON s.StateID = f.StateID " + + "LEFT JOIN m_district d ON d.DistrictID = f.DistrictID " + + "LEFT JOIN m_districtblock b ON b.BlockID = f.BlockID " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "WHERE f.FacilityID IN :facilityIDs AND f.Deleted = false", nativeQuery = true) + List getFacilityDetails(@Param("facilityIDs") List facilityIDs); + + // ASHA login: get supervisor details + @Query(value = "SELECT asm.supervisorUserID, u.FirstName, u.LastName, u.ContactNo " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.supervisorUserID " + + "WHERE asm.ashaUserID = :ashaUserID AND asm.deleted = false " + + "AND u.Deleted = false LIMIT 1", nativeQuery = true) + List getSupervisorForAsha(@Param("ashaUserID") Integer ashaUserID); + + @Query(value = "SELECT GenderName FROM m_gender WHERE GenderID = :genderID", nativeQuery = true) + String getGenderName(@Param("genderID") Integer genderID); + + // Villages mapped to facilities + @Query(value = "SELECT fvm.FacilityID, fvm.DistrictBranchID, dbm.VillageName " + + "FROM facility_village_mapping fvm " + + "JOIN m_DistrictBranchMapping dbm ON dbm.DistrictBranchID = fvm.DistrictBranchID " + + "WHERE fvm.FacilityID IN :facilityIDs AND fvm.Deleted = false", nativeQuery = true) + List getVillagesForFacilities(@Param("facilityIDs") List facilityIDs); + + // ASHA login: get peers at same facility (ANM, CHO, etc.) + @Query(value = "SELECT DISTINCT usrm.UserID, u.FirstName, u.LastName, r.RoleName " + + "FROM m_UserServiceRoleMapping usrm " + + "JOIN m_User u ON u.UserID = usrm.UserID " + + "JOIN m_Role r ON r.RoleID = usrm.RoleID " + + "WHERE usrm.FacilityID IN :facilityIDs " + + "AND usrm.UserID != :currentUserID " + + "AND usrm.Deleted = false AND u.Deleted = false", nativeQuery = true) + List getPeersAtFacility(@Param("facilityIDs") List facilityIDs, + @Param("currentUserID") Integer currentUserID); +} \ No newline at end of file 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 0c2dc21b5..bedc77ffd 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -44,4 +44,12 @@ IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( @Query("select record from IncentiveActivityRecord record where record.ashaId = :ashaId") List findRecordsByAsha(@Param("ashaId") Integer ashaId); + + @Query("SELECT " + + "SUM(CASE WHEN record.approvalStatus = 101 THEN 1 ELSE 0 END), " + + "SUM(CASE WHEN record.approvalStatus = 102 THEN 1 ELSE 0 END), " + + "SUM(CASE WHEN record.approvalStatus = 103 THEN 1 ELSE 0 END) " + + "FROM IncentiveActivityRecord record " + + "WHERE record.ashaId = :ashaId") + List getStatusCountByAshaId(@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 112f74ef5..170f7a32d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java @@ -28,4 +28,14 @@ IncentiveActivity findIncentiveMasterById( @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); + + @Query(value = "SELECT " + + "SUM(CASE WHEN i.approval_status = 101 THEN 1 ELSE 0 END) as pendingCount, " + + "SUM(CASE WHEN i.approval_status = 102 THEN 1 ELSE 0 END) as approvalCount, " + + "SUM(CASE WHEN i.approval_status = 103 THEN 1 ELSE 0 END) as rejectCount " + + "FROM m_incentive_activity i " + + "WHERE i.asha_id = :ashaId " + + "AND i.is_deleted = false", + nativeQuery = true) + Object[] getStatusCountByAshaId(@Param("ashaId") Integer ashaId); } diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java new file mode 100644 index 000000000..f7398da92 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -0,0 +1,303 @@ +package com.iemr.flw.service.impl; + +import java.util.*; + +import com.iemr.flw.domain.iemr.AshaSupervisorMapping; +import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; +import com.iemr.flw.repo.iemr.FacilityLoginRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import org.json.JSONArray; +import org.json.JSONObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + + +@Service +public class AshaSupervisorLoginService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private AshaSupervisorLoginRepo ashaSupervisorLoginRepo; + + @Autowired + private FacilityLoginRepo facilityLoginRepo; + + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + /** + * Common facilityData block for ALL users. + * Returns empty structure if user has no facility mapping. + */ + public JSONObject buildFacilityLoginData(Long userID, String roleName) { + JSONObject result = new JSONObject(); + result.put("location", buildEmptyLocation()); + try { + if ("ASHA Supervisor".equalsIgnoreCase(roleName)) { + enrichAshaSupervisorData(result, userID.intValue()); + } else if ("ASHA".equalsIgnoreCase(roleName)) { + enrichAshaData(result, userID.intValue()); + } else { + enrichGeneralFacilityData(result, userID.intValue()); + } + } catch (Exception e) { + logger.error("Error building facility login data for userID " + userID + ": " + e.getMessage(), e); + } + return result; + } + + private JSONObject buildEmptyLocation() { + return new JSONObject() + .put("state", "") + .put("district", "") + .put("blockOrUlb", "") + .put("locationType", ""); + } + + // ==================== ASHA ==================== + + private void enrichAshaData(JSONObject result, Integer ashaUserID) { + List facilityIDs = facilityLoginRepo.getUserFacilityIDs(ashaUserID); + if (facilityIDs == null || facilityIDs.isEmpty()) + return; + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) + return; + + populateLocation(result, facilityRows.get(0)); + + // ASHA gets a single facility (first mapped) + Object[] row = facilityRows.get(0); + JSONObject facility = new JSONObject(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + result.put("facility", facility); + + // Supervisor details + List supervisorRows = facilityLoginRepo.getSupervisorForAsha(ashaUserID); + if (supervisorRows != null && !supervisorRows.isEmpty()) { + Object[] sRow = supervisorRows.get(0); + JSONObject supervisor = new JSONObject(); + supervisor.put("userId", sRow[0]); + supervisor.put("fullName", fullName(sRow[1], sRow[2])); + supervisor.put("mobile", str(sRow[3])); + result.put("supervisor", supervisor); + } else { + result.put("supervisor", JSONObject.NULL); + } + + // Peers at same facility + List peerRows = facilityLoginRepo.getPeersAtFacility(facilityIDs, ashaUserID); + JSONArray peers = new JSONArray(); + if (peerRows != null) { + for (Object[] pRow : peerRows) { + JSONObject peer = new JSONObject(); + peer.put("userId", pRow[0]); + peer.put("fullName", fullName(pRow[1], pRow[2])); + peer.put("role", str(pRow[3])); + peers.put(peer); + } + } + result.put("peersAtFacility", peers); + } + + // ==================== ASHA Supervisor ==================== + + private void enrichAshaSupervisorData(JSONObject result, Integer supervisorUserID) { + ArrayList mappings = ashaSupervisorLoginRepo + .findBySupervisorUserIDAndDeletedFalse(supervisorUserID); + if (mappings == null || mappings.isEmpty()) + return; + + Set facilityIDSet = new HashSet<>(); + for (AshaSupervisorMapping m : mappings) { + if (m.getFacilityID() != null) + facilityIDSet.add(m.getFacilityID()); + } + if (facilityIDSet.isEmpty()) + return; + List facilityIDs = new ArrayList<>(facilityIDSet); + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) + return; + + populateLocation(result, facilityRows.get(0)); + + JSONArray facilitiesArray = new JSONArray(); + for (Object[] row : facilityRows) { + JSONObject facility = new JSONObject(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + facilitiesArray.put(facility); + } + result.put("facilities", facilitiesArray); + + // Count distinct ASHAs mapped to this supervisor + Set ashaUserIDs = new HashSet<>(); + for (AshaSupervisorMapping m : mappings) { + if (m.getAshaUserID() != null) + ashaUserIDs.add(m.getAshaUserID()); + } + result.put("totalAshaCount", ashaUserIDs.size()); + } + + // ==================== General Facility User (CHO, ANM, etc.) + // ==================== + + private void enrichGeneralFacilityData(JSONObject result, Integer userID) { + List facilityIDs = facilityLoginRepo.getUserFacilityIDs(userID); + if (facilityIDs == null || facilityIDs.isEmpty()) + return; + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) + return; + + populateLocation(result, facilityRows.get(0)); + + JSONArray facilitiesArray = new JSONArray(); + for (Object[] row : facilityRows) { + JSONObject facility = new JSONObject(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + facilitiesArray.put(facility); + } + result.put("facilities", facilitiesArray); + } + + // ==================== Shared Helpers ==================== + + private void populateLocation(JSONObject result, Object[] facilityRow) { + JSONObject location = new JSONObject(); + location.put("state", str(facilityRow[3])); + location.put("district", str(facilityRow[5])); + location.put("blockOrUlb", str(facilityRow[7])); + location.put("locationType", str(facilityRow[8])); + result.put("location", location); + } + + private String str(Object val) { + return val != null ? val.toString() : ""; + } + + private String fullName(Object first, Object last) { + return (str(first) + " " + str(last)).trim(); + } + + /** + * API 1: Get all ASHAs mapped to this supervisor with facility info. + */ + public JSONObject getSupervisorAshas(Integer supervisorUserID) { + JSONObject result = new JSONObject(); + JSONArray ashas = new JSONArray(); + + List rows = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorUserID); + if (rows == null || rows.isEmpty()) { + result.put("totalAshaCount", 0); + result.put("ashas", ashas); + return result; + } + + // Collect distinct facility IDs and build village map + Set facilityIDSet = new HashSet<>(); + for (Object[] row : rows) { + if (row[3] != null) + facilityIDSet.add((Integer) row[3]); + } + + Map> villageMap = new HashMap<>(); + if (!facilityIDSet.isEmpty()) { + List villageRows = facilityLoginRepo + .getVillagesForFacilities(new ArrayList<>(facilityIDSet)); + if (villageRows != null) { + for (Object[] vRow : villageRows) { + Integer facID = (Integer) vRow[0]; + JSONObject village = new JSONObject(); + village.put("villageId", vRow[1]); + village.put("villageName", str(vRow[2])); + villageMap.computeIfAbsent(facID, k -> new ArrayList<>()).add(village); + } + } + } + + for (Object[] row : rows) { + Integer facilityID = (Integer) row[3]; + JSONObject asha = new JSONObject(); + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("facilityId", facilityID); + asha.put("facilityName", str(row[4])); + asha.put("facilityType", str(row[5])); + + JSONArray villages = new JSONArray(); + List vList = villageMap.get(facilityID); + if (vList != null) { + for (JSONObject v : vList) + villages.put(v); + } + asha.put("villages", villages); + + ashas.put(asha); + } + + result.put("totalAshaCount", ashas.length()); + result.put("ashas", ashas); + return result; + } + + /** + * API 2: Get ASHAs at a specific facility for this supervisor with detailed + * info. + */ + + + public List> getAshasAtFacility(Integer supervisorId, Integer facilityId) { + + List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId); + List> ashaList = new ArrayList<>(); + Map asha = new HashMap<>(); + + for (Object[] row : rows) { + + Integer ashaId = ((Number) row[0]).intValue(); + List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId); + + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); + asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); + asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); + + if (countList != null && !countList.isEmpty()) { + Object[] counts = countList.get(0); + asha.put("pendingCount", counts[0] != null ? counts[0] : 0); + asha.put("approvalCount", counts[1] != null ? counts[1] : 0); + asha.put("rejectCount", counts[2] != null ? counts[2] : 0); + } else { + asha.put("pendingCount", 0); + asha.put("approvalCount", 0); + asha.put("rejectCount", 0); + } + + ashaList.add(asha); + } + + return ashaList; + } + + public String getGenderName(Integer genderID) { + if (genderID == null) + return null; + return facilityLoginRepo.getGenderName(genderID); + } +} \ No newline at end of file From 39cee900ed254320bc966498c92b113c991014b8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 10:41:18 +0530 Subject: [PATCH 167/450] Add feature for asha supervisor for incentive approval --- .../AshaSupervisorIncentiveApproval.java | 45 ++- .../repo/iemr/SupervisorDashboardRepo.java | 89 ++++++ .../service/SupervisorDashboardService.java | 6 + .../impl/SupervisorDashboardServiceImpl.java | 261 ++++++++++++++++++ 4 files changed, 395 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java create mode 100644 src/main/java/com/iemr/flw/service/SupervisorDashboardService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 1bbec7b77..c3fc66f37 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -1,15 +1,18 @@ package com.iemr.flw.controller; import com.iemr.flw.dto.iemr.AshaByFacilityRequestDTO; +import com.iemr.flw.service.SupervisorDashboardService; import com.iemr.flw.service.impl.AshaSupervisorLoginService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.response.OutputResponse; +import io.swagger.v3.oas.annotations.Operation; import org.json.JSONObject; +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.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; @@ -23,8 +26,16 @@ public class AshaSupervisorIncentiveApproval { @Autowired private AshaSupervisorLoginService ashaSupervisorLoginService; - @PostMapping("/getAshaList") - public ResponseEntity getAshaList(@RequestBody AshaByFacilityRequestDTO request) { + @Autowired + private SupervisorDashboardService supervisorDashboardService; + + @Autowired + private JwtUtil jwtUtil; + + + + @PostMapping("/getAshaListByFacility") + public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityRequestDTO request) { try { List> result = ashaSupervisorLoginService.getAshasAtFacility( request.getSuperVisorId(), @@ -44,4 +55,26 @@ public ResponseEntity getAshaList(@RequestBody AshaByFacilityRequestDTO reque } } + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + + + @Operation(summary = "Get comprehensive ASHA Supervisor dashboard with facilities, ASHAs, villages and incentive data") + @PostMapping("/dashboard") + public String getSupervisorDashboard(@RequestHeader(value = "JwtToken") String token ) { + OutputResponse response = new OutputResponse(); + + try { + if(token!=null){ + String result = supervisorDashboardService.getSupervisorDashboard(jwtUtil.extractUserId(token)); + response.setResponse(result); + } + + } catch (Exception e) { + logger.error("getSupervisorDashboard failed: " + e.getMessage(), e); + response.setError(e); + } + return response.toString(); + } + } diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java new file mode 100644 index 000000000..ee5ce32f1 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -0,0 +1,89 @@ +package com.iemr.flw.repo.iemr; + +import java.util.List; + +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.IncentiveActivityRecord; + +@Repository +public interface SupervisorDashboardRepo extends JpaRepository { + + // Get all ASHA userIDs mapped to a supervisor + @Query(value = "SELECT DISTINCT asm.ashaUserID " + + "FROM asha_supervisor_mapping asm " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.deleted = false", nativeQuery = true) + List getAshaIdsBySupervisor(@Param("supervisorUserID") Integer supervisorUserID); + + // Get ASHAs with facility info for a supervisor + @Query(value = "SELECT DISTINCT asm.ashaUserID, u.FirstName, u.LastName, " + + "f.FacilityID, f.FacilityName, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName, " + + "COALESCE(u.AgentID,'') AS agentID, " + + "COALESCE(u.EmergencyContactNo,'') AS mobile, " + + "COALESCE(g.GenderName,'') AS gender " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.ashaUserID AND u.Deleted = false " + + "JOIN m_facility f ON f.FacilityID = asm.facilityID AND f.Deleted = false " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "LEFT JOIN m_gender g ON g.GenderID = u.GenderID " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.deleted = false", nativeQuery = true) + List getAshasWithFacilityInfo(@Param("supervisorUserID") Integer supervisorUserID); + + // Get facility details with geo names + @Query(value = "SELECT DISTINCT f.FacilityID, f.FacilityName, " + + "COALESCE(s.StateName,'') AS stateName, " + + "COALESCE(d.DistrictName,'') AS districtName, " + + "COALESCE(b.BlockName,'') AS blockName, " + + "COALESCE(f.RuralUrban,'') AS ruralUrban, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "FROM m_facility f " + + "LEFT JOIN m_state s ON s.StateID = f.StateID " + + "LEFT JOIN m_district d ON d.DistrictID = f.DistrictID " + + "LEFT JOIN m_districtblock b ON b.BlockID = f.BlockID " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "WHERE f.FacilityID IN :facilityIDs AND f.Deleted = false", nativeQuery = true) + List getFacilityDetails(@Param("facilityIDs") List facilityIDs); + + // Villages mapped to facilities + @Query(value = "SELECT fvm.FacilityID, fvm.DistrictBranchID, dbm.VillageName " + + "FROM facility_village_mapping fvm " + + "JOIN m_DistrictBranchMapping dbm ON dbm.DistrictBranchID = fvm.DistrictBranchID " + + "WHERE fvm.FacilityID IN :facilityIDs AND fvm.Deleted = false", nativeQuery = true) + List getVillagesForFacilities(@Param("facilityIDs") List facilityIDs); + + // Incentive status counts per ASHA: verified, rejected, pending, total amount + @Query(value = "SELECT iar.asha_id, " + + "COUNT(*) AS totalRecords, " + + "SUM(CASE WHEN iar.approval_status = 101 THEN 1 ELSE 0 END) AS verified, " + + "SUM(CASE WHEN iar.approval_status = 102 THEN 1 ELSE 0 END) AS rejected, " + + "SUM(CASE WHEN iar.approval_status = 103 THEN 1 ELSE 0 END) AS pending, " + + "COALESCE(SUM(CASE WHEN iar.approval_status = 101 THEN iar.amount ELSE 0 END), 0) AS totalAmount " + + "FROM incentive_activity_record iar " + + "WHERE iar.asha_id IN :ashaIds " + + "GROUP BY iar.asha_id", nativeQuery = true) + List getIncentiveStatusByAshaIds(@Param("ashaIds") List ashaIds); + + // Incentive activity history per ASHA (recent records) + @Query(value = "SELECT iar.asha_id, iar.name AS activityName, " + + "iar.amount, iar.is_eligible, iar.created_date " + + "FROM incentive_activity_record iar " + + "WHERE iar.asha_id IN :ashaIds " + + "ORDER BY iar.created_date DESC", nativeQuery = true) + List getIncentiveHistoryByAshaIds(@Param("ashaIds") List ashaIds); + + // Supervisor user details + @Query(value = "SELECT u.UserID, u.FirstName, u.LastName, " + + "COALESCE(u.AgentID,'') AS agentID, " + + "COALESCE(u.EmergencyContactNo,'') AS mobile, " + + "COALESCE(g.GenderName,'') AS gender " + + "FROM m_User u " + + "LEFT JOIN m_gender g ON g.GenderID = u.GenderID " + + "WHERE u.UserID = :userId AND u.Deleted = false", nativeQuery = true) + List getSupervisorUserDetails(@Param("userId") Integer userId); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java new file mode 100644 index 000000000..2db8a724e --- /dev/null +++ b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java @@ -0,0 +1,6 @@ +package com.iemr.flw.service; + +public interface SupervisorDashboardService { + + String getSupervisorDashboard(Integer supervisorUserID); +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java new file mode 100644 index 000000000..752f4decd --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -0,0 +1,261 @@ +package com.iemr.flw.service.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.iemr.flw.repo.iemr.SupervisorDashboardRepo; +import com.iemr.flw.service.SupervisorDashboardService; + +@Service +public class SupervisorDashboardServiceImpl implements SupervisorDashboardService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private SupervisorDashboardRepo dashboardRepo; + + @Override + public String getSupervisorDashboard(Integer supervisorUserID) { + JSONObject result = new JSONObject(); + + // 1. Supervisor user details + List supervisorRows = dashboardRepo.getSupervisorUserDetails(supervisorUserID); + if (supervisorRows != null && !supervisorRows.isEmpty()) { + Object[] sRow = supervisorRows.get(0); + JSONObject supervisor = new JSONObject(); + supervisor.put("userId", sRow[0]); + supervisor.put("fullName", fullName(sRow[1], sRow[2])); + supervisor.put("employeeId", str(sRow[3]).isEmpty() ? JSONObject.NULL : str(sRow[3])); + supervisor.put("mobile", str(sRow[4]).isEmpty() ? JSONObject.NULL : str(sRow[4])); + supervisor.put("gender", str(sRow[5]).isEmpty() ? JSONObject.NULL : str(sRow[5])); + result.put("supervisor", supervisor); + } + + // 2. Get all ASHAs with facility info + List ashaRows = dashboardRepo.getAshasWithFacilityInfo(supervisorUserID); + if (ashaRows == null || ashaRows.isEmpty()) { + result.put("totalAshaCount", 0); + result.put("incentiveSummary", buildEmptyIncentiveSummary()); + result.put("facilities", new JSONArray()); + return result.toString(); + } + + // Collect distinct facility IDs and ASHA IDs + Set facilityIDSet = new HashSet<>(); + Set ashaIDSet = new HashSet<>(); + for (Object[] row : ashaRows) { + if (row[3] != null) + facilityIDSet.add((Integer) row[3]); + if (row[0] != null) + ashaIDSet.add((Integer) row[0]); + } + List facilityIDs = new ArrayList<>(facilityIDSet); + List ashaIDs = new ArrayList<>(ashaIDSet); + + result.put("totalAshaCount", ashaIDs.size()); + + // 3. Location from first facility + List facilityRows = dashboardRepo.getFacilityDetails(facilityIDs); + if (facilityRows != null && !facilityRows.isEmpty()) { + Object[] fRow = facilityRows.get(0); + JSONObject location = new JSONObject(); + location.put("state", str(fRow[2])); + location.put("district", str(fRow[3])); + location.put("blockOrUlb", str(fRow[4])); + location.put("locationType", str(fRow[5])); + result.put("location", location); + } + + // 4. Build village map (facilityID -> villages) + Map> villageMap = new HashMap<>(); + List villageRows = dashboardRepo.getVillagesForFacilities(facilityIDs); + if (villageRows != null) { + for (Object[] vRow : villageRows) { + Integer facID = (Integer) vRow[0]; + JSONObject village = new JSONObject(); + village.put("villageId", vRow[1]); + village.put("villageName", str(vRow[2])); + villageMap.computeIfAbsent(facID, k -> new ArrayList<>()).add(village); + } + } + + // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) + Map incentiveStatusMap = new HashMap<>(); + long overallVerified = 0, overallRejected = 0, overallPending = 0, overallTotalAmount = 0; + try { + List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs); + if (statusRows != null) { + for (Object[] sRow : statusRows) { + Integer ashaId = (Integer) sRow[0]; + long total = ((Number) sRow[1]).longValue(); + long verified = ((Number) sRow[2]).longValue(); + long rejected = ((Number) sRow[3]).longValue(); + long pending = ((Number) sRow[4]).longValue(); + long totalAmount = ((Number) sRow[5]).longValue(); + + JSONObject status = new JSONObject(); + status.put("totalRecords", total); + status.put("verified", verified); + status.put("rejected", rejected); + status.put("pending", pending); + status.put("totalAmount", totalAmount); + incentiveStatusMap.put(ashaId, status); + + overallVerified += verified; + overallRejected += rejected; + overallPending += pending; + overallTotalAmount += totalAmount; + } + } + } catch (Exception e) { + logger.error("Error fetching incentive status: " + e.getMessage(), e); + } + + // Overall incentive summary across all ASHAs + JSONObject overallSummary = new JSONObject(); + overallSummary.put("verified", overallVerified); + overallSummary.put("rejected", overallRejected); + overallSummary.put("pending", overallPending); + overallSummary.put("totalAmount", overallTotalAmount); + result.put("incentiveSummary", overallSummary); + + // 6. Get incentive history per ASHA + Map> historyMap = new HashMap<>(); + try { + List historyRows = dashboardRepo.getIncentiveHistoryByAshaIds(ashaIDs); + if (historyRows != null) { + for (Object[] hRow : historyRows) { + Integer ashaId = (Integer) hRow[0]; + JSONObject record = new JSONObject(); + record.put("activityName", str(hRow[1])); + record.put("amount", hRow[2]); + String status; + if (hRow[3] == null) { + status = "pending"; + } else if ((Boolean) hRow[3]) { + status = "verified"; + } else { + status = "rejected"; + } + record.put("status", status); + record.put("createdDate", hRow[4] != null ? hRow[4].toString() : JSONObject.NULL); + historyMap.computeIfAbsent(ashaId, k -> new ArrayList<>()).add(record); + } + } + } catch (Exception e) { + logger.error("Error fetching incentive history: " + e.getMessage(), e); + } + + // 7. Build facilities array with nested ASHAs + Map> ashasByFacility = new HashMap<>(); + for (Object[] row : ashaRows) { + Integer facID = (Integer) row[3]; + ashasByFacility.computeIfAbsent(facID, k -> new ArrayList<>()).add(row); + } + + Map facilityDetailsMap = new HashMap<>(); + if (facilityRows != null) { + for (Object[] fRow : facilityRows) { + facilityDetailsMap.put((Integer) fRow[0], fRow); + } + } + + JSONArray facilitiesArray = new JSONArray(); + for (Integer facID : facilityIDs) { + JSONObject facility = new JSONObject(); + facility.put("facilityId", facID); + + Object[] fDetails = facilityDetailsMap.get(facID); + if (fDetails != null) { + facility.put("facilityName", str(fDetails[1])); + facility.put("facilityType", str(fDetails[6])); + } + + // Villages + JSONArray villages = new JSONArray(); + List vList = villageMap.get(facID); + if (vList != null) { + for (JSONObject v : vList) + villages.put(v); + } + facility.put("villages", villages); + + // ASHAs at this facility + JSONArray ashasArray = new JSONArray(); + List facAshaRows = ashasByFacility.get(facID); + if (facAshaRows != null) { + for (Object[] row : facAshaRows) { + Integer ashaId = (Integer) row[0]; + JSONObject asha = new JSONObject(); + asha.put("userId", ashaId); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[6]).isEmpty() ? JSONObject.NULL : str(row[6])); + asha.put("mobile", str(row[7]).isEmpty() ? JSONObject.NULL : str(row[7])); + asha.put("gender", str(row[8]).isEmpty() ? JSONObject.NULL : str(row[8])); + + // Individual ASHA incentive status + JSONObject incentive = new JSONObject(); + JSONObject ashaStatus = incentiveStatusMap.get(ashaId); + if (ashaStatus != null) { + incentive.put("verified", ashaStatus.get("verified")); + incentive.put("rejected", ashaStatus.get("rejected")); + incentive.put("pending", ashaStatus.get("pending")); + incentive.put("totalAmount", ashaStatus.get("totalAmount")); + } else { + incentive.put("verified", 0); + incentive.put("rejected", 0); + incentive.put("pending", 0); + incentive.put("totalAmount", 0); + } + + // History with status per record + JSONArray history = new JSONArray(); + List hList = historyMap.get(ashaId); + if (hList != null) { + for (JSONObject h : hList) + history.put(h); + } + incentive.put("history", history); + + asha.put("incentive", incentive); + ashasArray.put(asha); + } + } + + facility.put("ashaCount", ashasArray.length()); + facility.put("ashas", ashasArray); + facilitiesArray.put(facility); + } + + result.put("facilities", facilitiesArray); + return result.toString(); + } + + private JSONObject buildEmptyIncentiveSummary() { + JSONObject summary = new JSONObject(); + summary.put("verified", 0); + summary.put("rejected", 0); + summary.put("pending", 0); + summary.put("totalAmount", 0); + return summary; + } + + private String str(Object val) { + return val != null ? val.toString() : ""; + } + + private String fullName(Object first, Object last) { + return (str(first) + " " + str(last)).trim(); + } +} \ No newline at end of file From 5711996c8b5080393c958e4ed3a7f2b1d819000b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 12:43:02 +0530 Subject: [PATCH 168/450] Add feature for asha supervisor for incentive approval --- .../AshaSupervisorIncentiveApproval.java | 16 ++-- .../dto/iemr/AshaByFacilityRequestDTO.java | 4 +- .../flw/repo/iemr/IncentiveRecordRepo.java | 9 +- .../repo/iemr/SupervisorDashboardRepo.java | 16 ++-- .../service/SupervisorDashboardService.java | 2 +- .../impl/AshaSupervisorLoginService.java | 17 +++- .../impl/SupervisorDashboardServiceImpl.java | 87 ++++--------------- 7 files changed, 66 insertions(+), 85 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index c3fc66f37..7f0eed948 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -35,11 +35,17 @@ public class AshaSupervisorIncentiveApproval { @PostMapping("/getAshaListByFacility") - public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityRequestDTO request) { + public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityRequestDTO request,@RequestHeader(value = "JwtToken") String token) { try { + if(token==null){ + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + + } List> result = ashaSupervisorLoginService.getAshasAtFacility( - request.getSuperVisorId(), - request.getFacilityId() + jwtUtil.extractUserId(token), + request.getFacilityId(), + request.getMonth(), + request.getYear() ); Map response = new HashMap<>(); @@ -61,12 +67,12 @@ public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityReques @Operation(summary = "Get comprehensive ASHA Supervisor dashboard with facilities, ASHAs, villages and incentive data") @PostMapping("/dashboard") - public String getSupervisorDashboard(@RequestHeader(value = "JwtToken") String token ) { + public String getSupervisorDashboard(@RequestBody AshaByFacilityRequestDTO request,@RequestHeader(value = "JwtToken") String token ) { OutputResponse response = new OutputResponse(); try { if(token!=null){ - String result = supervisorDashboardService.getSupervisorDashboard(jwtUtil.extractUserId(token)); + String result = supervisorDashboardService.getSupervisorDashboard(jwtUtil.extractUserId(token),request.getMonth(),request.getYear()); response.setResponse(result); } diff --git a/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java index 1a99f83be..74be288dc 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java @@ -4,7 +4,7 @@ @Data public class AshaByFacilityRequestDTO { - Integer userId; - Integer superVisorId; Integer facilityId; + private Integer month; + private Integer year; } 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 bedc77ffd..86ef31175 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -50,6 +50,11 @@ IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( "SUM(CASE WHEN record.approvalStatus = 102 THEN 1 ELSE 0 END), " + "SUM(CASE WHEN record.approvalStatus = 103 THEN 1 ELSE 0 END) " + "FROM IncentiveActivityRecord record " + - "WHERE record.ashaId = :ashaId") - List getStatusCountByAshaId(@Param("ashaId") Integer ashaId); + "WHERE record.ashaId = :ashaId " + + "AND record.createdDate >= :startDate " + + "AND record.createdDate < :endDate") + List getStatusCountByAshaId( + @Param("ashaId") Integer ashaId, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index ee5ce32f1..3a1c19f1b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -1,5 +1,6 @@ package com.iemr.flw.repo.iemr; +import java.sql.Timestamp; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; @@ -62,12 +63,17 @@ public interface SupervisorDashboardRepo extends JpaRepository getIncentiveStatusByAshaIds(@Param("ashaIds") List ashaIds); + + "WHERE iar.asha_id IN (:ashaIds) " + + "AND iar.created_date >= :startDate " + + "AND iar.created_date < :endDate " + + "GROUP BY iar.asha_id", + nativeQuery = true) + List getIncentiveStatusByAshaIds( + @Param("ashaIds") List ashaIds, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); // Incentive activity history per ASHA (recent records) @Query(value = "SELECT iar.asha_id, iar.name AS activityName, " diff --git a/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java index 2db8a724e..ae555d851 100644 --- a/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java +++ b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java @@ -2,5 +2,5 @@ public interface SupervisorDashboardService { - String getSupervisorDashboard(Integer supervisorUserID); + String getSupervisorDashboard(Integer supervisorUserID,Integer month,Integer year); } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index f7398da92..d9987b2b9 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -1,5 +1,7 @@ package com.iemr.flw.service.impl; +import java.sql.Timestamp; +import java.time.LocalDate; import java.util.*; import com.iemr.flw.domain.iemr.AshaSupervisorMapping; @@ -261,16 +263,27 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { */ - public List> getAshasAtFacility(Integer supervisorId, Integer facilityId) { + public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year) { List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId); List> ashaList = new ArrayList<>(); Map asha = new HashMap<>(); + logger.info("Month: {}", month); + logger.info("Year: {}", year); + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + logger.info("startLocalDate {}", startLocalDate); + logger.info("endLocalDate {}", endLocalDate); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); for (Object[] row : rows) { Integer ashaId = ((Number) row[0]).intValue(); - List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId); + List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId,startDate,endDate); asha.put("userId", row[0]); asha.put("fullName", fullName(row[1], row[2])); diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 752f4decd..c82c39577 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -1,5 +1,7 @@ package com.iemr.flw.service.impl; +import java.sql.Timestamp; +import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -26,7 +28,7 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic private SupervisorDashboardRepo dashboardRepo; @Override - public String getSupervisorDashboard(Integer supervisorUserID) { + public String getSupervisorDashboard(Integer supervisorUserID,Integer month,Integer year) { JSONObject result = new JSONObject(); // 1. Supervisor user details @@ -92,9 +94,21 @@ public String getSupervisorDashboard(Integer supervisorUserID) { // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) Map incentiveStatusMap = new HashMap<>(); - long overallVerified = 0, overallRejected = 0, overallPending = 0, overallTotalAmount = 0; + long overallVerified = 0, overallRejected = 0, overallPending = 0; try { - List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs); + logger.info("Month: {}", month); + logger.info("Year: {}", year); + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + logger.info("startLocalDate {}", startLocalDate); + logger.info("endLocalDate {}", endLocalDate); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs,startDate,endDate); if (statusRows != null) { for (Object[] sRow : statusRows) { Integer ashaId = (Integer) sRow[0]; @@ -102,20 +116,18 @@ public String getSupervisorDashboard(Integer supervisorUserID) { long verified = ((Number) sRow[2]).longValue(); long rejected = ((Number) sRow[3]).longValue(); long pending = ((Number) sRow[4]).longValue(); - long totalAmount = ((Number) sRow[5]).longValue(); JSONObject status = new JSONObject(); status.put("totalRecords", total); status.put("verified", verified); status.put("rejected", rejected); status.put("pending", pending); - status.put("totalAmount", totalAmount); + status.put("overDue", 0); incentiveStatusMap.put(ashaId, status); overallVerified += verified; overallRejected += rejected; overallPending += pending; - overallTotalAmount += totalAmount; } } } catch (Exception e) { @@ -127,36 +139,9 @@ public String getSupervisorDashboard(Integer supervisorUserID) { overallSummary.put("verified", overallVerified); overallSummary.put("rejected", overallRejected); overallSummary.put("pending", overallPending); - overallSummary.put("totalAmount", overallTotalAmount); + overallSummary.put("overDue", 0); result.put("incentiveSummary", overallSummary); - // 6. Get incentive history per ASHA - Map> historyMap = new HashMap<>(); - try { - List historyRows = dashboardRepo.getIncentiveHistoryByAshaIds(ashaIDs); - if (historyRows != null) { - for (Object[] hRow : historyRows) { - Integer ashaId = (Integer) hRow[0]; - JSONObject record = new JSONObject(); - record.put("activityName", str(hRow[1])); - record.put("amount", hRow[2]); - String status; - if (hRow[3] == null) { - status = "pending"; - } else if ((Boolean) hRow[3]) { - status = "verified"; - } else { - status = "rejected"; - } - record.put("status", status); - record.put("createdDate", hRow[4] != null ? hRow[4].toString() : JSONObject.NULL); - historyMap.computeIfAbsent(ashaId, k -> new ArrayList<>()).add(record); - } - } - } catch (Exception e) { - logger.error("Error fetching incentive history: " + e.getMessage(), e); - } - // 7. Build facilities array with nested ASHAs Map> ashasByFacility = new HashMap<>(); for (Object[] row : ashaRows) { @@ -182,14 +167,6 @@ public String getSupervisorDashboard(Integer supervisorUserID) { facility.put("facilityType", str(fDetails[6])); } - // Villages - JSONArray villages = new JSONArray(); - List vList = villageMap.get(facID); - if (vList != null) { - for (JSONObject v : vList) - villages.put(v); - } - facility.put("villages", villages); // ASHAs at this facility JSONArray ashasArray = new JSONArray(); @@ -204,37 +181,11 @@ public String getSupervisorDashboard(Integer supervisorUserID) { asha.put("mobile", str(row[7]).isEmpty() ? JSONObject.NULL : str(row[7])); asha.put("gender", str(row[8]).isEmpty() ? JSONObject.NULL : str(row[8])); - // Individual ASHA incentive status - JSONObject incentive = new JSONObject(); - JSONObject ashaStatus = incentiveStatusMap.get(ashaId); - if (ashaStatus != null) { - incentive.put("verified", ashaStatus.get("verified")); - incentive.put("rejected", ashaStatus.get("rejected")); - incentive.put("pending", ashaStatus.get("pending")); - incentive.put("totalAmount", ashaStatus.get("totalAmount")); - } else { - incentive.put("verified", 0); - incentive.put("rejected", 0); - incentive.put("pending", 0); - incentive.put("totalAmount", 0); - } - - // History with status per record - JSONArray history = new JSONArray(); - List hList = historyMap.get(ashaId); - if (hList != null) { - for (JSONObject h : hList) - history.put(h); - } - incentive.put("history", history); - - asha.put("incentive", incentive); ashasArray.put(asha); } } facility.put("ashaCount", ashasArray.length()); - facility.put("ashas", ashasArray); facilitiesArray.put(facility); } From 703e26247d56f8584eb8cc24faf0fe18334e3ee5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 14:24:54 +0530 Subject: [PATCH 169/450] Add feature for asha supervisor for incentive approval --- .../AshaSupervisorIncentiveApproval.java | 11 +++++++--- .../dto/iemr/AshaByFacilityRequestDTO.java | 3 ++- .../repo/iemr/AshaSupervisorLoginRepo.java | 11 +++++++--- .../flw/repo/iemr/IncentiveRecordRepo.java | 11 ++++++++++ .../impl/AshaSupervisorLoginService.java | 22 ++++++++++++++----- 5 files changed, 46 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 7f0eed948..2606fc86a 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -45,13 +45,18 @@ public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityReques jwtUtil.extractUserId(token), request.getFacilityId(), request.getMonth(), - request.getYear() + request.getYear(), + request.getApprovalStatus() ); + Map approvalStatus = new HashMap<>(); + approvalStatus.put("pending", 0); + approvalStatus.put("verified", 0); + approvalStatus.put("rejected", 0); Map response = new HashMap<>(); - response.put("data", result); response.put("statusCode", 200); - + response.put("approvalStatus", approvalStatus); + response.put("data", result); return ResponseEntity.status(HttpStatus.OK).body(response); } catch (Exception e) { diff --git a/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java index 74be288dc..9ae46ad4c 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AshaByFacilityRequestDTO.java @@ -4,7 +4,8 @@ @Data public class AshaByFacilityRequestDTO { - Integer facilityId; + private Integer facilityId; private Integer month; private Integer year; + private Integer approvalStatus; } diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java index 637281270..ded4cbd23 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -34,9 +34,14 @@ public interface AshaSupervisorLoginRepo extends CrudRepository getAshasAtFacility(@Param("supervisorUserID") Integer supervisorUserID, - @Param("facilityID") Integer facilityID); + + "AND asm.deleted = false " + + "AND (:approvalStatus = 0 OR iar.approval_status = :approvalStatus)", + nativeQuery = true) + List getAshasAtFacility( + @Param("supervisorUserID") Integer supervisorUserID, + @Param("facilityID") Integer facilityID, + @Param("approvalStatus") Integer approvalStatus); } \ No newline at end of file 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 86ef31175..71be3b532 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -57,4 +57,15 @@ List getStatusCountByAshaId( @Param("ashaId") Integer ashaId, @Param("startDate") Timestamp startDate, @Param("endDate") Timestamp endDate); + + + @Query("SELECT COALESCE(SUM(record.amount), 0) " + + "FROM IncentiveActivityRecord record " + + "WHERE record.ashaId = :ashaId " + + "AND record.startDate <= :toDate " + + "AND record.endDate >= :fromDate") + Long getTotalAmountByAsha( + @Param("ashaId") Integer ashaId, + @Param("fromDate") Timestamp fromDate, + @Param("toDate") Timestamp toDate); } diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index d9987b2b9..0b1cc20e7 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -263,9 +263,11 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { */ - public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year) { + public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatus) { + + List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId,approvalStatus); + List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); - List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId); List> ashaList = new ArrayList<>(); Map asha = new HashMap<>(); logger.info("Month: {}", month); @@ -280,22 +282,32 @@ public List> getAshasAtFacility(Integer supervisorId, Intege Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + for (Object[] row : superVisorRow) { + Integer facilityID = (Integer) row[3]; + asha.put("facilityId", facilityID); + asha.put("facilityName", str(row[4])); + asha.put("facilityType", str(row[5])); + } + + for (Object[] row : rows) { Integer ashaId = ((Number) row[0]).intValue(); List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId,startDate,endDate); + Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); asha.put("userId", row[0]); asha.put("fullName", fullName(row[1], row[2])); asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); + asha.put("totalAmount",totalAmount); if (countList != null && !countList.isEmpty()) { Object[] counts = countList.get(0); - asha.put("pendingCount", counts[0] != null ? counts[0] : 0); - asha.put("approvalCount", counts[1] != null ? counts[1] : 0); - asha.put("rejectCount", counts[2] != null ? counts[2] : 0); + asha.put("pending", counts[0] != null ? counts[0] : 0); + asha.put("verified", counts[1] != null ? counts[1] : 0); + asha.put("rejected", counts[2] != null ? counts[2] : 0); } else { asha.put("pendingCount", 0); asha.put("approvalCount", 0); From d4107ea9236e42a96f1d78846b44eb20e65ab8dc Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 14:45:41 +0530 Subject: [PATCH 170/450] Add feature for asha supervisor for incentive approval --- .../impl/SupervisorDashboardServiceImpl.java | 365 +++++++++--------- 1 file changed, 178 insertions(+), 187 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index c82c39577..8505649f6 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -22,191 +22,182 @@ @Service public class SupervisorDashboardServiceImpl implements SupervisorDashboardService { - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Autowired - private SupervisorDashboardRepo dashboardRepo; - - @Override - public String getSupervisorDashboard(Integer supervisorUserID,Integer month,Integer year) { - JSONObject result = new JSONObject(); - - // 1. Supervisor user details - List supervisorRows = dashboardRepo.getSupervisorUserDetails(supervisorUserID); - if (supervisorRows != null && !supervisorRows.isEmpty()) { - Object[] sRow = supervisorRows.get(0); - JSONObject supervisor = new JSONObject(); - supervisor.put("userId", sRow[0]); - supervisor.put("fullName", fullName(sRow[1], sRow[2])); - supervisor.put("employeeId", str(sRow[3]).isEmpty() ? JSONObject.NULL : str(sRow[3])); - supervisor.put("mobile", str(sRow[4]).isEmpty() ? JSONObject.NULL : str(sRow[4])); - supervisor.put("gender", str(sRow[5]).isEmpty() ? JSONObject.NULL : str(sRow[5])); - result.put("supervisor", supervisor); - } - - // 2. Get all ASHAs with facility info - List ashaRows = dashboardRepo.getAshasWithFacilityInfo(supervisorUserID); - if (ashaRows == null || ashaRows.isEmpty()) { - result.put("totalAshaCount", 0); - result.put("incentiveSummary", buildEmptyIncentiveSummary()); - result.put("facilities", new JSONArray()); - return result.toString(); - } - - // Collect distinct facility IDs and ASHA IDs - Set facilityIDSet = new HashSet<>(); - Set ashaIDSet = new HashSet<>(); - for (Object[] row : ashaRows) { - if (row[3] != null) - facilityIDSet.add((Integer) row[3]); - if (row[0] != null) - ashaIDSet.add((Integer) row[0]); - } - List facilityIDs = new ArrayList<>(facilityIDSet); - List ashaIDs = new ArrayList<>(ashaIDSet); - - result.put("totalAshaCount", ashaIDs.size()); - - // 3. Location from first facility - List facilityRows = dashboardRepo.getFacilityDetails(facilityIDs); - if (facilityRows != null && !facilityRows.isEmpty()) { - Object[] fRow = facilityRows.get(0); - JSONObject location = new JSONObject(); - location.put("state", str(fRow[2])); - location.put("district", str(fRow[3])); - location.put("blockOrUlb", str(fRow[4])); - location.put("locationType", str(fRow[5])); - result.put("location", location); - } - - // 4. Build village map (facilityID -> villages) - Map> villageMap = new HashMap<>(); - List villageRows = dashboardRepo.getVillagesForFacilities(facilityIDs); - if (villageRows != null) { - for (Object[] vRow : villageRows) { - Integer facID = (Integer) vRow[0]; - JSONObject village = new JSONObject(); - village.put("villageId", vRow[1]); - village.put("villageName", str(vRow[2])); - villageMap.computeIfAbsent(facID, k -> new ArrayList<>()).add(village); - } - } - - // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) - Map incentiveStatusMap = new HashMap<>(); - long overallVerified = 0, overallRejected = 0, overallPending = 0; - try { - logger.info("Month: {}", month); - logger.info("Year: {}", year); - - LocalDate startLocalDate = LocalDate.of(year, month, 1); - LocalDate endLocalDate = startLocalDate.plusMonths(1); - - logger.info("startLocalDate {}", startLocalDate); - logger.info("endLocalDate {}", endLocalDate); - - Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - - List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs,startDate,endDate); - if (statusRows != null) { - for (Object[] sRow : statusRows) { - Integer ashaId = (Integer) sRow[0]; - long total = ((Number) sRow[1]).longValue(); - long verified = ((Number) sRow[2]).longValue(); - long rejected = ((Number) sRow[3]).longValue(); - long pending = ((Number) sRow[4]).longValue(); - - JSONObject status = new JSONObject(); - status.put("totalRecords", total); - status.put("verified", verified); - status.put("rejected", rejected); - status.put("pending", pending); - status.put("overDue", 0); - incentiveStatusMap.put(ashaId, status); - - overallVerified += verified; - overallRejected += rejected; - overallPending += pending; - } - } - } catch (Exception e) { - logger.error("Error fetching incentive status: " + e.getMessage(), e); - } - - // Overall incentive summary across all ASHAs - JSONObject overallSummary = new JSONObject(); - overallSummary.put("verified", overallVerified); - overallSummary.put("rejected", overallRejected); - overallSummary.put("pending", overallPending); - overallSummary.put("overDue", 0); - result.put("incentiveSummary", overallSummary); - - // 7. Build facilities array with nested ASHAs - Map> ashasByFacility = new HashMap<>(); - for (Object[] row : ashaRows) { - Integer facID = (Integer) row[3]; - ashasByFacility.computeIfAbsent(facID, k -> new ArrayList<>()).add(row); - } - - Map facilityDetailsMap = new HashMap<>(); - if (facilityRows != null) { - for (Object[] fRow : facilityRows) { - facilityDetailsMap.put((Integer) fRow[0], fRow); - } - } - - JSONArray facilitiesArray = new JSONArray(); - for (Integer facID : facilityIDs) { - JSONObject facility = new JSONObject(); - facility.put("facilityId", facID); - - Object[] fDetails = facilityDetailsMap.get(facID); - if (fDetails != null) { - facility.put("facilityName", str(fDetails[1])); - facility.put("facilityType", str(fDetails[6])); - } - - - // ASHAs at this facility - JSONArray ashasArray = new JSONArray(); - List facAshaRows = ashasByFacility.get(facID); - if (facAshaRows != null) { - for (Object[] row : facAshaRows) { - Integer ashaId = (Integer) row[0]; - JSONObject asha = new JSONObject(); - asha.put("userId", ashaId); - asha.put("fullName", fullName(row[1], row[2])); - asha.put("employeeId", str(row[6]).isEmpty() ? JSONObject.NULL : str(row[6])); - asha.put("mobile", str(row[7]).isEmpty() ? JSONObject.NULL : str(row[7])); - asha.put("gender", str(row[8]).isEmpty() ? JSONObject.NULL : str(row[8])); - - ashasArray.put(asha); - } - } - - facility.put("ashaCount", ashasArray.length()); - facilitiesArray.put(facility); - } - - result.put("facilities", facilitiesArray); - return result.toString(); - } - - private JSONObject buildEmptyIncentiveSummary() { - JSONObject summary = new JSONObject(); - summary.put("verified", 0); - summary.put("rejected", 0); - summary.put("pending", 0); - summary.put("totalAmount", 0); - return summary; - } - - private String str(Object val) { - return val != null ? val.toString() : ""; - } - - private String fullName(Object first, Object last) { - return (str(first) + " " + str(last)).trim(); - } + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private SupervisorDashboardRepo dashboardRepo; + + @Override + public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { + JSONObject result = new JSONObject(); + + // 1. Supervisor user details + List supervisorRows = dashboardRepo.getSupervisorUserDetails(supervisorUserID); + if (supervisorRows != null && !supervisorRows.isEmpty()) { + Object[] sRow = supervisorRows.get(0); + JSONObject supervisor = new JSONObject(); + supervisor.put("userId", sRow[0]); + supervisor.put("fullName", fullName(sRow[1], sRow[2])); + supervisor.put("employeeId", str(sRow[3]).isEmpty() ? JSONObject.NULL : str(sRow[3])); + supervisor.put("mobile", str(sRow[4]).isEmpty() ? JSONObject.NULL : str(sRow[4])); + supervisor.put("gender", str(sRow[5]).isEmpty() ? JSONObject.NULL : str(sRow[5])); + result.put("supervisor", supervisor); + } + + // 2. Get all ASHAs with facility info + List ashaRows = dashboardRepo.getAshasWithFacilityInfo(supervisorUserID); + if (ashaRows == null || ashaRows.isEmpty()) { + result.put("totalAshaCount", 0); + result.put("incentiveSummary", buildEmptyIncentiveSummary()); + result.put("facilities", new JSONArray()); + return result.toString(); + } + + // Collect distinct facility IDs and ASHA IDs + Set facilityIDSet = new HashSet<>(); + Set ashaIDSet = new HashSet<>(); + for (Object[] row : ashaRows) { + if (row[3] != null) + facilityIDSet.add((Integer) row[3]); + if (row[0] != null) + ashaIDSet.add((Integer) row[0]); + } + List facilityIDs = new ArrayList<>(facilityIDSet); + List ashaIDs = new ArrayList<>(ashaIDSet); + + result.put("totalAshaCount", ashaIDs.size()); + + // 3. Location from first facility + List facilityRows = dashboardRepo.getFacilityDetails(facilityIDs); + if (facilityRows != null && !facilityRows.isEmpty()) { + Object[] fRow = facilityRows.get(0); + JSONObject location = new JSONObject(); + location.put("state", str(fRow[2])); + location.put("district", str(fRow[3])); + location.put("blockOrUlb", str(fRow[4])); + location.put("locationType", str(fRow[5])); + result.put("location", location); + } + + // 4. Build village map (facilityID -> villages) + Map> villageMap = new HashMap<>(); + List villageRows = dashboardRepo.getVillagesForFacilities(facilityIDs); + if (villageRows != null) { + for (Object[] vRow : villageRows) { + Integer facID = (Integer) vRow[0]; + JSONObject village = new JSONObject(); + village.put("villageId", vRow[1]); + village.put("villageName", str(vRow[2])); + villageMap.computeIfAbsent(facID, k -> new ArrayList<>()).add(village); + } + } + + // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) + long overallVerified = 0, overallRejected = 0, overallPending = 0; + try { + logger.info("Month: {}", month); + logger.info("Year: {}", year); + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + logger.info("startLocalDate {}", startLocalDate); + logger.info("endLocalDate {}", endLocalDate); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs, startDate, endDate); + if (statusRows != null) { + for (Object[] sRow : statusRows) { + Integer ashaId = (Integer) sRow[0]; + long total = ((Number) sRow[1]).longValue(); + long verified = ((Number) sRow[2]).longValue(); + long rejected = ((Number) sRow[3]).longValue(); + long pending = ((Number) sRow[4]).longValue(); + + overallVerified += verified; + overallRejected += rejected; + overallPending += pending; + } + } + } catch (Exception e) { + logger.error("Error fetching incentive status: " + e.getMessage(), e); + } + + // Overall incentive summary across all ASHAs + JSONObject overallSummary = new JSONObject(); + overallSummary.put("verified", overallVerified > 0 ? 1 : 0); + overallSummary.put("rejected", overallRejected > 0 ? 1 : 0); + overallSummary.put("pending", overallPending > 0 ? 1 : 0); + overallSummary.put("overDue", 0); + result.put("incentiveSummary", overallSummary); + + // 7. Build facilities array with nested ASHAs + Map> ashasByFacility = new HashMap<>(); + for (Object[] row : ashaRows) { + Integer facID = (Integer) row[3]; + ashasByFacility.computeIfAbsent(facID, k -> new ArrayList<>()).add(row); + } + + Map facilityDetailsMap = new HashMap<>(); + if (facilityRows != null) { + for (Object[] fRow : facilityRows) { + facilityDetailsMap.put((Integer) fRow[0], fRow); + } + } + + JSONArray facilitiesArray = new JSONArray(); + for (Integer facID : facilityIDs) { + JSONObject facility = new JSONObject(); + facility.put("facilityId", facID); + + Object[] fDetails = facilityDetailsMap.get(facID); + if (fDetails != null) { + facility.put("facilityName", str(fDetails[1])); + facility.put("facilityType", str(fDetails[6])); + } + + + // ASHAs at this facility + JSONArray ashasArray = new JSONArray(); + List facAshaRows = ashasByFacility.get(facID); + if (facAshaRows != null) { + for (Object[] row : facAshaRows) { + Integer ashaId = (Integer) row[0]; + JSONObject asha = new JSONObject(); + asha.put("userId", ashaId); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[6]).isEmpty() ? JSONObject.NULL : str(row[6])); + asha.put("mobile", str(row[7]).isEmpty() ? JSONObject.NULL : str(row[7])); + asha.put("gender", str(row[8]).isEmpty() ? JSONObject.NULL : str(row[8])); + + ashasArray.put(asha); + } + } + + facility.put("ashaCount", ashasArray.length()); + facilitiesArray.put(facility); + } + + result.put("facilities", facilitiesArray); + return result.toString(); + } + + private JSONObject buildEmptyIncentiveSummary() { + JSONObject summary = new JSONObject(); + summary.put("verified", 0); + summary.put("rejected", 0); + summary.put("pending", 0); + summary.put("totalAmount", 0); + return summary; + } + + private String str(Object val) { + return val != null ? val.toString() : ""; + } + + private String fullName(Object first, Object last) { + return (str(first) + " " + str(last)).trim(); + } } \ No newline at end of file From 11442b7bf58213a94024376396e9aba225c1404d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 14:52:21 +0530 Subject: [PATCH 171/450] Add feature for asha supervisor for incentive approval --- .../impl/AshaSupervisorLoginService.java | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index 0b1cc20e7..efcb99c9a 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -263,9 +263,9 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { */ - public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatus) { + public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatusID) { - List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId,approvalStatus); + List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId,approvalStatusID); List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); List> ashaList = new ArrayList<>(); @@ -290,6 +290,7 @@ public List> getAshasAtFacility(Integer supervisorId, Intege } + for (Object[] row : rows) { Integer ashaId = ((Number) row[0]).intValue(); @@ -303,17 +304,36 @@ public List> getAshasAtFacility(Integer supervisorId, Intege asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); asha.put("totalAmount",totalAmount); + long pending = 0; + long verified = 0; + long rejected = 0; + if (countList != null && !countList.isEmpty()) { Object[] counts = countList.get(0); - asha.put("pending", counts[0] != null ? counts[0] : 0); - asha.put("verified", counts[1] != null ? counts[1] : 0); - asha.put("rejected", counts[2] != null ? counts[2] : 0); - } else { - asha.put("pendingCount", 0); - asha.put("approvalCount", 0); - asha.put("rejectCount", 0); + + pending = counts[0] != null ? ((Number) counts[0]).longValue() : 0; + verified = counts[1] != null ? ((Number) counts[1]).longValue() : 0; + rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; } + asha.put("pending", pending); + asha.put("verified", verified); + asha.put("rejected", rejected); + int approvalStatus = 0; + + + if (rejected > 0) { + approvalStatus = 102; + } + else if (pending > 0) { + approvalStatus = 103; + } + else if (verified > 0) { + approvalStatus = 101; + } + + asha.put("approvalStatus", approvalStatus); + ashaList.add(asha); } From bd1271c2f997a50c520e3e902f639fd537603739 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Feb 2026 15:13:28 +0530 Subject: [PATCH 172/450] Add feature for asha supervisor for incentive approval --- .../AshaSupervisorIncentiveApproval.java | 34 ++++++++++++++++++- .../dto/iemr/UpdateApprovalRequestDTO.java | 11 ++++++ .../flw/repo/iemr/IncentiveRecordRepo.java | 17 +++++++++- .../impl/AshaSupervisorLoginService.java | 16 +++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 2606fc86a..f757e7c02 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -1,6 +1,7 @@ package com.iemr.flw.controller; import com.iemr.flw.dto.iemr.AshaByFacilityRequestDTO; +import com.iemr.flw.dto.iemr.UpdateApprovalRequestDTO; import com.iemr.flw.service.SupervisorDashboardService; import com.iemr.flw.service.impl.AshaSupervisorLoginService; import com.iemr.flw.utils.JwtUtil; @@ -32,6 +33,7 @@ public class AshaSupervisorIncentiveApproval { @Autowired private JwtUtil jwtUtil; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @PostMapping("/getAshaListByFacility") @@ -66,7 +68,6 @@ public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityReques } } - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @@ -88,4 +89,35 @@ public String getSupervisorDashboard(@RequestBody AshaByFacilityRequestDTO reque return response.toString(); } + @PostMapping("/updateApprovalStatus") + public ResponseEntity updateApprovalStatus( + @RequestBody UpdateApprovalRequestDTO request, + @RequestHeader(value = "JwtToken") String token) { + + try { + if (token == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + } + + int updatedRows = ashaSupervisorLoginService.updateApprovalStatus( + request.getAshaId(), + request.getMonth(), + request.getYear(), + request.getApprovalStatus() + ); + + Map response = new HashMap<>(); + response.put("statusCode", 200); + response.put("updatedRecords", updatedRows); + + return ResponseEntity.ok(response); + + } catch (Exception e) { + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Server error: " + e.getMessage()); + } + } + + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java new file mode 100644 index 000000000..d59493f58 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java @@ -0,0 +1,11 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class UpdateApprovalRequestDTO { + private Integer ashaId; + private Integer month; + private Integer year; + private Integer approvalStatus; +} 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 71be3b532..3060e0d0d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -3,9 +3,11 @@ import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.List; @@ -68,4 +70,17 @@ Long getTotalAmountByAsha( @Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); -} + + @Modifying + @Transactional + @Query(value = "UPDATE incentive_activity_record iar " + + "SET iar.approval_status = :approvalStatus " + + "WHERE iar.asha_id = :ashaId " + + "AND iar.created_date >= :startDate " + + "AND iar.created_date < :endDate", + nativeQuery = true) + int updateApprovalStatusByAshaAndDateRange( + @Param("ashaId") Integer ashaId, + @Param("approvalStatus") Integer approvalStatus, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate);} diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index efcb99c9a..f5d46da48 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service @@ -261,7 +262,22 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { * API 2: Get ASHAs at a specific facility for this supervisor with detailed * info. */ + @Transactional + public int updateApprovalStatus(Integer ashaId, Integer month, Integer year, Integer approvalStatus) { + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( + ashaId, + approvalStatus, + startDate, + endDate + ); + } public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatusID) { From af553780c453818ff069c1caf250f0950aa46f9b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 10:42:06 +0530 Subject: [PATCH 173/450] add IncentiveApprovalStatus enum class --- .../masterEnum/IncentiveApprovalStatus.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/main/java/com/iemr/flw/masterEnum/IncentiveApprovalStatus.java diff --git a/src/main/java/com/iemr/flw/masterEnum/IncentiveApprovalStatus.java b/src/main/java/com/iemr/flw/masterEnum/IncentiveApprovalStatus.java new file mode 100644 index 000000000..e40ecc980 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/IncentiveApprovalStatus.java @@ -0,0 +1,35 @@ +package com.iemr.flw.masterEnum; + +public enum IncentiveApprovalStatus { + + VERIFIED(101, "Verified"), + PENDING(102, "Pending"), + REJECTED(103, "Rejected"), + OVERDUE(104, "Overdue"); + + private final int code; + private final String label; + + IncentiveApprovalStatus(int code, String label) { + this.code = code; + this.label = label; + } + + public int getCode() { + return code; + } + + public String getLabel() { + return label; + } + + // 🔥 Reverse lookup (code → enum) + public static IncentiveApprovalStatus fromCode(int code) { + for (IncentiveApprovalStatus status : values()) { + if (status.code == code) { + return status; + } + } + throw new IllegalArgumentException("Invalid approval status code: " + code); + } +} \ No newline at end of file From d3078a08fb7cf44d895adb43a4ca08d04b9ad348 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 10:50:19 +0530 Subject: [PATCH 174/450] add IncentiveApprovalStatus enum class --- .../AshaSupervisorIncentiveApproval.java | 4 +++- .../dto/iemr/UpdateApprovalRequestDTO.java | 2 ++ .../impl/AshaSupervisorLoginService.java | 19 ++++++++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index f757e7c02..8320cc428 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -103,7 +103,9 @@ public ResponseEntity updateApprovalStatus( request.getAshaId(), request.getMonth(), request.getYear(), - request.getApprovalStatus() + request.getApprovalStatus(), + request.getIncentiveIds(), + request.getRemarks() ); Map response = new HashMap<>(); diff --git a/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java index d59493f58..01cfc5ccb 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java @@ -8,4 +8,6 @@ public class UpdateApprovalRequestDTO { private Integer month; private Integer year; private Integer approvalStatus; + private String incentiveIds; + private String remarks; } diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index f5d46da48..c6ada65e6 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -5,6 +5,7 @@ import java.util.*; import com.iemr.flw.domain.iemr.AshaSupervisorMapping; +import com.iemr.flw.masterEnum.IncentiveApprovalStatus; import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; import com.iemr.flw.repo.iemr.FacilityLoginRepo; import com.iemr.flw.repo.iemr.IncentiveRecordRepo; @@ -263,13 +264,29 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { * info. */ @Transactional - public int updateApprovalStatus(Integer ashaId, Integer month, Integer year, Integer approvalStatus) { + public int updateApprovalStatus(Integer ashaId, Integer month, Integer year, Integer approvalStatus,String incentiveIds,String remarks) { LocalDate startLocalDate = LocalDate.of(year, month, 1); LocalDate endLocalDate = startLocalDate.plusMonths(1); Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + if(approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())){ + String[] ids = incentiveIds.split(","); + + for (int i = 0; i < ids.length; i++) { + if(incentiveRecordRepo.findById(Long.parseLong(String.valueOf(i))).isPresent()){ + return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( + ashaId, + approvalStatus, + startDate, + endDate + ); + } + + } + } + return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( ashaId, From fa20336d12df903c7d57b7c7c7f9853ddcd74dc6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 13:59:54 +0530 Subject: [PATCH 175/450] add IncentiveApprovalStatus enum class --- .../AshaSupervisorIncentiveApproval.java | 3 +- .../com/iemr/flw/dto/iemr/PaymentItem.java | 20 +++++ .../com/iemr/flw/dto/iemr/PaymentRequest.java | 42 ++++++++++ .../com/iemr/flw/dto/iemr/VerifiedBy.java | 18 +++++ .../flw/repo/iemr/IncentiveRecordRepo.java | 23 +++++- .../impl/AshaSupervisorLoginService.java | 80 +++++++++++++------ .../impl/UtpreronaPaymentIntegrationImpl.java | 64 +++++++++++++++ 7 files changed, 225 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java create mode 100644 src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 8320cc428..703c25c37 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -105,7 +105,8 @@ public ResponseEntity updateApprovalStatus( request.getYear(), request.getApprovalStatus(), request.getIncentiveIds(), - request.getRemarks() + request.getRemarks(), + token ); Map response = new HashMap<>(); diff --git a/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java b/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java new file mode 100644 index 000000000..fef317805 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java @@ -0,0 +1,20 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class PaymentItem { + @JsonProperty("activity_code") + public String activityCode; + + @JsonProperty("count") + public String count; + + @JsonProperty("incentive_amount") + public String incentiveAmount; + + public PaymentItem(String activityCode, String count, String incentiveAmount) { + this.activityCode = activityCode; + this.count = count; + this.incentiveAmount = incentiveAmount; + } + } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java b/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java new file mode 100644 index 000000000..1bc706b99 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java @@ -0,0 +1,42 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class PaymentRequest { + @JsonProperty("submission_id") + public String submissionId; + + @JsonProperty("partner_code") + public String partnerCode; + + @JsonProperty("period") + public Period period; + + @JsonProperty("asha_id") + public String ashaId; + + @JsonProperty("generated_at") + public String generatedAt; + + @JsonProperty("verified_by") + public VerifiedBy verifiedBy; + + @JsonProperty("items") + public List items; + + public PaymentRequest() {} + + public PaymentRequest(String submissionId, String partnerCode, Period period, + String ashaId, String generatedAt, + VerifiedBy verifiedBy, List items) { + this.submissionId = submissionId; + this.partnerCode = partnerCode; + this.period = period; + this.ashaId = ashaId; + this.generatedAt = generatedAt; + this.verifiedBy = verifiedBy; + this.items = items; + } + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java b/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java new file mode 100644 index 000000000..1bd7ce545 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java @@ -0,0 +1,18 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class VerifiedBy { + @JsonProperty("employee_id") + public String employeeId; + + @JsonProperty("name") + public String name; + + public VerifiedBy() {} + + public VerifiedBy(String employeeId, String name) { + this.employeeId = employeeId; + this.name = name; + } + } 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 3060e0d0d..64f2a9f8b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -75,6 +75,8 @@ Long getTotalAmountByAsha( @Transactional @Query(value = "UPDATE incentive_activity_record iar " + "SET iar.approval_status = :approvalStatus " + + "SET iar.verifiedBy_userId = :ashaSupervisorUserId " + + "SET iar.verifiedBy_userName = :ashaSupervisorUserName " + "WHERE iar.asha_id = :ashaId " + "AND iar.created_date >= :startDate " + "AND iar.created_date < :endDate", @@ -83,4 +85,23 @@ int updateApprovalStatusByAshaAndDateRange( @Param("ashaId") Integer ashaId, @Param("approvalStatus") Integer approvalStatus, @Param("startDate") Timestamp startDate, - @Param("endDate") Timestamp endDate);} + @Param("endDate") Timestamp endDate, + @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, + @Param("ashaSupervisorUserName") String ashaSupervisorUserName); + + + @Modifying + @Query("UPDATE IncentiveRecord iar " + + "SET iar.approvalStatus = :status, " + + "iar.remarks = :remarks, " + + "iar.verifiedBy_userId = :ashaSupervisorUserId, " + + "iar.verifiedBy_userName = :ashaSupervisorUserName " + + "WHERE iar.id = :id") + int updateApprovalStatusById( + @Param("id") Long id, + @Param("status") Integer status, + @Param("remarks") String remarks, + @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, + @Param("ashaSupervisorUserName") String ashaSupervisorUserName + ); +} diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index c6ada65e6..dd0c3d852 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -10,6 +10,10 @@ import com.iemr.flw.repo.iemr.FacilityLoginRepo; import com.iemr.flw.repo.iemr.IncentiveRecordRepo; import com.iemr.flw.repo.iemr.IncentivesRepo; +import com.iemr.flw.utils.JwtUtil; +import io.jsonwebtoken.Jwe; +import jakarta.el.ELException; +import org.checkerframework.checker.units.qual.A; import org.json.JSONArray; import org.json.JSONObject; @@ -34,6 +38,9 @@ public class AshaSupervisorLoginService { @Autowired private IncentiveRecordRepo incentiveRecordRepo; + @Autowired + private JwtUtil jwtUtil; + /** * Common facilityData block for ALL users. * Returns empty structure if user has no facility mapping. @@ -264,36 +271,63 @@ public JSONObject getSupervisorAshas(Integer supervisorUserID) { * info. */ @Transactional - public int updateApprovalStatus(Integer ashaId, Integer month, Integer year, Integer approvalStatus,String incentiveIds,String remarks) { + public int updateApprovalStatus(Integer ashaId, + Integer month, + Integer year, + Integer approvalStatus, + String incentiveIds, + String remarks, + String token) { + try { - LocalDate startLocalDate = LocalDate.of(year, month, 1); - LocalDate endLocalDate = startLocalDate.plusMonths(1); + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); - Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - if(approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())){ - String[] ids = incentiveIds.split(","); - - for (int i = 0; i < ids.length; i++) { - if(incentiveRecordRepo.findById(Long.parseLong(String.valueOf(i))).isPresent()){ - return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( - ashaId, - approvalStatus, - startDate, - endDate - ); + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); + String ashaSupervisorUsername = jwtUtil.extractUsername(token); + + // 👉 If Rejected → Update only selected incentive IDs + if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode()) + && incentiveIds != null + && !incentiveIds.isEmpty()) { + + String[] ids = incentiveIds.split(","); + int totalUpdated = 0; + + for (String idStr : ids) { + Long id = Long.parseLong(idStr.trim()); + + if (incentiveRecordRepo.existsById(id)) { + totalUpdated += incentiveRecordRepo.updateApprovalStatusById( + id, + approvalStatus, + remarks, + ashaSupervisorUserId, + ashaSupervisorUsername + ); + } } + return totalUpdated; } - } + // 👉 Otherwise update full month data + return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( + ashaId, + approvalStatus, + startDate, + endDate, + ashaSupervisorUserId, + ashaSupervisorUsername + ); - return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( - ashaId, - approvalStatus, - startDate, - endDate - ); + } catch (Exception e) { + e.printStackTrace(); + return 0; // never return null in int method + } } public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatusID) { diff --git a/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java new file mode 100644 index 000000000..ef449d66e --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java @@ -0,0 +1,64 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.dto.iemr.PaymentRequest; +import io.swagger.v3.oas.models.responses.ApiResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +@Service +public class UtpreronaPaymentIntegrationImpl { + @Value("${ssdPortalUrl}") + private String API_URL ; + private static final int TIMEOUT_SECONDS = 30; + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + + public UtpreronaPaymentIntegrationImpl() { + this.httpClient = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(TIMEOUT_SECONDS)) + .build(); + this.objectMapper = new ObjectMapper(); + } + + public ApiResponse sendPaymentRequest(PaymentRequest paymentRequest) + throws IOException, InterruptedException { + + String jsonBody = objectMapper.writeValueAsString(paymentRequest); + System.out.println("📤 Sending Request:"); + System.out.println(objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(paymentRequest)); + + HttpRequest httpRequest = HttpRequest.newBuilder() + .uri(URI.create(API_URL)) + .timeout(Duration.ofSeconds(TIMEOUT_SECONDS)) + .header("Content-Type", "application/json") + .header("Accept", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) + .build(); + + HttpResponse httpResponse = httpClient.send( + httpRequest, + HttpResponse.BodyHandlers.ofString() + ); + + System.out.println("Response Status: " + httpResponse.statusCode()); + System.out.println("Response Body: " + httpResponse.body()); + + if (httpResponse.statusCode() == 200) { + return objectMapper.readValue(httpResponse.body(), ApiResponse.class); + } else { + throw new IOException("API Error - Status: " + httpResponse.statusCode() + + " | Body: " + httpResponse.body()); + } + } + +} From 57239bb5faaf06488e53838fe1d7ca3904923243 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 16:52:50 +0530 Subject: [PATCH 176/450] fix --- .../flw/domain/iemr/IncentiveActivityRecord.java | 14 ++++++++++++++ .../iemr/flw/repo/iemr/IncentiveRecordRepo.java | 16 ++++++++-------- .../flw/service/impl/IncentiveServiceImpl.java | 5 +++++ 3 files changed, 27 insertions(+), 8 deletions(-) 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 d2392b24f..011e761d7 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -3,6 +3,8 @@ import lombok.Data; import jakarta.persistence.*; + +import javax.management.MXBean; import java.sql.Timestamp; @Entity @@ -55,4 +57,16 @@ public class IncentiveActivityRecord { @Column(name = "approval_status") Integer approvalStatus; + + @Column(name = "verifiedBy_userId") + private Integer verifiedByUserId; + + @Column(name = "verifiedBy_userName") + private String verifiedByUserName; + + @Column(name = "remarks") + private String remarks; + + @Transient + private String activityDec; } 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 64f2a9f8b..c7f062df8 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -75,8 +75,8 @@ Long getTotalAmountByAsha( @Transactional @Query(value = "UPDATE incentive_activity_record iar " + "SET iar.approval_status = :approvalStatus " - + "SET iar.verifiedBy_userId = :ashaSupervisorUserId " - + "SET iar.verifiedBy_userName = :ashaSupervisorUserName " + + "SET iar.verifiedByUserId = :ashaSupervisorUserId " + + "SET iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.asha_id = :ashaId " + "AND iar.created_date >= :startDate " + "AND iar.created_date < :endDate", @@ -91,12 +91,12 @@ int updateApprovalStatusByAshaAndDateRange( @Modifying - @Query("UPDATE IncentiveRecord iar " + - "SET iar.approvalStatus = :status, " + - "iar.remarks = :remarks, " + - "iar.verifiedBy_userId = :ashaSupervisorUserId, " + - "iar.verifiedBy_userName = :ashaSupervisorUserName " + - "WHERE iar.id = :id") + @Query("UPDATE IncentiveActivityRecord iar " + + "SET iar.approvalStatus = :status, " + + "iar.remarks = :remarks, " + + "iar.verifiedByUserId = :ashaSupervisorUserId, " + + "iar.verifiedByUserName = :ashaSupervisorUserName " + + "WHERE iar.id = :id") int updateApprovalStatusById( @Param("id") Long id, @Param("status") Integer status, 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 bbf28e4dd..0b6cccb27 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -185,6 +185,11 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); String beneName = rmnchBeneficiaryDetails.getFirstName() + " " + rmnchBeneficiaryDetails.getLastName(); entry.setName(beneName); + if(incentivesRepo.findById(entry.getActivityId()).isPresent()){ + IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); + entry.setActivityDec(incentiveActivity.getDescription()); + + } } else { entry.setName(""); From b434d5880ce4d56f2515f59950a1aa85dce71d9b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 17:11:25 +0530 Subject: [PATCH 177/450] fix --- src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java b/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java index 1bc706b99..88218b26a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PaymentRequest.java @@ -40,3 +40,4 @@ public PaymentRequest(String submissionId, String partnerCode, Period period, this.items = items; } } + From 8a9591a0f35464a714b1a2c1540d41232e6860d7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 17:12:28 +0530 Subject: [PATCH 178/450] fix --- .../java/com/iemr/flw/dto/iemr/Period.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/Period.java diff --git a/src/main/java/com/iemr/flw/dto/iemr/Period.java b/src/main/java/com/iemr/flw/dto/iemr/Period.java new file mode 100644 index 000000000..401e849bc --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/Period.java @@ -0,0 +1,20 @@ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Period { + @JsonProperty("start") + public String start; + + @JsonProperty("end") + public String end; + + public Period() {} + + + public Period(String start, String end) { + this.start = start; + this.end = end; + } + } + From e3b8adf05ec140e3ec5addf4b0eb88941b3a6a12 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 17:17:19 +0530 Subject: [PATCH 179/450] fix --- .../flw/service/impl/UtpreronaPaymentIntegrationImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java index ef449d66e..ca884383c 100644 --- a/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java @@ -15,8 +15,8 @@ @Service public class UtpreronaPaymentIntegrationImpl { - @Value("${ssdPortalUrl}") - private String API_URL ; +// @Value("${ssdPortalUrl}") + private String API_URL = ""; private static final int TIMEOUT_SECONDS = 30; private final HttpClient httpClient; From 13341c571ee43817de003463ac0c3afc2b1e8020 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 17:25:07 +0530 Subject: [PATCH 180/450] add activityDec for supervisor --- .../com/iemr/flw/dto/iemr/IncentiveRecordDTO.java | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 9a07f65c4..a707f36a2 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -1,6 +1,7 @@ package com.iemr.flw.dto.iemr; import jakarta.persistence.Column; +import jakarta.persistence.Transient; import lombok.Data; import java.sql.Timestamp; @@ -35,5 +36,15 @@ public class IncentiveRecordDTO { private Boolean isEligible; private Boolean isDefaultActivity; + + private Integer approvalStatus; + + private Integer verifiedByUserId; + + private String verifiedByUserName; + + private String remarks; + + private String activityDec; } From 7034fe4d90f67488346a899dda184fc7a008526a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 17:30:07 +0530 Subject: [PATCH 181/450] add activityDec for supervisor --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 0b6cccb27..0c854bcbe 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -187,7 +187,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { entry.setName(beneName); if(incentivesRepo.findById(entry.getActivityId()).isPresent()){ IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); - entry.setActivityDec(incentiveActivity.getDescription()); + entry.setActivityDec(incentiveActivity.getGroup()+"-"+incentiveActivity.getDescription()); } From 932595f83e3012758a9e3c1d9fda70d33031a827 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 2 Mar 2026 18:01:33 +0530 Subject: [PATCH 182/450] add activityDec for supervisor --- .../java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java | 3 +++ src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java | 3 +++ .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 3 ++- 3 files changed, 8 insertions(+), 1 deletion(-) 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 011e761d7..26599aad3 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -69,4 +69,7 @@ public class IncentiveActivityRecord { @Transient private String activityDec; + + @Transient + private String groupName; } 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 a707f36a2..c58109130 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -46,5 +46,8 @@ public class IncentiveRecordDTO { private String remarks; private String activityDec; + + private String groupName; + } 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 0c854bcbe..cb6116a76 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -187,7 +187,8 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { entry.setName(beneName); if(incentivesRepo.findById(entry.getActivityId()).isPresent()){ IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); - entry.setActivityDec(incentiveActivity.getGroup()+"-"+incentiveActivity.getDescription()); + entry.setGroupName(incentiveActivity.getGroup()); + entry.setActivityDec(incentiveActivity.getDescription()); } From 4bd0a4ed0f70c601d3d6cfc2b5ed38ceedd8e6d4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 11:47:38 +0530 Subject: [PATCH 183/450] add reason in reject incentive --- .../AshaSupervisorIncentiveApproval.java | 4 ++-- .../iemr/flw/domain/iemr/IncentiveActivity.java | 1 - .../domain/iemr/IncentiveActivityRecord.java | 7 +++++-- .../iemr/flw/dto/iemr/IncentiveRecordDTO.java | 6 ++++-- .../flw/dto/iemr/UpdateApprovalRequestDTO.java | 3 ++- .../iemr/flw/repo/iemr/IncentiveRecordRepo.java | 17 ++++++++++------- .../impl/AshaSupervisorLoginService.java | 8 +++++--- 7 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 703c25c37..a514dc23d 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -7,7 +7,6 @@ import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; -import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -105,7 +104,8 @@ public ResponseEntity updateApprovalStatus( request.getYear(), request.getApprovalStatus(), request.getIncentiveIds(), - request.getRemarks(), + request.getReason(), + request.getOtherReason(), token ); 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 b5c039f55..ccfe11069 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java @@ -36,7 +36,6 @@ public class IncentiveActivity { @Column(name = "group_name") private String group; - @Column(name = "fmr_code") private String fmrCode; 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 26599aad3..4a61e0d5a 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -64,8 +64,11 @@ public class IncentiveActivityRecord { @Column(name = "verifiedBy_userName") private String verifiedByUserName; - @Column(name = "remarks") - private String remarks; + @Column(name = "reason") + private String reason; + + @Column(name = "other_reason") + private String otherReason; @Transient private String activityDec; 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 c58109130..763fc6353 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -43,11 +43,13 @@ public class IncentiveRecordDTO { private String verifiedByUserName; - private String remarks; - private String activityDec; private String groupName; + private String reason; + + private String otherReason; + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java index 01cfc5ccb..ff7867301 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/UpdateApprovalRequestDTO.java @@ -9,5 +9,6 @@ public class UpdateApprovalRequestDTO { private Integer year; private Integer approvalStatus; private String incentiveIds; - private String remarks; + private String reason; + private String otherReason; } 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 c7f062df8..5a9c454bf 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -74,10 +74,10 @@ Long getTotalAmountByAsha( @Modifying @Transactional @Query(value = "UPDATE incentive_activity_record iar " - + "SET iar.approval_status = :approvalStatus " - + "SET iar.verifiedByUserId = :ashaSupervisorUserId " - + "SET iar.verifiedByUserName = :ashaSupervisorUserName " - + "WHERE iar.asha_id = :ashaId " + + "SET iar.approval_status = :approvalStatus, " + + "SET iar.verifiedByUserId = :ashaSupervisorUserId, " + + "SET iar.verifiedByUserName = :ashaSupervisorUserName, " + + "WHERE iar.asha_id = :ashaId, " + "AND iar.created_date >= :startDate " + "AND iar.created_date < :endDate", nativeQuery = true) @@ -93,15 +93,18 @@ int updateApprovalStatusByAshaAndDateRange( @Modifying @Query("UPDATE IncentiveActivityRecord iar " + "SET iar.approvalStatus = :status, " - + "iar.remarks = :remarks, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + + "iar.reason = :reason, " + + "iar.otherReason = :otherReason, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.id = :id") int updateApprovalStatusById( @Param("id") Long id, @Param("status") Integer status, - @Param("remarks") String remarks, @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, - @Param("ashaSupervisorUserName") String ashaSupervisorUserName + @Param("ashaSupervisorUserName") String ashaSupervisorUserName, + @Param("reason") String reason, + @Param("otherReason") String otherReason + ); } diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index dd0c3d852..aee6222d7 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -276,7 +276,8 @@ public int updateApprovalStatus(Integer ashaId, Integer year, Integer approvalStatus, String incentiveIds, - String remarks, + String reason, + String otherReason, String token) { try { @@ -304,9 +305,10 @@ public int updateApprovalStatus(Integer ashaId, totalUpdated += incentiveRecordRepo.updateApprovalStatusById( id, approvalStatus, - remarks, ashaSupervisorUserId, - ashaSupervisorUsername + ashaSupervisorUsername, + reason, + otherReason ); } } From 01442746d790cdfa9abcb8d19e67dd2fb9c941ab Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 15:26:13 +0530 Subject: [PATCH 184/450] add reason in reject incentive --- .../com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 4 ++-- .../flw/service/impl/SupervisorDashboardServiceImpl.java | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index 3a1c19f1b..d86e8d7c1 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -62,8 +62,8 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 8505649f6..16bf668b5 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -106,16 +106,17 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + logger.info("Asha ID"+ashaIDs); List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs, startDate, endDate); if (statusRows != null) { for (Object[] sRow : statusRows) { - Integer ashaId = (Integer) sRow[0]; - long total = ((Number) sRow[1]).longValue(); long verified = ((Number) sRow[2]).longValue(); long rejected = ((Number) sRow[3]).longValue(); long pending = ((Number) sRow[4]).longValue(); - + logger.info("verified"+verified); + logger.info("rejected"+rejected); + logger.info("pending"+pending); overallVerified += verified; overallRejected += rejected; overallPending += pending; From 30d6dea2060038314a7a030766a378134ba4d992 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 16:24:27 +0530 Subject: [PATCH 185/450] add reason in reject incentive --- .../com/iemr/flw/service/impl/AshaSupervisorLoginService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index aee6222d7..6b7c62a01 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -392,10 +392,10 @@ public List> getAshasAtFacility(Integer supervisorId, Intege if (rejected > 0) { - approvalStatus = 102; + approvalStatus = 103; } else if (pending > 0) { - approvalStatus = 103; + approvalStatus = 102; } else if (verified > 0) { approvalStatus = 101; From d52ab132428c15c24fca5acdf986d78245f224e4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 16:30:44 +0530 Subject: [PATCH 186/450] add reason in reject incentive --- .../java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 5a9c454bf..e1650088a 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -75,9 +75,9 @@ Long getTotalAmountByAsha( @Transactional @Query(value = "UPDATE incentive_activity_record iar " + "SET iar.approval_status = :approvalStatus, " - + "SET iar.verifiedByUserId = :ashaSupervisorUserId, " - + "SET iar.verifiedByUserName = :ashaSupervisorUserName, " - + "WHERE iar.asha_id = :ashaId, " + + "iar.verifiedByUserId = :ashaSupervisorUserId, " + + "iar.verifiedByUserName = :ashaSupervisorUserName " + + "WHERE iar.asha_id = :ashaId " + "AND iar.created_date >= :startDate " + "AND iar.created_date < :endDate", nativeQuery = true) From 47a8b9c05e52e29d44051782aea729537338324a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 16:35:40 +0530 Subject: [PATCH 187/450] add reason in reject incentive --- .../com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 e1650088a..cf9f12286 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -73,13 +73,13 @@ Long getTotalAmountByAsha( @Modifying @Transactional - @Query(value = "UPDATE incentive_activity_record iar " - + "SET iar.approval_status = :approvalStatus, " + @Query(value = "UPDATE IncentiveActivityRecord iar " + + "SET iar.approvalStatus = :approvalStatus, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.verifiedByUserName = :ashaSupervisorUserName " - + "WHERE iar.asha_id = :ashaId " - + "AND iar.created_date >= :startDate " - + "AND iar.created_date < :endDate", + + "WHERE iar.ashaId = :ashaId " + + "AND iar.createdDate >= :startDate " + + "AND iar.createdDate < :endDate", nativeQuery = true) int updateApprovalStatusByAshaAndDateRange( @Param("ashaId") Integer ashaId, From 9c52edece0b37d4e2822be867c2c5e37c94b238b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 16:38:55 +0530 Subject: [PATCH 188/450] add reason in reject incentive --- .../java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 cf9f12286..19aa78770 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -73,14 +73,13 @@ Long getTotalAmountByAsha( @Modifying @Transactional - @Query(value = "UPDATE IncentiveActivityRecord iar " + @Query("UPDATE IncentiveActivityRecord iar " + "SET iar.approvalStatus = :approvalStatus, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.ashaId = :ashaId " + "AND iar.createdDate >= :startDate " - + "AND iar.createdDate < :endDate", - nativeQuery = true) + + "AND iar.createdDate < :endDate") int updateApprovalStatusByAshaAndDateRange( @Param("ashaId") Integer ashaId, @Param("approvalStatus") Integer approvalStatus, From dc515b0861ae8724a6634848b17ce6ca9d5d463e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 17:20:17 +0530 Subject: [PATCH 189/450] add reason in reject incentive --- .../com/iemr/flw/service/impl/AshaSupervisorLoginService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java index 6b7c62a01..122c7fd1e 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java @@ -380,8 +380,8 @@ public List> getAshasAtFacility(Integer supervisorId, Intege if (countList != null && !countList.isEmpty()) { Object[] counts = countList.get(0); - pending = counts[0] != null ? ((Number) counts[0]).longValue() : 0; - verified = counts[1] != null ? ((Number) counts[1]).longValue() : 0; + verified = counts[0] != null ? ((Number) counts[0]).longValue() : 0; + pending = counts[1] != null ? ((Number) counts[1]).longValue() : 0; rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; } From 5c4fd9c386dc16e48a6dee7f3ee36bc0381a54de Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 17:50:55 +0530 Subject: [PATCH 190/450] add reason in reject incentive --- .../AshaSupervisorIncentiveApproval.java | 33 +- .../service/SupervisorDashboardService.java | 18 +- .../impl/AshaSupervisorLoginService.java | 417 ------------------ .../impl/SupervisorDashboardServiceImpl.java | 176 ++++++++ 4 files changed, 207 insertions(+), 437 deletions(-) delete mode 100644 src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index a514dc23d..3f840f614 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -3,7 +3,6 @@ import com.iemr.flw.dto.iemr.AshaByFacilityRequestDTO; import com.iemr.flw.dto.iemr.UpdateApprovalRequestDTO; import com.iemr.flw.service.SupervisorDashboardService; -import com.iemr.flw.service.impl.AshaSupervisorLoginService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; @@ -23,9 +22,6 @@ @RequestMapping("/ashaSupervisor") public class AshaSupervisorIncentiveApproval { - @Autowired - private AshaSupervisorLoginService ashaSupervisorLoginService; - @Autowired private SupervisorDashboardService supervisorDashboardService; @@ -36,31 +32,32 @@ public class AshaSupervisorIncentiveApproval { @PostMapping("/getAshaListByFacility") - public ResponseEntity getAshaListByFacility(@RequestBody AshaByFacilityRequestDTO request,@RequestHeader(value = "JwtToken") String token) { + public ResponseEntity getAshaListByFacility( + @RequestBody AshaByFacilityRequestDTO request, + @RequestHeader(value = "JwtToken") String token) { + try { - if(token==null){ - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + if (token == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); } - List> result = ashaSupervisorLoginService.getAshasAtFacility( + + Map result = supervisorDashboardService.getAshasAtFacility( jwtUtil.extractUserId(token), request.getFacilityId(), request.getMonth(), request.getYear(), request.getApprovalStatus() ); - Map approvalStatus = new HashMap<>(); - approvalStatus.put("pending", 0); - approvalStatus.put("verified", 0); - approvalStatus.put("rejected", 0); - Map response = new HashMap<>(); - response.put("statusCode", 200); - response.put("approvalStatus", approvalStatus); - response.put("data", result); - return ResponseEntity.status(HttpStatus.OK).body(response); + logger.info("result {}", result); + + return ResponseEntity.status(HttpStatus.OK).body(result); } catch (Exception e) { + + logger.error("Error in getAshaListByFacility", e); + return ResponseEntity .status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Server error: " + e.getMessage()); @@ -98,7 +95,7 @@ public ResponseEntity updateApprovalStatus( return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); } - int updatedRows = ashaSupervisorLoginService.updateApprovalStatus( + int updatedRows = supervisorDashboardService.updateApprovalStatus( request.getAshaId(), request.getMonth(), request.getYear(), diff --git a/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java index ae555d851..bc580a26d 100644 --- a/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java +++ b/src/main/java/com/iemr/flw/service/SupervisorDashboardService.java @@ -1,6 +1,20 @@ package com.iemr.flw.service; +import java.util.List; +import java.util.Map; + public interface SupervisorDashboardService { - String getSupervisorDashboard(Integer supervisorUserID,Integer month,Integer year); -} \ No newline at end of file + String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year); + + Map getAshasAtFacility(Integer supervisorId, Integer facilityId, Integer month, Integer year, Integer approvalStatusID); + + public int updateApprovalStatus(Integer ashaId, + Integer month, + Integer year, + Integer approvalStatus, + String incentiveIds, + String reason, + String otherReason, + String token); +} diff --git a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java b/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java deleted file mode 100644 index 122c7fd1e..000000000 --- a/src/main/java/com/iemr/flw/service/impl/AshaSupervisorLoginService.java +++ /dev/null @@ -1,417 +0,0 @@ -package com.iemr.flw.service.impl; - -import java.sql.Timestamp; -import java.time.LocalDate; -import java.util.*; - -import com.iemr.flw.domain.iemr.AshaSupervisorMapping; -import com.iemr.flw.masterEnum.IncentiveApprovalStatus; -import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; -import com.iemr.flw.repo.iemr.FacilityLoginRepo; -import com.iemr.flw.repo.iemr.IncentiveRecordRepo; -import com.iemr.flw.repo.iemr.IncentivesRepo; -import com.iemr.flw.utils.JwtUtil; -import io.jsonwebtoken.Jwe; -import jakarta.el.ELException; -import org.checkerframework.checker.units.qual.A; -import org.json.JSONArray; -import org.json.JSONObject; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - - -@Service -public class AshaSupervisorLoginService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); - - @Autowired - private AshaSupervisorLoginRepo ashaSupervisorLoginRepo; - - @Autowired - private FacilityLoginRepo facilityLoginRepo; - - @Autowired - private IncentiveRecordRepo incentiveRecordRepo; - - @Autowired - private JwtUtil jwtUtil; - - /** - * Common facilityData block for ALL users. - * Returns empty structure if user has no facility mapping. - */ - public JSONObject buildFacilityLoginData(Long userID, String roleName) { - JSONObject result = new JSONObject(); - result.put("location", buildEmptyLocation()); - try { - if ("ASHA Supervisor".equalsIgnoreCase(roleName)) { - enrichAshaSupervisorData(result, userID.intValue()); - } else if ("ASHA".equalsIgnoreCase(roleName)) { - enrichAshaData(result, userID.intValue()); - } else { - enrichGeneralFacilityData(result, userID.intValue()); - } - } catch (Exception e) { - logger.error("Error building facility login data for userID " + userID + ": " + e.getMessage(), e); - } - return result; - } - - private JSONObject buildEmptyLocation() { - return new JSONObject() - .put("state", "") - .put("district", "") - .put("blockOrUlb", "") - .put("locationType", ""); - } - - // ==================== ASHA ==================== - - private void enrichAshaData(JSONObject result, Integer ashaUserID) { - List facilityIDs = facilityLoginRepo.getUserFacilityIDs(ashaUserID); - if (facilityIDs == null || facilityIDs.isEmpty()) - return; - - List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); - if (facilityRows == null || facilityRows.isEmpty()) - return; - - populateLocation(result, facilityRows.get(0)); - - // ASHA gets a single facility (first mapped) - Object[] row = facilityRows.get(0); - JSONObject facility = new JSONObject(); - facility.put("facilityId", row[0]); - facility.put("facilityName", str(row[1])); - facility.put("facilityType", str(row[9])); - result.put("facility", facility); - - // Supervisor details - List supervisorRows = facilityLoginRepo.getSupervisorForAsha(ashaUserID); - if (supervisorRows != null && !supervisorRows.isEmpty()) { - Object[] sRow = supervisorRows.get(0); - JSONObject supervisor = new JSONObject(); - supervisor.put("userId", sRow[0]); - supervisor.put("fullName", fullName(sRow[1], sRow[2])); - supervisor.put("mobile", str(sRow[3])); - result.put("supervisor", supervisor); - } else { - result.put("supervisor", JSONObject.NULL); - } - - // Peers at same facility - List peerRows = facilityLoginRepo.getPeersAtFacility(facilityIDs, ashaUserID); - JSONArray peers = new JSONArray(); - if (peerRows != null) { - for (Object[] pRow : peerRows) { - JSONObject peer = new JSONObject(); - peer.put("userId", pRow[0]); - peer.put("fullName", fullName(pRow[1], pRow[2])); - peer.put("role", str(pRow[3])); - peers.put(peer); - } - } - result.put("peersAtFacility", peers); - } - - // ==================== ASHA Supervisor ==================== - - private void enrichAshaSupervisorData(JSONObject result, Integer supervisorUserID) { - ArrayList mappings = ashaSupervisorLoginRepo - .findBySupervisorUserIDAndDeletedFalse(supervisorUserID); - if (mappings == null || mappings.isEmpty()) - return; - - Set facilityIDSet = new HashSet<>(); - for (AshaSupervisorMapping m : mappings) { - if (m.getFacilityID() != null) - facilityIDSet.add(m.getFacilityID()); - } - if (facilityIDSet.isEmpty()) - return; - List facilityIDs = new ArrayList<>(facilityIDSet); - - List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); - if (facilityRows == null || facilityRows.isEmpty()) - return; - - populateLocation(result, facilityRows.get(0)); - - JSONArray facilitiesArray = new JSONArray(); - for (Object[] row : facilityRows) { - JSONObject facility = new JSONObject(); - facility.put("facilityId", row[0]); - facility.put("facilityName", str(row[1])); - facility.put("facilityType", str(row[9])); - facilitiesArray.put(facility); - } - result.put("facilities", facilitiesArray); - - // Count distinct ASHAs mapped to this supervisor - Set ashaUserIDs = new HashSet<>(); - for (AshaSupervisorMapping m : mappings) { - if (m.getAshaUserID() != null) - ashaUserIDs.add(m.getAshaUserID()); - } - result.put("totalAshaCount", ashaUserIDs.size()); - } - - // ==================== General Facility User (CHO, ANM, etc.) - // ==================== - - private void enrichGeneralFacilityData(JSONObject result, Integer userID) { - List facilityIDs = facilityLoginRepo.getUserFacilityIDs(userID); - if (facilityIDs == null || facilityIDs.isEmpty()) - return; - - List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); - if (facilityRows == null || facilityRows.isEmpty()) - return; - - populateLocation(result, facilityRows.get(0)); - - JSONArray facilitiesArray = new JSONArray(); - for (Object[] row : facilityRows) { - JSONObject facility = new JSONObject(); - facility.put("facilityId", row[0]); - facility.put("facilityName", str(row[1])); - facility.put("facilityType", str(row[9])); - facilitiesArray.put(facility); - } - result.put("facilities", facilitiesArray); - } - - // ==================== Shared Helpers ==================== - - private void populateLocation(JSONObject result, Object[] facilityRow) { - JSONObject location = new JSONObject(); - location.put("state", str(facilityRow[3])); - location.put("district", str(facilityRow[5])); - location.put("blockOrUlb", str(facilityRow[7])); - location.put("locationType", str(facilityRow[8])); - result.put("location", location); - } - - private String str(Object val) { - return val != null ? val.toString() : ""; - } - - private String fullName(Object first, Object last) { - return (str(first) + " " + str(last)).trim(); - } - - /** - * API 1: Get all ASHAs mapped to this supervisor with facility info. - */ - public JSONObject getSupervisorAshas(Integer supervisorUserID) { - JSONObject result = new JSONObject(); - JSONArray ashas = new JSONArray(); - - List rows = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorUserID); - if (rows == null || rows.isEmpty()) { - result.put("totalAshaCount", 0); - result.put("ashas", ashas); - return result; - } - - // Collect distinct facility IDs and build village map - Set facilityIDSet = new HashSet<>(); - for (Object[] row : rows) { - if (row[3] != null) - facilityIDSet.add((Integer) row[3]); - } - - Map> villageMap = new HashMap<>(); - if (!facilityIDSet.isEmpty()) { - List villageRows = facilityLoginRepo - .getVillagesForFacilities(new ArrayList<>(facilityIDSet)); - if (villageRows != null) { - for (Object[] vRow : villageRows) { - Integer facID = (Integer) vRow[0]; - JSONObject village = new JSONObject(); - village.put("villageId", vRow[1]); - village.put("villageName", str(vRow[2])); - villageMap.computeIfAbsent(facID, k -> new ArrayList<>()).add(village); - } - } - } - - for (Object[] row : rows) { - Integer facilityID = (Integer) row[3]; - JSONObject asha = new JSONObject(); - asha.put("userId", row[0]); - asha.put("fullName", fullName(row[1], row[2])); - asha.put("facilityId", facilityID); - asha.put("facilityName", str(row[4])); - asha.put("facilityType", str(row[5])); - - JSONArray villages = new JSONArray(); - List vList = villageMap.get(facilityID); - if (vList != null) { - for (JSONObject v : vList) - villages.put(v); - } - asha.put("villages", villages); - - ashas.put(asha); - } - - result.put("totalAshaCount", ashas.length()); - result.put("ashas", ashas); - return result; - } - - /** - * API 2: Get ASHAs at a specific facility for this supervisor with detailed - * info. - */ - @Transactional - public int updateApprovalStatus(Integer ashaId, - Integer month, - Integer year, - Integer approvalStatus, - String incentiveIds, - String reason, - String otherReason, - String token) { - try { - - LocalDate startLocalDate = LocalDate.of(year, month, 1); - LocalDate endLocalDate = startLocalDate.plusMonths(1); - - Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - - Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); - String ashaSupervisorUsername = jwtUtil.extractUsername(token); - - // 👉 If Rejected → Update only selected incentive IDs - if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode()) - && incentiveIds != null - && !incentiveIds.isEmpty()) { - - String[] ids = incentiveIds.split(","); - int totalUpdated = 0; - - for (String idStr : ids) { - Long id = Long.parseLong(idStr.trim()); - - if (incentiveRecordRepo.existsById(id)) { - totalUpdated += incentiveRecordRepo.updateApprovalStatusById( - id, - approvalStatus, - ashaSupervisorUserId, - ashaSupervisorUsername, - reason, - otherReason - ); - } - } - - return totalUpdated; - } - - // 👉 Otherwise update full month data - return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( - ashaId, - approvalStatus, - startDate, - endDate, - ashaSupervisorUserId, - ashaSupervisorUsername - ); - - } catch (Exception e) { - e.printStackTrace(); - return 0; // never return null in int method - } - } - - public List> getAshasAtFacility(Integer supervisorId, Integer facilityId,Integer month,Integer year,Integer approvalStatusID) { - - List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId,approvalStatusID); - List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); - - List> ashaList = new ArrayList<>(); - Map asha = new HashMap<>(); - logger.info("Month: {}", month); - logger.info("Year: {}", year); - - LocalDate startLocalDate = LocalDate.of(year, month, 1); - LocalDate endLocalDate = startLocalDate.plusMonths(1); - - logger.info("startLocalDate {}", startLocalDate); - logger.info("endLocalDate {}", endLocalDate); - - Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - - for (Object[] row : superVisorRow) { - Integer facilityID = (Integer) row[3]; - asha.put("facilityId", facilityID); - asha.put("facilityName", str(row[4])); - asha.put("facilityType", str(row[5])); - } - - - - for (Object[] row : rows) { - - Integer ashaId = ((Number) row[0]).intValue(); - List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId,startDate,endDate); - Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); - - asha.put("userId", row[0]); - asha.put("fullName", fullName(row[1], row[2])); - asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); - asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); - asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); - asha.put("totalAmount",totalAmount); - - long pending = 0; - long verified = 0; - long rejected = 0; - - if (countList != null && !countList.isEmpty()) { - Object[] counts = countList.get(0); - - verified = counts[0] != null ? ((Number) counts[0]).longValue() : 0; - pending = counts[1] != null ? ((Number) counts[1]).longValue() : 0; - rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; - } - - asha.put("pending", pending); - asha.put("verified", verified); - asha.put("rejected", rejected); - int approvalStatus = 0; - - - if (rejected > 0) { - approvalStatus = 103; - } - else if (pending > 0) { - approvalStatus = 102; - } - else if (verified > 0) { - approvalStatus = 101; - } - - asha.put("approvalStatus", approvalStatus); - - ashaList.add(asha); - } - - return ashaList; - } - - public String getGenderName(Integer genderID) { - if (genderID == null) - return null; - return facilityLoginRepo.getGenderName(genderID); - } -} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 16bf668b5..a9e406d04 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -9,6 +9,11 @@ import java.util.Map; import java.util.Set; +import com.iemr.flw.masterEnum.IncentiveApprovalStatus; +import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; +import com.iemr.flw.repo.iemr.FacilityLoginRepo; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.utils.JwtUtil; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; @@ -18,6 +23,7 @@ import com.iemr.flw.repo.iemr.SupervisorDashboardRepo; import com.iemr.flw.service.SupervisorDashboardService; +import org.springframework.transaction.annotation.Transactional; @Service public class SupervisorDashboardServiceImpl implements SupervisorDashboardService { @@ -27,6 +33,18 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic @Autowired private SupervisorDashboardRepo dashboardRepo; + @Autowired + private AshaSupervisorLoginRepo ashaSupervisorLoginRepo; + + @Autowired + private FacilityLoginRepo facilityLoginRepo; + + @Autowired + private IncentiveRecordRepo incentiveRecordRepo; + + @Autowired + private JwtUtil jwtUtil; + @Override public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { JSONObject result = new JSONObject(); @@ -185,6 +203,164 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In return result.toString(); } + @Override + public Map getAshasAtFacility(Integer supervisorId, Integer facilityId, + Integer month, Integer year, Integer approvalStatusID) { + + List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); + List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); + + List> ashaList = new ArrayList<>(); + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + long overallVerified = 0, overallRejected = 0, overallPending = 0; + + String facilityName = ""; + String facilityType = ""; + Integer facilityID = null; + + for (Object[] row : superVisorRow) { + facilityID = (Integer) row[3]; + facilityName = str(row[4]); + facilityType = str(row[5]); + } + + for (Object[] row : rows) { + + Map asha = new HashMap<>(); // ✅ loop ke andar + + Integer ashaId = ((Number) row[0]).intValue(); + + List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); + Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); + + asha.put("facilityId", facilityID); + asha.put("facilityName", facilityName); + asha.put("facilityType", facilityType); + + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); + asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); + asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); + asha.put("totalAmount", totalAmount); + + long pending = 0; + long verified = 0; + long rejected = 0; + + if (countList != null && !countList.isEmpty()) { + + Object[] counts = countList.get(0); + + verified = counts[0] != null ? ((Number) counts[0]).longValue() : 0; + pending = counts[1] != null ? ((Number) counts[1]).longValue() : 0; + rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; + } + + overallRejected += rejected; + overallPending += pending; + overallVerified += verified; + + asha.put("pending", pending); + asha.put("verified", verified); + asha.put("rejected", rejected); + + int approvalStatus = 0; + + if (rejected > 0) { + approvalStatus = 103; + } else if (pending > 0) { + approvalStatus = 102; + } else if (verified > 0) { + approvalStatus = 101; + } + + asha.put("approvalStatus", approvalStatus); + + ashaList.add(asha); + } + + Map response = new HashMap<>(); + + Map approvalStatus = new HashMap<>(); + approvalStatus.put("verified", overallVerified>0?1:0); + approvalStatus.put("pending", overallPending>0?1:0); + approvalStatus.put("rejected", overallRejected>0?1:0); + + response.put("approvalStatus", approvalStatus); + response.put("data", ashaList); + response.put("statusCode", 200); + + return response; + } + @Transactional + public int updateApprovalStatus(Integer ashaId, + Integer month, + Integer year, + Integer approvalStatus, + String incentiveIds, + String reason, + String otherReason, + String token) { + try { + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); + String ashaSupervisorUsername = jwtUtil.extractUsername(token); + + // 👉 If Rejected → Update only selected incentive IDs + if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode()) + && incentiveIds != null + && !incentiveIds.isEmpty()) { + + String[] ids = incentiveIds.split(","); + int totalUpdated = 0; + + for (String idStr : ids) { + Long id = Long.parseLong(idStr.trim()); + + if (incentiveRecordRepo.existsById(id)) { + totalUpdated += incentiveRecordRepo.updateApprovalStatusById( + id, + approvalStatus, + ashaSupervisorUserId, + ashaSupervisorUsername, + reason, + otherReason + ); + } + } + + return totalUpdated; + } + + // 👉 Otherwise update full month data + return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( + ashaId, + approvalStatus, + startDate, + endDate, + ashaSupervisorUserId, + ashaSupervisorUsername + ); + + } catch (Exception e) { + e.printStackTrace(); + return 0; // never return null in int method + } + } + private JSONObject buildEmptyIncentiveSummary() { JSONObject summary = new JSONObject(); summary.put("verified", 0); From cfc24b55225a1b6a25c0375fc54dbe1b9fc79224 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 6 Mar 2026 17:59:15 +0530 Subject: [PATCH 191/450] add reason in reject incentive --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 2 ++ 1 file changed, 2 insertions(+) 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 19aa78770..9ef9d41de 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -76,6 +76,8 @@ Long getTotalAmountByAsha( @Query("UPDATE IncentiveActivityRecord iar " + "SET iar.approvalStatus = :approvalStatus, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + + "iar.reason = NULL, " + + "iar.otherReason = NULL, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.ashaId = :ashaId " + "AND iar.createdDate >= :startDate " From a3de947426cb52d498e5d4faca3ecfbf0829cbff Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 11:35:33 +0530 Subject: [PATCH 192/450] add reason in reject incentive --- .../flw/repo/iemr/AshaSupervisorLoginRepo.java | 17 +++++++++++++++++ .../impl/SupervisorDashboardServiceImpl.java | 9 ++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java index ded4cbd23..bb4bf2803 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -44,4 +44,21 @@ List getAshasAtFacility( @Param("supervisorUserID") Integer supervisorUserID, @Param("facilityID") Integer facilityID, @Param("approvalStatus") Integer approvalStatus); + + + @Query(value = "SELECT DISTINCT asm.ashaUserID, u.FirstName, u.LastName, " + + "COALESCE(u.AgentID,'') AS agentID, " + + "COALESCE(u.EmergencyContactNo,'') AS mobile, " + + "COALESCE(g.GenderName,'') AS gender " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.ashaUserID AND u.Deleted = false " + + "LEFT JOIN m_gender g ON g.GenderID = u.GenderID " + + "LEFT JOIN incentive_activity_record iar ON iar.asha_id = asm.ashaUserID " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.deleted = false " + + "AND (:approvalStatus = 0 OR iar.approval_status = :approvalStatus)", + nativeQuery = true) + List getAshasAtFacility( + @Param("supervisorUserID") Integer supervisorUserID, + @Param("approvalStatus") Integer approvalStatus); } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index a9e406d04..bae5b3a0d 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -206,8 +206,15 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In @Override public Map getAshasAtFacility(Integer supervisorId, Integer facilityId, Integer month, Integer year, Integer approvalStatusID) { + List rows; - List rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); + if(!facilityId.equals(0)){ + rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, approvalStatusID); + + }else { + rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); + + } List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); List> ashaList = new ArrayList<>(); From acbb1a357ca2ad360958fa7de3b69ae6b7b07ac4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 11:45:13 +0530 Subject: [PATCH 193/450] add reason in reject incentive --- .../iemr/flw/service/impl/SupervisorDashboardServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index bae5b3a0d..59a377807 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -208,7 +208,7 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Integer month, Integer year, Integer approvalStatusID) { List rows; - if(!facilityId.equals(0)){ + if(facilityId.equals(0)){ rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, approvalStatusID); }else { From ba16801783893425708ad4e6c446f2e977a81aa7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 14:49:31 +0530 Subject: [PATCH 194/450] incentive claim feature --- .../flw/controller/IncentiveController.java | 43 +++++++++++++++++-- .../domain/iemr/IncentiveActivityRecord.java | 3 ++ .../iemr/flw/dto/iemr/IncentiveRecordDTO.java | 2 + .../flw/repo/iemr/IncentiveRecordRepo.java | 19 +++++++- .../iemr/flw/service/IncentiveService.java | 6 ++- .../service/impl/IncentiveServiceImpl.java | 36 +++++++++++++++- 6 files changed, 102 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index ba60dffb3..b177ce74a 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -1,9 +1,7 @@ package com.iemr.flw.controller; 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.dto.iemr.*; import com.iemr.flw.service.IncentiveService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; @@ -14,10 +12,14 @@ 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.List; +import java.util.Map; @RestController @RequestMapping(value = "/incentive", consumes = "application/json", produces = "application/json") @@ -29,6 +31,9 @@ public class IncentiveController { @Autowired IncentiveService incentiveService; + @Autowired + private JwtUtil jwtUtil; + @Operation(summary = "save incentive master") @RequestMapping(value = {"/masterData/saveAll"}, method = {RequestMethod.POST}) public String saveIncentiveMasterData(@RequestBody List activityDTOS, @RequestHeader(value = "Authorization") String authorization, HttpServletRequest request) { @@ -128,4 +133,36 @@ public String updateIncentive(@ModelAttribute PendingActivityDTO requestDTO) { } + @PostMapping("/updateClaim") + public ResponseEntity updateApprovalStatus( + @RequestBody UpdateClaimedStatusRequestDTO request, + @RequestHeader(value = "JwtToken") String token) { + + try { + if (token == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + } + + String result = incentiveService.updateClaimStatus( + jwtUtil.extractUserId(token), + request.getMonth(), + request.getYear(), + request.isClaimed(), + token + ); + + Map response = new HashMap<>(); + response.put("statusCode", 200); + response.put("message", result); + + return ResponseEntity.ok(response); + + } catch (Exception e) { + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body("Server error: " + e.getMessage()); + } + } + + } 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 4a61e0d5a..766c4d659 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -70,6 +70,9 @@ public class IncentiveActivityRecord { @Column(name = "other_reason") private String otherReason; + @Column(name = "is_claimed") + private Boolean isClaimed; + @Transient private String activityDec; 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 763fc6353..43002ca4e 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -51,5 +51,7 @@ public class IncentiveRecordDTO { private String otherReason; + private Boolean isClaimed; + } 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 9ef9d41de..5e2f33867 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -2,6 +2,7 @@ import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import jakarta.persistence.Column; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; @@ -80,6 +81,7 @@ Long getTotalAmountByAsha( + "iar.otherReason = NULL, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.ashaId = :ashaId " + + "AND iar.isClaimed = true " + "AND iar.createdDate >= :startDate " + "AND iar.createdDate < :endDate") int updateApprovalStatusByAshaAndDateRange( @@ -92,13 +94,15 @@ int updateApprovalStatusByAshaAndDateRange( @Modifying + @Transactional @Query("UPDATE IncentiveActivityRecord iar " + "SET iar.approvalStatus = :status, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.reason = :reason, " + "iar.otherReason = :otherReason, " + "iar.verifiedByUserName = :ashaSupervisorUserName " - + "WHERE iar.id = :id") + + "WHERE iar.id = :id " + + "AND iar.isClaimed = true") int updateApprovalStatusById( @Param("id") Long id, @Param("status") Integer status, @@ -106,6 +110,19 @@ int updateApprovalStatusById( @Param("ashaSupervisorUserName") String ashaSupervisorUserName, @Param("reason") String reason, @Param("otherReason") String otherReason + ); + @Modifying + @Transactional + @Query("UPDATE IncentiveActivityRecord iar " + + "SET iar.isClaimed = :isClaimed " + + "WHERE iar.ashaId = :ashaId " + + "AND iar.createdDate >= :startDate " + + "AND iar.createdDate < :endDate") + int updateClaimStatusByAshaAndDateRange( + @Param("ashaId") Integer ashaId, + @Param("isClaimed") Boolean isClaimed, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate ); } diff --git a/src/main/java/com/iemr/flw/service/IncentiveService.java b/src/main/java/com/iemr/flw/service/IncentiveService.java index d6bb55507..3ed165b22 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveService.java @@ -16,4 +16,8 @@ public interface IncentiveService { String getAllIncentivesByUserId(GetBenRequestHandler requestDTO); String updateIncentive(PendingActivityDTO pendingActivityDTO); -} + public String updateClaimStatus(Integer ashaId, + Integer month, + Integer year, + Boolean isClaimed, + String token);} 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 cb6116a76..e0ef2072c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -8,6 +8,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.IncentiveApprovalStatus; import com.iemr.flw.masterEnum.IncentiveName; import com.iemr.flw.masterEnum.StateCode; import com.iemr.flw.repo.identity.BeneficiaryRepo; @@ -21,9 +22,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; import java.math.BigInteger; import java.sql.Timestamp; import java.time.LocalDate; @@ -393,6 +393,38 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { return null; } + @Transactional + public String updateClaimStatus(Integer ashaId, + Integer month, + Integer year, + Boolean isClaimed, + String token) { + try { + + LocalDate startLocalDate = LocalDate.of(year, month, 1); + LocalDate endLocalDate = startLocalDate.plusMonths(1); + + Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + + + Integer updateRecord= recordRepo.updateClaimStatusByAshaAndDateRange( + ashaId, + isClaimed, + startDate, + endDate + ); + if(updateRecord>0){ + return "Incentive is claimed successfully "; + } + + } catch (Exception e) { + e.printStackTrace(); + return e.getMessage(); // never return null in int method + } + return null; + } + public String convertAttachmentsToJson(MultipartFile file) { try { String base64 = Base64.getEncoder().encodeToString(file.getBytes()); From 9de2ebdd3fb48163929b017f43b5f226cedf1608 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 14:51:39 +0530 Subject: [PATCH 195/450] incentive claim feature --- .../flw/dto/iemr/UpdateClaimedStatusRequestDTO.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/main/java/com/iemr/flw/dto/iemr/UpdateClaimedStatusRequestDTO.java diff --git a/src/main/java/com/iemr/flw/dto/iemr/UpdateClaimedStatusRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UpdateClaimedStatusRequestDTO.java new file mode 100644 index 000000000..052b7d12f --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/UpdateClaimedStatusRequestDTO.java @@ -0,0 +1,11 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class UpdateClaimedStatusRequestDTO { + private Integer ashaId; + private Integer month; + private Integer year; + private boolean isClaimed; +} From 4b61f00c61228a66056fac1c58348d661d90e8e7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 15:26:04 +0530 Subject: [PATCH 196/450] incentive claim feature --- .../iemr/flw/domain/iemr/IncentiveActivityRecord.java | 9 +++++++++ .../java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java | 9 +++++++++ .../iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java | 6 ++++-- .../com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 10 +++++++++- .../iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++++ .../service/impl/SupervisorDashboardServiceImpl.java | 4 ++++ 6 files changed, 39 insertions(+), 3 deletions(-) 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 766c4d659..6e1c18010 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -73,6 +73,15 @@ public class IncentiveActivityRecord { @Column(name = "is_claimed") private Boolean isClaimed; + @Column(name = "approval_date") + private Timestamp approvalDate; + + @Column(name = "calimed_date") + private Timestamp calimedDate; + + @Transient + private String supervisorRole; + @Transient private String activityDec; 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 43002ca4e..354e762d5 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/IncentiveRecordDTO.java @@ -53,5 +53,14 @@ public class IncentiveRecordDTO { private Boolean isClaimed; + private Timestamp approvalDate; + + private Timestamp calimedDate; + + private String supervisorRole; + + + + } diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java index bb4bf2803..e4f3693bb 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -38,7 +38,8 @@ public interface AshaSupervisorLoginRepo extends CrudRepository getAshasAtFacility( @Param("supervisorUserID") Integer supervisorUserID, @@ -56,7 +57,8 @@ List getAshasAtFacility( + "LEFT JOIN incentive_activity_record iar ON iar.asha_id = asm.ashaUserID " + "WHERE asm.supervisorUserID = :supervisorUserID " + "AND asm.deleted = false " - + "AND (:approvalStatus = 0 OR iar.approval_status = :approvalStatus)", + + "AND (:approvalStatus = 0 OR iar.approval_status = :approvalStatus) " + + "AND iar.is_claimed = true", nativeQuery = true) List getAshasAtFacility( @Param("supervisorUserID") Integer supervisorUserID, 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 5e2f33867..05a6bb14e 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -54,6 +54,7 @@ IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( "SUM(CASE WHEN record.approvalStatus = 103 THEN 1 ELSE 0 END) " + "FROM IncentiveActivityRecord record " + "WHERE record.ashaId = :ashaId " + + "AND record.isClaimed = true " + "AND record.createdDate >= :startDate " + "AND record.createdDate < :endDate") List getStatusCountByAshaId( @@ -65,6 +66,7 @@ List getStatusCountByAshaId( @Query("SELECT COALESCE(SUM(record.amount), 0) " + "FROM IncentiveActivityRecord record " + "WHERE record.ashaId = :ashaId " + + "AND record.isClaimed = true " + "AND record.startDate <= :toDate " + "AND record.endDate >= :fromDate") Long getTotalAmountByAsha( @@ -79,6 +81,7 @@ Long getTotalAmountByAsha( + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.reason = NULL, " + "iar.otherReason = NULL, " + + "iar.approvalDate = :approvalDate, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.ashaId = :ashaId " + "AND iar.isClaimed = true " @@ -89,6 +92,7 @@ int updateApprovalStatusByAshaAndDateRange( @Param("approvalStatus") Integer approvalStatus, @Param("startDate") Timestamp startDate, @Param("endDate") Timestamp endDate, + @Param("approvalDate") Timestamp approvalDate, @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, @Param("ashaSupervisorUserName") String ashaSupervisorUserName); @@ -99,6 +103,7 @@ int updateApprovalStatusByAshaAndDateRange( + "SET iar.approvalStatus = :status, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.reason = :reason, " + + "iar.approvalDate = :approvalDate, " + "iar.otherReason = :otherReason, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.id = :id " @@ -109,19 +114,22 @@ int updateApprovalStatusById( @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, @Param("ashaSupervisorUserName") String ashaSupervisorUserName, @Param("reason") String reason, + @Param("approvalDate") Timestamp approvalDate, @Param("otherReason") String otherReason ); @Modifying @Transactional @Query("UPDATE IncentiveActivityRecord iar " - + "SET iar.isClaimed = :isClaimed " + + "SET iar.isClaimed = :isClaimed, " + + "iar.calimedDate = :calimedDate " + "WHERE iar.ashaId = :ashaId " + "AND iar.createdDate >= :startDate " + "AND iar.createdDate < :endDate") int updateClaimStatusByAshaAndDateRange( @Param("ashaId") Integer ashaId, @Param("isClaimed") Boolean isClaimed, + @Param("calimedDate") Timestamp calimedDate, @Param("startDate") Timestamp startDate, @Param("endDate") Timestamp endDate ); 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 e0ef2072c..70a8a8703 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -189,6 +189,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); entry.setGroupName(incentiveActivity.getGroup()); entry.setActivityDec(incentiveActivity.getDescription()); + entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); } @@ -400,6 +401,8 @@ public String updateClaimStatus(Integer ashaId, Boolean isClaimed, String token) { try { + Timestamp calimedDate = Timestamp.valueOf(LocalDateTime.now()); + LocalDate startLocalDate = LocalDate.of(year, month, 1); LocalDate endLocalDate = startLocalDate.plusMonths(1); @@ -411,6 +414,7 @@ public String updateClaimStatus(Integer ashaId, Integer updateRecord= recordRepo.updateClaimStatusByAshaAndDateRange( ashaId, isClaimed, + calimedDate, startDate, endDate ); diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 59a377807..69fd289de 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -2,6 +2,7 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -316,6 +317,7 @@ public int updateApprovalStatus(Integer ashaId, String otherReason, String token) { try { + Timestamp approvalDate = Timestamp.valueOf(LocalDateTime.now()); LocalDate startLocalDate = LocalDate.of(year, month, 1); LocalDate endLocalDate = startLocalDate.plusMonths(1); @@ -344,6 +346,7 @@ public int updateApprovalStatus(Integer ashaId, ashaSupervisorUserId, ashaSupervisorUsername, reason, + approvalDate, otherReason ); } @@ -358,6 +361,7 @@ public int updateApprovalStatus(Integer ashaId, approvalStatus, startDate, endDate, + approvalDate, ashaSupervisorUserId, ashaSupervisorUsername ); From 5de0958e903e7f07ea04f24c12e86a31d88dc0f6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 16:43:13 +0530 Subject: [PATCH 197/450] incentive claim feature --- .../impl/MaternalHealthServiceImpl.java | 65 +++++++++++++++++-- 1 file changed, 58 insertions(+), 7 deletions(-) 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 08bb264a3..1ff2c9eb9 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -26,6 +26,7 @@ import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; @@ -675,10 +676,9 @@ private void checkAndAddIncentives(List ancList) { } } if (ancFullActivityAM != null) { - if (ancVisit.getAncVisit() == 4 || ancVisit.getAncVisit() == 2 || ancVisit.getAncVisit() == 3) { - recordAncRelatedIncentive(ancFullActivityAM, ancVisit); + if (ancVisit.getAncVisit() != null && ancVisit.getAncVisit() == 4) { + recordFullAncIncentive(ancFullActivityAM, ancVisit); } - } if (ancFullActivityCH != null) { if (ancVisit.getAncVisit() != null) { @@ -729,7 +729,26 @@ private void checkAndAddIncentives(List ancList) { } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { - IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId()); + + if (ancVisit.getAncDate() == null || ancVisit.getLmpDate() == null) { + return; + } + + LocalDate ancLocalDate = ancVisit.getAncDate().toLocalDateTime().toLocalDate(); + LocalDate lmpLocalDate = ancVisit.getLmpDate().toLocalDateTime().toLocalDate(); + + long weeksBetween = ChronoUnit.WEEKS.between(lmpLocalDate, ancLocalDate); + + if (weeksBetween < 0 || weeksBetween >= 12) { + return; + } + + IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivity.getId(), + ancVisit.getCreatedDate(), + ancVisit.getBenId() + ); + Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); if (record == null) { @@ -739,16 +758,48 @@ record = new IncentiveActivityRecord(); record.setCreatedBy(ancVisit.getCreatedBy()); record.setUpdatedDate(ancVisit.getCreatedDate()); record.setUpdatedBy(ancVisit.getCreatedBy()); - record.setStartDate(ancVisit.getCreatedDate()); - record.setEndDate(ancVisit.getCreatedDate()); + record.setStartDate(ancVisit.getLmpDate()); + record.setEndDate(ancVisit.getLmpDate()); record.setBenId(ancVisit.getBenId()); record.setAshaId(userId); record.setAmount(Long.valueOf(incentiveActivity.getRate())); recordRepo.save(record); } - } + private void recordFullAncIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { + + // ✅ Once per case check — already record hai toh return + IncentiveActivityRecord existRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivity.getId(), + ancVisit.getCreatedDate(), + ancVisit.getBenId() + ); + + + if (existRecord != null) { + return; + } + + // ✅ userId null check + Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); + if (userId == null) { + return; + } + + IncentiveActivityRecord record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); + record.setCreatedDate(ancVisit.getAncDate()); + record.setCreatedBy(ancVisit.getCreatedBy()); + record.setUpdatedDate(ancVisit.getAncDate()); + record.setUpdatedBy(ancVisit.getCreatedBy()); + record.setStartDate(ancVisit.getAncDate()); + record.setEndDate(ancVisit.getAncDate()); + record.setBenId(ancVisit.getBenId()); + record.setAshaId(userId); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } public void sendAncDueTomorrowNotifications(String ashaId) { try { From c2da167e88546b8ce79dbb7eaec73509055e5a39 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 16:43:44 +0530 Subject: [PATCH 198/450] incentive claim feature --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 -- 1 file changed, 2 deletions(-) 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 1ff2c9eb9..7afb3bb79 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -769,7 +769,6 @@ record = new IncentiveActivityRecord(); private void recordFullAncIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { - // ✅ Once per case check — already record hai toh return IncentiveActivityRecord existRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), ancVisit.getCreatedDate(), @@ -781,7 +780,6 @@ private void recordFullAncIncentive(IncentiveActivity incentiveActivity, ANCVisi return; } - // ✅ userId null check Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); if (userId == null) { return; From 20f6b56c113274bfaa4cbabe59e463cf5e5fe8d9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 17:58:57 +0530 Subject: [PATCH 199/450] incentive claim feature --- .../impl/MaternalHealthServiceImpl.java | 22 ++++++++++++++++++- .../impl/UtpreronaPaymentIntegrationImpl.java | 6 +++-- 2 files changed, 25 insertions(+), 3 deletions(-) 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 7afb3bb79..234a26837 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -671,7 +671,7 @@ private void checkAndAddIncentives(List ancList) { if (ancVisit.getAncVisit() != null) { if (ancVisit.getAncVisit() == 1) { - recordAncRelatedIncentive(anc1Activity, ancVisit); + recordAncFirstTRIMIncentive(anc1Activity, ancVisit); } } } @@ -729,6 +729,26 @@ private void checkAndAddIncentives(List ancList) { } 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); + } + + } + private void recordAncFirstTRIMIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { if (ancVisit.getAncDate() == null || ancVisit.getLmpDate() == null) { return; diff --git a/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java index ca884383c..f0e5a5544 100644 --- a/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UtpreronaPaymentIntegrationImpl.java @@ -16,7 +16,8 @@ @Service public class UtpreronaPaymentIntegrationImpl { // @Value("${ssdPortalUrl}") - private String API_URL = ""; + private String API_URL = "https://nhmssd.assam.gov.in/APPMS_2024_25/api/utpreronaPayment.php"; + private String API_KEY = "41202fa384eab2725a17bbac58cf708bf04cd1dd5175010941606156dc36d6b5"; private static final int TIMEOUT_SECONDS = 30; private final HttpClient httpClient; @@ -33,7 +34,7 @@ public ApiResponse sendPaymentRequest(PaymentRequest paymentRequest) throws IOException, InterruptedException { String jsonBody = objectMapper.writeValueAsString(paymentRequest); - System.out.println("📤 Sending Request:"); + System.out.println("Sending Request:"); System.out.println(objectMapper.writerWithDefaultPrettyPrinter() .writeValueAsString(paymentRequest)); @@ -42,6 +43,7 @@ public ApiResponse sendPaymentRequest(PaymentRequest paymentRequest) .timeout(Duration.ofSeconds(TIMEOUT_SECONDS)) .header("Content-Type", "application/json") .header("Accept", "application/json") + .header("x-api-key", API_KEY) .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); From 93cdd8366123f1cf168935372e64651a3e941418 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 18:18:32 +0530 Subject: [PATCH 200/450] incentive claim feature --- .../impl/MaternalHealthServiceImpl.java | 64 +++++++++++++++++-- 1 file changed, 60 insertions(+), 4 deletions(-) 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 234a26837..a396055d8 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -153,27 +153,50 @@ public List getANCVisits(GetBenRequestHandler dto) { @Override public String saveANCVisit(List ancVisitDTOs) { try { + + logger.info("ANC save process started. Total records: {}", ancVisitDTOs.size()); + List ancList = new ArrayList<>(); List ancCareList = new ArrayList<>(); + ancVisitDTOs.forEach(it -> { + + logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getAncVisit()); + ANCVisit ancVisit = ancVisitRepo.findANCVisitByBenIdAndAncVisitAndIsActive(it.getBenId(), it.getAncVisit(), true); + logger.info("ANC visit fetch completed"); + if (ancVisit != null) { + + logger.info("Existing ANC visit found for BenId: {}", it.getBenId()); + Long id = ancVisit.getId(); modelMapper.map(it, ancVisit); ancVisit.setId(id); + } else { + + logger.info("New ANC visit will be created for BenId: {}", it.getBenId()); + ancVisit = new ANCVisit(); modelMapper.map(it, ancVisit); ancVisit.setId(null); Long benRegId = beneficiaryRepo.getRegIDFromBenId(it.getBenId()); + logger.info("Beneficiary Reg Id fetched: {}", benRegId); + // Saving data in BenVisitDetails table - PregnantWomanRegister pwr = pregnantWomanRegisterRepo.findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); + PregnantWomanRegister pwr = pregnantWomanRegisterRepo + .findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); + + logger.info("PregnantWomanRegister fetched"); + BenVisitDetail benVisitDetail = new BenVisitDetail(); modelMapper.map(it, benVisitDetail); + benVisitDetail.setBeneficiaryRegId(benRegId); benVisitDetail.setVisitCategory("ANC"); benVisitDetail.setVisitReason("Follow Up"); @@ -182,37 +205,70 @@ public String saveANCVisit(List ancVisitDTOs) { benVisitDetail.setModifiedBy(it.getUpdatedBy()); benVisitDetail.setLastModDate(it.getUpdatedDate()); benVisitDetail.setProviderServiceMapID(it.getProviderServiceMapID()); + + logger.info("Saving BenVisitDetail"); + benVisitDetail = benVisitDetailsRepo.save(benVisitDetail); + logger.info("BenVisitDetail saved with id: {}", benVisitDetail.getBenVisitId()); + // Saving Data in AncCare table AncCare ancCare = new AncCare(); modelMapper.map(it, ancCare); + ancCare.setBenVisitId(benVisitDetail.getBenVisitId()); ancCare.setBeneficiaryRegId(benRegId); + if (pwr != null) { + + logger.info("LMP found calculating EDD"); + ancCare.setLastMenstrualPeriodLmp(pwr.getLmpDate()); + Calendar cal = Calendar.getInstance(); cal.setTime(pwr.getLmpDate()); cal.add(Calendar.DAY_OF_WEEK, 280); + ancCare.setExpectedDateofDelivery(new Timestamp(cal.getTime().getTime())); } + ancCare.setTrimesterNumber(it.getAncVisit().shortValue()); ancCare.setModifiedBy(it.getUpdatedBy()); ancCare.setLastModDate(it.getUpdatedDate()); ancCare.setProcessed("N"); + ancCareList.add(ancCare); + + logger.info("AncCare added to list"); } + ancList.add(ancVisit); + logger.info("ANCVisit added to list"); + }); + logger.info("Saving ANCVisit list"); + ancVisitRepo.saveAll(ancList); + + logger.info("ANCVisit saved successfully"); + + logger.info("Saving AncCare list"); + ancCareRepo.saveAll(ancCareList); - checkAndAddIncentives(ancList); + + logger.info("AncCare saved successfully"); + logger.info("ANC visit details saved"); + checkAndAddIncentives(ancList); + 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); + + logger.error("Saving ANC visit details failed with error : {}", e.getMessage()); + logger.error("Full exception : ", e); + } return null; } From e5f966f66178e3dc17006f7319e5fe9d3b52021a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 18:31:30 +0530 Subject: [PATCH 201/450] incentive claim feature --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 70a8a8703..6b951054c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -189,7 +189,10 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); entry.setGroupName(incentiveActivity.getGroup()); entry.setActivityDec(incentiveActivity.getDescription()); - entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); + if(entry.getVerifiedByUserId()!=null){ + entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); + + } } From 48e7c5b6eb42065dace6ad6de77d7ea43d42d6ef Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 19:03:21 +0530 Subject: [PATCH 202/450] incentive claim feature --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 a396055d8..9588c023f 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -830,9 +830,9 @@ private void recordAncFirstTRIMIncentive(IncentiveActivity incentiveActivity, AN if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(incentiveActivity.getId()); - record.setCreatedDate(ancVisit.getCreatedDate()); + record.setCreatedDate(ancVisit.getLmpDate()); record.setCreatedBy(ancVisit.getCreatedBy()); - record.setUpdatedDate(ancVisit.getCreatedDate()); + record.setUpdatedDate(ancVisit.getLmpDate()); record.setUpdatedBy(ancVisit.getCreatedBy()); record.setStartDate(ancVisit.getLmpDate()); record.setEndDate(ancVisit.getLmpDate()); From af7c1d7273715aa30bc00d32c640daf2142f6a52 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 10 Mar 2026 19:19:19 +0530 Subject: [PATCH 203/450] incentive claim feature --- .../controller/MaternalHealthController.java | 16 +- .../flw/service/MaternalHealthService.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 163 +++++++++--------- 3 files changed, 89 insertions(+), 92 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java index f0955af6d..9c8459daa 100644 --- a/src/main/java/com/iemr/flw/controller/MaternalHealthController.java +++ b/src/main/java/com/iemr/flw/controller/MaternalHealthController.java @@ -98,16 +98,20 @@ public String getPregnantWomanList(@RequestBody GetBenRequestHandler requestDTO, @Operation(summary = "save anc visit details") @RequestMapping(value = { "/ancVisit/saveAll" }, method = { RequestMethod.POST }) public String saveANCVisit(@RequestBody List ancVisitDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "JwtToken") String token) { OutputResponse response = new OutputResponse(); try { if (ancVisitDTOs.size() != 0) { logger.info("Saving ANC visits with timestamp : " + new Timestamp(System.currentTimeMillis())); - String s = maternalHealthService.saveANCVisit(ancVisitDTOs); - if (s != null) - response.setResponse(s); - else - response.setError(5000, "Saving anc data to db failed"); + if(token!=null){ + String s = maternalHealthService.saveANCVisit(ancVisitDTOs,jwtUtil.extractUserId(token)); + + if (s != null) + response.setResponse(s); + else + response.setError(5000, "Saving anc data to db failed"); + } + } else response.setError(5000, "Invalid/NULL request obj"); } catch (Exception e) { diff --git a/src/main/java/com/iemr/flw/service/MaternalHealthService.java b/src/main/java/com/iemr/flw/service/MaternalHealthService.java index 33de9bc93..5e4e9b615 100644 --- a/src/main/java/com/iemr/flw/service/MaternalHealthService.java +++ b/src/main/java/com/iemr/flw/service/MaternalHealthService.java @@ -16,7 +16,7 @@ public interface MaternalHealthService { List getANCVisits(GetBenRequestHandler dto); - String saveANCVisit(List ancVisitDTOs); + String saveANCVisit(List ancVisitDTOs,Integer useId ); List getPmsmaRecords(GetBenRequestHandler dto); 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 9588c023f..52de9aa68 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -151,7 +151,7 @@ public List getANCVisits(GetBenRequestHandler dto) { } @Override - public String saveANCVisit(List ancVisitDTOs) { + public String saveANCVisit(List ancVisitDTOs,Integer userId) { try { logger.info("ANC save process started. Total records: {}", ancVisitDTOs.size()); @@ -260,7 +260,7 @@ public String saveANCVisit(List ancVisitDTOs) { logger.info("AncCare saved successfully"); logger.info("ANC visit details saved"); - checkAndAddIncentives(ancList); + checkAndAddIncentives(ancList,userId); return "no of anc details saved: " + ancList.size(); @@ -677,111 +677,104 @@ record = new IncentiveActivityRecord(); } - private void checkAndAddIncentives(List ancList) { - - IncentiveActivity anc1Activity = - 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()); + private void checkAndAddIncentives(List ancList, Integer userId) { + + Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); + + IncentiveActivity anc1Activity = null; + IncentiveActivity ancFullActivityAM = null; + IncentiveActivity identifiedHrpActivityAM = null; + IncentiveActivity comprehensiveAbortionActivityAM = null; + IncentiveActivity paiucdActivityAM = null; + + IncentiveActivity ancFullActivityCH = null; + IncentiveActivity comprehensiveAbortionActivityCH = null; + IncentiveActivity identifiedHrpActivityCH = null; + IncentiveActivity paiucdActivityCH = null; + + // ✅ State 5 — Assam + if (stateId.equals(5)) { + anc1Activity = incentivesRepo.findIncentiveMasterByNameAndGroup( + "ANC_REGISTRATION_1ST_TRIM", GroupName.MATERNAL_HEALTH.getDisplayName()); + ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FULL_ANC", GroupName.MATERNAL_HEALTH.getDisplayName()); + identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + "EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); + comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + "COMPREHENSIVE_ABORTION_CARE", GroupName.MATERNAL_HEALTH.getDisplayName()); + paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + } - IncentiveActivity paiucdActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + // ✅ State 8 + if (stateId.equals(8)) { + ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + "ANC_FOUR_CHECKUPS_SUPPORT", GroupName.ACTIVITY.getDisplayName()); + comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + "COMPREHENSIVE_ABORTION_CARE", GroupName.ACTIVITY.getDisplayName()); + identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + "EPMSMA_HRP_IDENTIFIED", GroupName.ACTIVITY.getDisplayName()); + paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); + } - IncentiveActivity paiucdActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); + final IncentiveActivity finalAnc1Activity = anc1Activity; + final IncentiveActivity finalAncFullActivityAM = ancFullActivityAM; + final IncentiveActivity finalIdentifiedHrpActivityAM = identifiedHrpActivityAM; + final IncentiveActivity finalComprehensiveAbortionActivityAM = comprehensiveAbortionActivityAM; + final IncentiveActivity finalPaiucdActivityAM = paiucdActivityAM; + final IncentiveActivity finalAncFullActivityCH = ancFullActivityCH; + final IncentiveActivity finalComprehensiveAbortionActivityCH = comprehensiveAbortionActivityCH; + final IncentiveActivity finalIdentifiedHrpActivityCH = identifiedHrpActivityCH; + final IncentiveActivity finalPaiucdActivityCH = paiucdActivityCH; ancList.forEach(ancVisit -> { - if (paiucdActivityAM != null) { - if (ancVisit.getIsPaiucd()!= null) { - if (ancVisit.getIsPaiucd().equals("Yes")) { - recordAncRelatedIncentive(paiucdActivityAM, ancVisit); - - } - } + if (finalPaiucdActivityAM != null && ancVisit.getIsPaiucd() != null + && ancVisit.getIsPaiucd().equals("Yes")) { + recordAncRelatedIncentive(finalPaiucdActivityAM, ancVisit); } - if (paiucdActivityCH != null) { - - if (ancVisit.getIsPaiucd()!= null) { - if (ancVisit.getIsPaiucd().equals("Yes")) { - - recordAncRelatedIncentive(paiucdActivityCH, ancVisit); - - } - } - - + if (finalPaiucdActivityCH != null && ancVisit.getIsPaiucd() != null + && ancVisit.getIsPaiucd().equals("Yes")) { + recordAncRelatedIncentive(finalPaiucdActivityCH, ancVisit); } - if (anc1Activity != null) { - if (ancVisit.getAncVisit() != null) { - if (ancVisit.getAncVisit() == 1) { - recordAncFirstTRIMIncentive(anc1Activity, ancVisit); - } - } - } - if (ancFullActivityAM != null) { - if (ancVisit.getAncVisit() != null && ancVisit.getAncVisit() == 4) { - recordFullAncIncentive(ancFullActivityAM, ancVisit); - } + if (finalAnc1Activity != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 1) { + recordAncFirstTRIMIncentive(finalAnc1Activity, ancVisit); } - if (ancFullActivityCH != null) { - if (ancVisit.getAncVisit() != null) { - if (ancVisit.getAncVisit() == 4) { - recordAncRelatedIncentive(ancFullActivityCH, ancVisit); - } - } + if (finalAncFullActivityAM != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordFullAncIncentive(finalAncFullActivityAM, ancVisit); } - if (comprehensiveAbortionActivityAM != null) { - if (ancVisit.getIsAborted() != null) { - if (ancVisit.getIsAborted()) { - recordAncRelatedIncentive(comprehensiveAbortionActivityAM, ancVisit); - } - } + if (finalAncFullActivityCH != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordAncRelatedIncentive(finalAncFullActivityCH, ancVisit); } - if (comprehensiveAbortionActivityCH != null) { - if (ancVisit.getIsAborted() != null) { - if (ancVisit.getIsAborted()) { - recordAncRelatedIncentive(comprehensiveAbortionActivityCH, ancVisit); - } - } - + if (finalComprehensiveAbortionActivityAM != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(finalComprehensiveAbortionActivityAM, ancVisit); } - if (identifiedHrpActivityAM != null) { - if (ancVisit.getIsHrpConfirmed() != null) { - if (ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(identifiedHrpActivityAM, ancVisit); - } - } + if (finalComprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(finalComprehensiveAbortionActivityCH, ancVisit); } - if (identifiedHrpActivityCH != null) { - if (ancVisit.getIsHrpConfirmed() != null) { - if (ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(identifiedHrpActivityCH, ancVisit); - } - } - + if (finalIdentifiedHrpActivityAM != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(finalIdentifiedHrpActivityAM, ancVisit); } + if (finalIdentifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(finalIdentifiedHrpActivityCH, ancVisit); + } }); - - } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { From 0f7f2f9c395d94894fb7b277f7fe343d2c412006 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Mar 2026 12:48:52 +0530 Subject: [PATCH 204/450] add no of claim in incentive response --- .../flw/controller/IncentiveController.java | 26 ++++++++ .../iemr/flw/service/IncentiveService.java | 1 + .../service/impl/IncentiveServiceImpl.java | 59 +++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index b177ce74a..d116ce154 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -108,6 +108,32 @@ public String getAllIncentivesByUserId(@RequestBody GetBenRequestHandler request return response.toString(); } + + @Operation(summary = "get high risk assessment data of all beneficiaries registered with given user id") + @RequestMapping(value = {"/claimedIncentiveByUser"}, method = {RequestMethod.POST}) + public String getAllIncentivesByUserIdGroupByCount(@RequestBody GetBenRequestHandler requestDTO, + @RequestHeader(value = "Authorization") String Authorization) { + OutputResponse response = new OutputResponse(); + try { + + if (requestDTO != null) { + logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + + requestDTO); + String s = incentiveService.getAllIncentivesGroupedSummary(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(); + } + @RequestMapping(value = {"/update"}, method = RequestMethod.POST, consumes = {"multipart/form-data"}) public String updateIncentive(@ModelAttribute PendingActivityDTO requestDTO) { OutputResponse response = new OutputResponse(); diff --git a/src/main/java/com/iemr/flw/service/IncentiveService.java b/src/main/java/com/iemr/flw/service/IncentiveService.java index 3ed165b22..ee3f2b85d 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveService.java @@ -14,6 +14,7 @@ public interface IncentiveService { String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO); String getAllIncentivesByUserId(GetBenRequestHandler requestDTO); + String getAllIncentivesGroupedSummary(GetBenRequestHandler requestDTO); String updateIncentive(PendingActivityDTO pendingActivityDTO); public String updateClaimStatus(Integer ashaId, 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 6b951054c..36ff30c28 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -211,6 +211,65 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { return gson.toJson(dtos); } + public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { + + List entities = recordRepo.findRecordsByAsha(request.getAshaId()); + + Set activityIds = entities.stream() + .filter(e -> e.getActivityId() != null) + .map(IncentiveActivityRecord::getActivityId) + .collect(Collectors.toSet()); + + Map activityMap = incentivesRepo.findAllById(activityIds) + .stream() + .collect(Collectors.toMap(IncentiveActivity::getId, a -> a)); + + // ✅ activityId se group karo + Map> groupedByActivity = entities.stream() + .filter(e -> e.getActivityId() != null) + .collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); + + List> summaryList = new ArrayList<>(); + + for (Map.Entry> entry : groupedByActivity.entrySet()) { + Long activityId = entry.getKey(); + List records = entry.getValue(); + + // ✅ DB se activity details lo + IncentiveActivity activity = activityMap.get(activityId); + + + + Long totalAmount = records.stream() + .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) + .sum(); + + // ✅ Per activity amount = rate from master + Long perActivityAmount = activity != null ? Long.valueOf(activity.getRate()) : 0L; + + Map summary = new LinkedHashMap<>(); + summary.put("activityId", activityId); + summary.put("activityDec", activity != null ? activity.getDescription() : ""); + summary.put("groupName", activity != null ? activity.getGroup() : ""); + summary.put("amount", perActivityAmount); // ✅ naya field + summary.put("claimCount", records.size()); + summary.put("totalAmount", totalAmount); + + summaryList.add(summary); + } + + // ✅ Null safe sort by groupName + summaryList.sort(Comparator.comparing( + m -> m.get("groupName") != null ? m.get("groupName").toString() : "" + )); + + Map response = new LinkedHashMap<>(); + response.put("data", summaryList); + response.put("statusCode", 200); + + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(response); + } @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { logger.info("run--1"); From bdec2cee4f48afa82511a1d14856ce850b0bbbd5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Mar 2026 15:15:04 +0530 Subject: [PATCH 205/450] add isDefaultActivity in incentive --- .../flw/controller/IncentiveController.java | 25 ++++ .../flw/domain/iemr/IncentiveActivity.java | 3 + .../dto/identity/GetBenRequestHandler.java | 10 ++ .../iemr/flw/service/IncentiveService.java | 1 + .../service/impl/IncentiveServiceImpl.java | 112 ++++++++++++++++-- 5 files changed, 142 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index d116ce154..0d317f9d6 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -134,6 +134,31 @@ public String getAllIncentivesByUserIdGroupByCount(@RequestBody GetBenRequestHan return response.toString(); } + @Operation(summary = "get high risk assessment data of all beneficiaries registered with given user id") + @RequestMapping(value = {"/AllIncentiveByActivityId"}, method = {RequestMethod.POST}) + public String getAllIncentivesByActivityIdAndUser(@RequestBody GetBenRequestHandler requestDTO, + @RequestHeader(value = "Authorization") String Authorization) { + OutputResponse response = new OutputResponse(); + try { + + if (requestDTO != null) { + logger.info("request object with timestamp : " + new Timestamp(System.currentTimeMillis()) + " " + + requestDTO); + String s = incentiveService.getAllIncentivesGroupedActivity(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(); + } + @RequestMapping(value = {"/update"}, method = RequestMethod.POST, consumes = {"multipart/form-data"}) public String updateIncentive(@ModelAttribute PendingActivityDTO requestDTO) { OutputResponse response = new OutputResponse(); 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 ccfe11069..e10742d54 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java @@ -57,5 +57,8 @@ public class IncentiveActivity { @Column(name = "is_deleted") private Boolean isDeleted; + @Column(name = "is_default_activity") + private Boolean isDefaultActivity; + } 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 00e452c52..d7251165f 100644 --- a/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java +++ b/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java @@ -12,6 +12,16 @@ public class GetBenRequestHandler { private Integer ashaId; + private Long activityId; + + public Long getActivityId() { + return activityId; + } + + public void setActivityId(Long activityId) { + this.activityId = activityId; + } + public Integer getAshaId() { return ashaId; } diff --git a/src/main/java/com/iemr/flw/service/IncentiveService.java b/src/main/java/com/iemr/flw/service/IncentiveService.java index ee3f2b85d..8b2e46001 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveService.java @@ -15,6 +15,7 @@ public interface IncentiveService { String getAllIncentivesByUserId(GetBenRequestHandler requestDTO); String getAllIncentivesGroupedSummary(GetBenRequestHandler requestDTO); + String getAllIncentivesGroupedActivity(GetBenRequestHandler requestDTO); String updateIncentive(PendingActivityDTO pendingActivityDTO); public String updateClaimStatus(Integer ashaId, 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 36ff30c28..f32f87940 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -211,6 +211,91 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { return gson.toJson(dtos); } + + + @Override + public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { + + if (request.getVillageID() != StateCode.CG.getStateCode()) { + checkMonthlyAshaIncentive(request.getAshaId()); + } + + boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); + + List entities = recordRepo.findRecordsByAsha(request.getAshaId()) + .stream() + .filter(e -> e.getActivityId() != null + && e.getActivityId().equals(request.getActivityId()) // ✅ pehle hi filter + && incentivesRepo.findIncentiveMasterById(e.getActivityId(), isCG) != null) + .collect(Collectors.toList()); + + if (entities.isEmpty()) { + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(new ArrayList<>()); + } + + Set benIds = entities.stream() + .map(IncentiveActivityRecord::getBenId) + .filter(b -> b != null && b > 0L) + .collect(Collectors.toSet()); + + Map benNameMap = new HashMap<>(); + for (Long benId : benIds) { + try { + Long regId = beneficiaryRepo.getBenRegIdFromBenId(benId); + BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping( + BigInteger.valueOf(regId)).getBenDetailsId(); + RMNCHMBeneficiarydetail detail = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); + benNameMap.put(benId, detail.getFirstName() + " " + detail.getLastName()); + } catch (Exception e) { + benNameMap.put(benId, ""); + } + } + + IncentiveActivity activity = incentivesRepo.findById(request.getActivityId()).orElse(null); + String groupName = activity != null ? activity.getGroup() : ""; + String activityDec = activity != null ? activity.getDescription() : ""; + + Set userIds = entities.stream() + .map(IncentiveActivityRecord::getVerifiedByUserId) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + Map roleMap = new HashMap<>(); + for (Integer uid : userIds) { + try { + List roles = userRepo.getUserRole(uid); + if (roles != null && !roles.isEmpty()) { + roleMap.put(uid, userRepo.getUserRole(uid).get(0).getRoleName()); + } + } catch (Exception e) { + roleMap.put(uid, ""); + } + } + + List dtos = new ArrayList<>(); + + entities.forEach(entry -> { + if (entry.getName() == null) { + entry.setName(entry.getBenId() != null && entry.getBenId() > 0L + ? benNameMap.getOrDefault(entry.getBenId(), "") + : ""); + } + + entry.setGroupName(groupName); + entry.setActivityDec(activityDec); + + if (entry.getVerifiedByUserId() != null) { + entry.setSupervisorRole(roleMap.getOrDefault(entry.getVerifiedByUserId(), "")); + } + + dtos.add(modelMapper.map(entry, IncentiveRecordDTO.class)); + }); + + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(dtos); + } + @Override public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { List entities = recordRepo.findRecordsByAsha(request.getAshaId()); @@ -220,11 +305,20 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { .map(IncentiveActivityRecord::getActivityId) .collect(Collectors.toSet()); + boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); + Map activityMap = incentivesRepo.findAllById(activityIds) .stream() + .filter(a -> { + if (isCG) { + return a.getState() != null && a.getState().equals(StateCode.CG.getStateCode()); + } else { + return a.getState() == null || !a.getState().equals(StateCode.CG.getStateCode()); + } + }) .collect(Collectors.toMap(IncentiveActivity::getId, a -> a)); - // ✅ activityId se group karo + Map> groupedByActivity = entities.stream() .filter(e -> e.getActivityId() != null) .collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); @@ -235,7 +329,6 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { Long activityId = entry.getKey(); List records = entry.getValue(); - // ✅ DB se activity details lo IncentiveActivity activity = activityMap.get(activityId); @@ -244,7 +337,10 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) .sum(); - // ✅ Per activity amount = rate from master + if (activity == null) { + continue; + } + Long perActivityAmount = activity != null ? Long.valueOf(activity.getRate()) : 0L; Map summary = new LinkedHashMap<>(); @@ -253,22 +349,20 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { summary.put("groupName", activity != null ? activity.getGroup() : ""); summary.put("amount", perActivityAmount); // ✅ naya field summary.put("claimCount", records.size()); + summary.put("isDefaultActivity", activity != null && activity.getIsDefaultActivity() != null + ? activity.getIsDefaultActivity() + : false); summary.put("totalAmount", totalAmount); summaryList.add(summary); } - // ✅ Null safe sort by groupName summaryList.sort(Comparator.comparing( m -> m.get("groupName") != null ? m.get("groupName").toString() : "" )); - Map response = new LinkedHashMap<>(); - response.put("data", summaryList); - response.put("statusCode", 200); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(response); + return gson.toJson(summaryList); } @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { From 1f1fed1a2eaab1f728426b1c6ac671e740fe4660 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Mar 2026 16:34:21 +0530 Subject: [PATCH 206/450] ssd portal api job --- .../com/iemr/flw/dto/iemr/PaymentItem.java | 8 +- .../java/com/iemr/flw/dto/iemr/Period.java | 7 +- .../com/iemr/flw/dto/iemr/VerifiedBy.java | 7 +- .../flw/repo/iemr/IncentiveRecordRepo.java | 27 ++- .../service/impl/IncentiveServiceImpl.java | 58 +++--- .../flw/service/impl/UTPReronaPaymentJob.java | 183 ++++++++++++++++++ 6 files changed, 252 insertions(+), 38 deletions(-) create mode 100644 src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java diff --git a/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java b/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java index fef317805..2bb0eceaa 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PaymentItem.java @@ -1,7 +1,9 @@ package com.iemr.flw.dto.iemr; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +@Data public class PaymentItem { @JsonProperty("activity_code") public String activityCode; @@ -12,9 +14,5 @@ public class PaymentItem { @JsonProperty("incentive_amount") public String incentiveAmount; - public PaymentItem(String activityCode, String count, String incentiveAmount) { - this.activityCode = activityCode; - this.count = count; - this.incentiveAmount = incentiveAmount; - } + } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/iemr/Period.java b/src/main/java/com/iemr/flw/dto/iemr/Period.java index 401e849bc..049e35be0 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/Period.java +++ b/src/main/java/com/iemr/flw/dto/iemr/Period.java @@ -1,7 +1,9 @@ package com.iemr.flw.dto.iemr; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +@Data public class Period { @JsonProperty("start") public String start; @@ -12,9 +14,6 @@ public class Period { public Period() {} - public Period(String start, String end) { - this.start = start; - this.end = end; - } + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java b/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java index 1bd7ce545..e64deb39c 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java +++ b/src/main/java/com/iemr/flw/dto/iemr/VerifiedBy.java @@ -1,7 +1,9 @@ package com.iemr.flw.dto.iemr; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +@Data public class VerifiedBy { @JsonProperty("employee_id") public String employeeId; @@ -11,8 +13,5 @@ public class VerifiedBy { public VerifiedBy() {} - public VerifiedBy(String employeeId, String name) { - this.employeeId = employeeId; - this.name = name; - } + } 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 05a6bb14e..81301f3d4 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -24,7 +24,7 @@ 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); - + List findRecordsByAsha(@Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); @Query("select record from IncentiveActivityRecord record where record.ashaId = :ashaId") @@ -133,4 +132,26 @@ int updateClaimStatusByAshaAndDateRange( @Param("startDate") Timestamp startDate, @Param("endDate") Timestamp endDate ); + + @Query("SELECT DISTINCT iar.ashaId FROM IncentiveActivityRecord iar " + + "WHERE iar.calimedDate >= :startDate " + + "AND iar.calimedDate < :endDate " + + "AND iar.isClaimed = true " + + "AND iar.approvalStatus = 101") + List findDistinctAshaIdsByDateRange( + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate + ); + + @Query("SELECT iar FROM IncentiveActivityRecord iar " + + "WHERE iar.ashaId = :ashaId " + + "AND iar.calimedDate >= :startDate " + + "AND iar.calimedDate < :endDate " + + "AND iar.isClaimed = true " + + "AND iar.approvalStatus = 101") + List findClaimedApprovedRecordsByAshaAndDateRange( + @Param("ashaId") Integer ashaId, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate + ); } 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 f32f87940..d8605ddf5 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -165,7 +165,7 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { public String getAllIncentivesByUserId(GetBenRequestHandler request) { if (request.getVillageID() != StateCode.CG.getStateCode()) { - checkMonthlyAshaIncentive(request.getAshaId()); + checkMonthlyAshaIncentive(request.getUserId()); } List dtos = new ArrayList<>(); @@ -217,16 +217,25 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { if (request.getVillageID() != StateCode.CG.getStateCode()) { - checkMonthlyAshaIncentive(request.getAshaId()); + checkMonthlyAshaIncentive(request.getUserId()); } - boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); - List entities = recordRepo.findRecordsByAsha(request.getAshaId()) + // ✅ Month aur year se date range banao + LocalDate firstDay = LocalDate.of(request.getYear(), request.getMonth(), 1); + LocalDate lastDay = firstDay.plusMonths(1); + + Timestamp startTs = Timestamp.valueOf(firstDay.atStartOfDay()); + Timestamp endTs = Timestamp.valueOf(lastDay.atStartOfDay()); + + List entities = recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(e -> e.getActivityId() != null - && e.getActivityId().equals(request.getActivityId()) // ✅ pehle hi filter - && incentivesRepo.findIncentiveMasterById(e.getActivityId(), isCG) != null) + && e.getActivityId().equals(request.getActivityId()) + && incentivesRepo.findIncentiveMasterById(e.getActivityId(), isCG) != null + && e.getCreatedDate() != null + && !e.getCreatedDate().before(startTs) // ✅ >= startDate + && e.getCreatedDate().before(endTs)) // ✅ < endDate .collect(Collectors.toList()); if (entities.isEmpty()) { @@ -298,15 +307,26 @@ public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { @Override public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { - List entities = recordRepo.findRecordsByAsha(request.getAshaId()); + LocalDate firstDay = LocalDate.of(request.getYear(), request.getMonth(), 1); + LocalDate lastDay = firstDay.plusMonths(1); + + Timestamp startTs = Timestamp.valueOf(firstDay.atStartOfDay()); + Timestamp endTs = Timestamp.valueOf(lastDay.atStartOfDay()); + + boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); + + List entities = recordRepo.findRecordsByAsha(request.getUserId()) + .stream() + .filter(e -> e.getCreatedDate() != null + && !e.getCreatedDate().before(startTs) + && e.getCreatedDate().before(endTs)) + .collect(Collectors.toList()); Set activityIds = entities.stream() .filter(e -> e.getActivityId() != null) .map(IncentiveActivityRecord::getActivityId) .collect(Collectors.toSet()); - boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); - Map activityMap = incentivesRepo.findAllById(activityIds) .stream() .filter(a -> { @@ -318,7 +338,6 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { }) .collect(Collectors.toMap(IncentiveActivity::getId, a -> a)); - Map> groupedByActivity = entities.stream() .filter(e -> e.getActivityId() != null) .collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); @@ -331,27 +350,22 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { IncentiveActivity activity = activityMap.get(activityId); - + if (activity == null) continue; Long totalAmount = records.stream() .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) .sum(); - if (activity == null) { - continue; - } - - Long perActivityAmount = activity != null ? Long.valueOf(activity.getRate()) : 0L; + Long perActivityAmount = Long.valueOf(activity.getRate()); Map summary = new LinkedHashMap<>(); summary.put("activityId", activityId); - summary.put("activityDec", activity != null ? activity.getDescription() : ""); - summary.put("groupName", activity != null ? activity.getGroup() : ""); - summary.put("amount", perActivityAmount); // ✅ naya field + summary.put("activityDec", activity.getDescription() != null ? activity.getDescription() : ""); + summary.put("groupName", activity.getGroup() != null ? activity.getGroup() : ""); + summary.put("amount", perActivityAmount); summary.put("claimCount", records.size()); - summary.put("isDefaultActivity", activity != null && activity.getIsDefaultActivity() != null - ? activity.getIsDefaultActivity() - : false); + summary.put("isDefaultActivity", activity.getIsDefaultActivity() != null + ? activity.getIsDefaultActivity() : false); summary.put("totalAmount", totalAmount); summaryList.add(summary); diff --git a/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java b/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java new file mode 100644 index 000000000..c42288034 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java @@ -0,0 +1,183 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import com.iemr.flw.domain.iemr.IncentiveActivity; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.dto.iemr.PaymentItem; +import com.iemr.flw.dto.iemr.PaymentRequest; +import com.iemr.flw.dto.iemr.Period; +import com.iemr.flw.dto.iemr.VerifiedBy; +import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.IncentivesRepo; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@Component +public class UTPReronaPaymentJob { + + @Autowired + private IncentiveRecordRepo recordRepo; + + @Autowired + private IncentivesRepo incentivesRepo; + + @Autowired + private UtpreronaPaymentIntegrationImpl paymentService; + + // Runs automatically on 1st of every month at midnight + @Scheduled(cron = "0 0 0 1 * *") + public void sendMonthlyPayments() { + triggerPayment(); + } + + // ✅ Separate method — call this for immediate testing + public void triggerPayment() { + + LocalDate today = LocalDate.now(); + +// ✅ Current month ka data — testing ke liye + LocalDate firstDay = today.withDayOfMonth(1); // Mar 1, 2026 + LocalDate lastDay = today; // Mar 11, 2026 (aaj) + + String periodStart = firstDay.format(DateTimeFormatter.ISO_DATE); + String periodEnd = lastDay.format(DateTimeFormatter.ISO_DATE); + + Timestamp startTs = Timestamp.valueOf(firstDay.atStartOfDay()); // 2026-03-01 00:00:00 + Timestamp endTs = Timestamp.valueOf(lastDay.plusDays(1).atStartOfDay()); // 2026-03-12 00:00:00 + + log.info("========================================"); + log.info("UTP Rerona Payment Job Started"); + log.info("Period: {} to {}", periodStart, periodEnd); + log.info("Start Timestamp: {}", startTs); + log.info("End Timestamp: {}", endTs); + log.info("========================================"); + + List allAshaIds = recordRepo.findDistinctAshaIdsByDateRange(startTs, endTs); + log.info("Total ASHAs found: {}", allAshaIds.size()); + + int success = 0, failed = 0, skipped = 0; + + for (Integer ashaId : allAshaIds) { + try { + log.info("----------------------------------------"); + log.info("Processing ASHA ID: {}", ashaId); + + // Fetch claimed and approved records for this ASHA + List entities = recordRepo + .findClaimedApprovedRecordsByAshaAndDateRange(ashaId, startTs, endTs); + + if (entities == null || entities.isEmpty()) { + log.warn("ASHA {} — No records found, skipping", ashaId); + skipped++; + continue; + } + + log.info("ASHA {} — Total records fetched: {}", ashaId, entities.size()); + + // Collect all unique activity IDs + Set activityIds = entities.stream() + .filter(e -> e.getActivityId() != null) + .map(IncentiveActivityRecord::getActivityId) + .collect(Collectors.toSet()); + + log.info("ASHA {} — Unique activity IDs: {}", ashaId, activityIds); + + // Fetch activity master data for all activity IDs at once + Map activityMap = incentivesRepo.findAllById(activityIds) + .stream() + .filter(a -> a.getIsDeleted() == null || !a.getIsDeleted()) + .collect(Collectors.toMap(IncentiveActivity::getId, a -> a)); + + // Group records by activity ID + Map> groupedByActivity = entities.stream() + .filter(e -> e.getActivityId() != null) + .collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); + + // Build items list from grouped records + List items = new ArrayList<>(); + + for (Map.Entry> entry : groupedByActivity.entrySet()) { + Long activityId = entry.getKey(); + List records = entry.getValue(); + + IncentiveActivity activity = activityMap.get(activityId); + if (activity == null) { + log.warn("ASHA {} — Activity ID {} not found in master, skipping", ashaId, activityId); + continue; + } + + // Calculate total incentive amount for this activity + Long totalAmount = records.stream() + .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) + .sum(); + + PaymentItem item = new PaymentItem(); + item.setActivityCode(String.valueOf(activityId)); + item.setCount(String.valueOf(records.size())); + item.setIncentiveAmount(String.valueOf(totalAmount)); + items.add(item); + + log.info("ASHA {} — Activity: {} | Count: {} | Total Amount: {}", + ashaId, activityId, records.size(), totalAmount); + } + + if (items.isEmpty()) { + log.warn("ASHA {} — No valid items found, skipping", ashaId); + skipped++; + continue; + } + + // Get verified by details from first record + IncentiveActivityRecord firstRecord = entities.get(0); + VerifiedBy verifiedBy = new VerifiedBy(); + verifiedBy.setEmployeeId(firstRecord.getVerifiedByUserId() != null + ? String.valueOf(firstRecord.getVerifiedByUserId()) : ""); + verifiedBy.setName(firstRecord.getVerifiedByUserName() != null + ? firstRecord.getVerifiedByUserName() : ""); + + // Build period object + Period period = new Period(); + period.setStart(periodStart); + period.setEnd(periodEnd); + + // Build final payment request + PaymentRequest paymentRequest = new PaymentRequest( + UUID.randomUUID().toString(), + "AMRIT", + period, + ashaId.toString(), + OffsetDateTime.now().format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), + verifiedBy, + items + ); + + // Log full request before sending + log.info("ASHA {} — Request Payload: {}", ashaId, new Gson().toJson(paymentRequest)); + + // Send payment request to API + paymentService.sendPaymentRequest(paymentRequest); + + log.info("ASHA {} — Payment sent successfully", ashaId); + success++; + + } catch (Exception e) { + log.error("ASHA {} — Payment failed: {}", ashaId, e.getMessage(), e); + failed++; + } + } + + log.info("========================================"); + log.info("Job Complete | Success: {} | Failed: {} | Skipped: {}", success, failed, skipped); + log.info("========================================"); + } +} \ No newline at end of file From 6725306ba0a774ac413e81419f0e9bef65b54452 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Mar 2026 16:36:16 +0530 Subject: [PATCH 207/450] ssd portal api job --- .../dto/identity/GetBenRequestHandler.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) 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 d7251165f..d1a654ec6 100644 --- a/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java +++ b/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java @@ -14,6 +14,26 @@ public class GetBenRequestHandler { private Long activityId; + private Integer month; + + private Integer year; + + public Integer getMonth() { + return month; + } + + public void setMonth(Integer month) { + this.month = month; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + public Long getActivityId() { return activityId; } From 7adcf511880fe065b5c2c475565c93f96f436f46 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 11 Mar 2026 16:45:25 +0530 Subject: [PATCH 208/450] ssd portal api job --- .../flw/repo/iemr/IncentiveRecordRepo.java | 4 +-- .../impl/SupervisorDashboardServiceImpl.java | 30 ++++++------------- 2 files changed, 10 insertions(+), 24 deletions(-) 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 81301f3d4..fdd0009b7 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -105,10 +105,8 @@ int updateApprovalStatusByAshaAndDateRange( + "iar.approvalDate = :approvalDate, " + "iar.otherReason = :otherReason, " + "iar.verifiedByUserName = :ashaSupervisorUserName " - + "WHERE iar.id = :id " - + "AND iar.isClaimed = true") + + "WHERE iar.isClaimed = true") int updateApprovalStatusById( - @Param("id") Long id, @Param("status") Integer status, @Param("ashaSupervisorUserId") Integer ashaSupervisorUserId, @Param("ashaSupervisorUserName") String ashaSupervisorUserName, diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 69fd289de..31afefd07 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -329,33 +329,21 @@ public int updateApprovalStatus(Integer ashaId, String ashaSupervisorUsername = jwtUtil.extractUsername(token); // 👉 If Rejected → Update only selected incentive IDs - if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode()) - && incentiveIds != null - && !incentiveIds.isEmpty()) { - - String[] ids = incentiveIds.split(","); + if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { int totalUpdated = 0; - for (String idStr : ids) { - Long id = Long.parseLong(idStr.trim()); - - if (incentiveRecordRepo.existsById(id)) { - totalUpdated += incentiveRecordRepo.updateApprovalStatusById( - id, - approvalStatus, - ashaSupervisorUserId, - ashaSupervisorUsername, - reason, - approvalDate, - otherReason - ); - } - } + totalUpdated += incentiveRecordRepo.updateApprovalStatusById( + approvalStatus, + ashaSupervisorUserId, + ashaSupervisorUsername, + reason, + approvalDate, + otherReason + ); return totalUpdated; } - // 👉 Otherwise update full month data return incentiveRecordRepo.updateApprovalStatusByAshaAndDateRange( ashaId, approvalStatus, From ad6a5025f1f6856dc57f8df4baf74eac779178a7 Mon Sep 17 00:00:00 2001 From: vishwab1 Date: Thu, 12 Mar 2026 11:35:44 +0530 Subject: [PATCH 209/450] fix: generic message for sql expose --- src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java | 2 +- src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 9144ca3be..ae3f1985a 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); } } diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index fcefd7127..1bb705ed0 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -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"); } } From a4b22f6d806ea2c4dc1984624f4a6cf01ea396cf Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Thu, 12 Mar 2026 11:52:07 +0530 Subject: [PATCH 210/450] fix: generic message for sql expose (#214) --- src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java | 2 +- src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java b/src/main/java/com/iemr/flw/utils/JwtAuthenticationUtil.java index 9144ca3be..ae3f1985a 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); } } diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index fcefd7127..1bb705ed0 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -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"); } } From 114075e51b90cad2b4465d68a42a10ea38122d33 Mon Sep 17 00:00:00 2001 From: vishwab1 Date: Thu, 12 Mar 2026 12:45:01 +0530 Subject: [PATCH 211/450] fix: path traversal --- .../iemr/flw/utils/PathTraversalFilter.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/com/iemr/flw/utils/PathTraversalFilter.java 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 000000000..e63012bc0 --- /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(".."); + } +} From 506cb4fa5d4132139c43ee26c24596becd593075 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 12 Mar 2026 12:46:32 +0530 Subject: [PATCH 212/450] ssd portal api job --- .../iemr/flw/domain/iemr/IncentiveActivity.java | 3 +++ .../iemr/flw/service/impl/UTPReronaPaymentJob.java | 14 +++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) 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 e10742d54..5e44d1e6a 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java @@ -60,5 +60,8 @@ public class IncentiveActivity { @Column(name = "is_default_activity") private Boolean isDefaultActivity; + @Column(name = "state_activity_code") + private Integer stateActivityCode; + } diff --git a/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java b/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java index c42288034..c45f18e1c 100644 --- a/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java +++ b/src/main/java/com/iemr/flw/service/impl/UTPReronaPaymentJob.java @@ -121,12 +121,24 @@ public void triggerPayment() { .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) .sum(); + + String stateActivityCode = activity.getStateActivityCode() != null + ? String.valueOf(activity.getStateActivityCode()) + : null; + + if (stateActivityCode == null) { + log.warn("ASHA {} — ActivityId {} stateActivityCode null, skipping", ashaId, activityId); + continue; // ✅ Is item ko request mein add hi mat karo + } + PaymentItem item = new PaymentItem(); - item.setActivityCode(String.valueOf(activityId)); + item.setActivityCode(stateActivityCode); item.setCount(String.valueOf(records.size())); item.setIncentiveAmount(String.valueOf(totalAmount)); items.add(item); + + log.info("ASHA {} — Activity: {} | Count: {} | Total Amount: {}", ashaId, activityId, records.size(), totalAmount); } From 490676784bdcbbe96d787821421b69b53b8737fb Mon Sep 17 00:00:00 2001 From: KOPPIREDDY DURGA PRASAD <144464542+DurgaPrasad-54@users.noreply.github.com> Date: Thu, 12 Mar 2026 16:08:43 +0530 Subject: [PATCH 213/450] Cherry-pick health and version API enhancements to release-3.8.0 (#215) * feat(health,version): add health and version endpoints * fix(health): cancel in-flight futures on generic failure * fix: remove duplicate plugin and unused variable --- pom.xml | 26 + .../controller/health/HealthController.java | 83 +++ .../controller/version/VersionController.java | 80 +++ .../flw/service/health/HealthService.java | 517 ++++++++++++++++++ .../flw/utils/JwtUserIdValidationFilter.java | 4 +- 5 files changed, 709 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/iemr/flw/controller/health/HealthController.java create mode 100644 src/main/java/com/iemr/flw/controller/version/VersionController.java create mode 100644 src/main/java/com/iemr/flw/service/health/HealthService.java diff --git a/pom.xml b/pom.xml index 42245b930..f7681e6a5 100644 --- a/pom.xml +++ b/pom.xml @@ -337,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 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 000000000..933085544 --- /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 000000000..f2f2bf66f --- /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/service/health/HealthService.java b/src/main/java/com/iemr/flw/service/health/HealthService.java new file mode 100644 index 000000000..084ffe5e4 --- /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/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index 1bb705ed0..9cf022f03 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -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) { From 1655025aa72528cdb7f0d6fb52452ce07e3c8d04 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 16 Mar 2026 13:02:52 +0530 Subject: [PATCH 214/450] add new column in AshaListByFacility --- .../flw/repo/iemr/IncentiveRecordRepo.java | 12 ++++++ .../impl/SupervisorDashboardServiceImpl.java | 42 ++++++++++++------- 2 files changed, 39 insertions(+), 15 deletions(-) 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 fdd0009b7..4e699231f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -73,6 +73,18 @@ Long getTotalAmountByAsha( @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + + @Query("SELECT record " + + "FROM IncentiveActivityRecord record " + + "WHERE record.ashaId = :ashaId " + + "AND record.isClaimed = true " + + "AND record.startDate <= :toDate " + + "AND record.endDate >= :fromDate") + List getRecordsByAsha( + @Param("ashaId") Integer ashaId, + @Param("fromDate") Timestamp fromDate, + @Param("toDate") Timestamp toDate); + @Modifying @Transactional @Query("UPDATE IncentiveActivityRecord iar " diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 31afefd07..c591d60b7 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -10,10 +10,9 @@ import java.util.Map; import java.util.Set; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import com.iemr.flw.masterEnum.IncentiveApprovalStatus; -import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; -import com.iemr.flw.repo.iemr.FacilityLoginRepo; -import com.iemr.flw.repo.iemr.IncentiveRecordRepo; +import com.iemr.flw.repo.iemr.*; import com.iemr.flw.utils.JwtUtil; import org.json.JSONArray; import org.json.JSONObject; @@ -22,7 +21,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.iemr.flw.repo.iemr.SupervisorDashboardRepo; import com.iemr.flw.service.SupervisorDashboardService; import org.springframework.transaction.annotation.Transactional; @@ -46,6 +44,8 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic @Autowired private JwtUtil jwtUtil; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; @Override public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { JSONObject result = new JSONObject(); @@ -246,17 +246,29 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); + List incentiveActivityRecord = incentiveRecordRepo.getRecordsByAsha(ashaId, startDate, endDate); + for (IncentiveActivityRecord incentiveActivityRecord_ :incentiveActivityRecord){ + asha.put("facilityId", facilityID); + asha.put("facilityName", facilityName); + asha.put("facilityType", facilityType); + + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); + asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); + asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); + asha.put("reason", incentiveActivityRecord_.getReason()); + asha.put("OtherReason", incentiveActivityRecord_.getOtherReason()); + asha.put("totalAmount", totalAmount); + asha.put("role", userServiceRoleRepo.getUserRole(incentiveActivityRecord_.getVerifiedByUserId()).get(0).getRoleName()); + asha.put("approvalDate", incentiveActivityRecord_.getApprovalDate()); + asha.put("approvalStatus", incentiveActivityRecord_.getApprovalStatus()); + asha.put("verifiedByUserName", incentiveActivityRecord_.getVerifiedByUserName()); + asha.put("verifiedByUserId", incentiveActivityRecord_.getVerifiedByUserId()); + asha.put("isClaimed", incentiveActivityRecord_.getIsClaimed()); + asha.put("claimedDate", incentiveActivityRecord_.getCalimedDate()); + } - asha.put("facilityId", facilityID); - asha.put("facilityName", facilityName); - asha.put("facilityType", facilityType); - - asha.put("userId", row[0]); - asha.put("fullName", fullName(row[1], row[2])); - asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); - asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); - asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); - asha.put("totalAmount", totalAmount); long pending = 0; long verified = 0; @@ -326,7 +338,7 @@ public int updateApprovalStatus(Integer ashaId, Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); - String ashaSupervisorUsername = jwtUtil.extractUsername(token); + String ashaSupervisorUsername = "saurav"; // 👉 If Rejected → Update only selected incentive IDs if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { From 164d17c5e8e2a6598fae6d3c899746c36ec0f3c9 Mon Sep 17 00:00:00 2001 From: Vanitha S <116701245+vanitha1822@users.noreply.github.com> Date: Wed, 18 Mar 2026 17:41:53 +0530 Subject: [PATCH 215/450] Bump version from 3.7.0 to 3.8.0 (#220) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f7681e6a5..707e18a2b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.7.0 + 3.8.0 war FLW-API From c1eed26c7b9f4ce787b2586ff2621ef7240a49b2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Mar 2026 16:00:28 +0530 Subject: [PATCH 216/450] fix CBAC incentive --- .../iemr/flw/domain/iemr/CbacDetailsImer.java | 330 +++++++++++++++ .../flw/repo/identity/BeneficiaryRepo.java | 37 +- .../flw/repo/iemr/BenReferDetailsRepo.java | 6 + .../flw/repo/iemr/CbacIemrDetailsRepo.java | 44 ++ .../IncentiveActivityLangMappingRepo.java | 3 + .../flw/repo/iemr/IncentiveRecordRepo.java | 12 + .../iemr/flw/repo/iemr/IncentivesRepo.java | 18 +- .../service/impl/IncentiveServiceImpl.java | 400 +++++++++++++----- 8 files changed, 735 insertions(+), 115 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/CbacDetailsImer.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/CbacIemrDetailsRepo.java 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 000000000..989ed1d1c --- /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/repo/identity/BeneficiaryRepo.java b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java index 96301fb3c..245b32f96 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -12,6 +12,8 @@ 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 @@ -28,10 +30,15 @@ public interface BeneficiaryRepo extends JpaRepository 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); @@ -83,6 +90,24 @@ Page getBenDataWithinDates(@Param("userName") String u 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/BenReferDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java index b5277c19e..f2c915f45 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java @@ -24,11 +24,15 @@ 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 { @@ -40,4 +44,6 @@ public interface BenReferDetailsRepo extends JpaRepository findByCreatedBy(String userName); } 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 000000000..5e93dfad6 --- /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/IncentiveActivityLangMappingRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java index f98070101..4ba40dc6e 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveActivityLangMappingRepo.java @@ -3,9 +3,12 @@ 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/IncentiveRecordRepo.java b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java index 6b8db13e3..2c10f69e1 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -41,4 +41,16 @@ IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( @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 112f74ef5..5dda59003 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 { @@ -28,4 +30,18 @@ IncentiveActivity findIncentiveMasterById( @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/service/impl/IncentiveServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java index 5580e8964..e09af740c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -3,10 +3,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; -import com.iemr.flw.domain.iemr.IncentiveActivity; -import com.iemr.flw.domain.iemr.IncentiveActivityLangMapping; -import com.iemr.flw.domain.iemr.IncentiveActivityRecord; -import com.iemr.flw.domain.iemr.IncentivePendingActivity; +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; @@ -28,6 +25,8 @@ 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 @@ -59,6 +58,12 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private MaaMeetingService maaMeetingService; + @Autowired + private BenReferDetailsRepo benReferDetailsRepo; + + @Autowired + private CbacIemrDetailsRepo cbacIemrDetailsRepo; + @Override public String saveIncentivesMaster(List activityDTOS) { try { @@ -78,7 +83,7 @@ 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) { } @@ -88,183 +93,362 @@ public String saveIncentivesMaster(List activityDTOS) { @Override public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { try { + Integer stateCode = incentiveRequestDTO.getState(); + String langCode = incentiveRequestDTO.getLangCode(); - List incs = new ArrayList<>(); - if(incentiveRequestDTO.getState()==StateCode.CG.getStateCode()){ - incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); + // 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(); - }else { - incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> !incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); + // 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()); } - List dtos = incs.stream().map(inc -> { - IncentiveActivityDTO dto = modelMapper.map(inc, IncentiveActivityDTO.class); - // Fetch language mapping - IncentiveActivityLangMapping mapping = incentiveActivityLangMappingRepo - .findByIdAndName(inc.getId(),inc.getName()); + // 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()); - dto.setGroupName(mapping.getGroup()); - if(Objects.equals(incentiveRequestDTO.getLangCode(), "en")){ - dto.setDescription(inc.getDescription()); - + if (isCG) { + dto.setGroupName(""); + } else if (isAM) { + dto.setGroupName(mapping.getGroup()); + } - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "as")){ - - if(mapping.getAssameActivityDescription()!=null){ - dto.setDescription(mapping.getAssameActivityDescription()); - - }else { - dto.setDescription(mapping.getDescription()); - - } - - }else if(Objects.equals(incentiveRequestDTO.getLangCode(), "hi")){ - if(mapping.getHindiActivityDescription()!=null){ - dto.setDescription(mapping.getHindiActivityDescription()); - - }else { - dto.setDescription(mapping.getDescription()); + // 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 { + } else { dto.setGroupName(inc.getGroup()); - } return dto; }).collect(Collectors.toList()); Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(dtos); + } catch (Exception e) { - e.printStackTrace(); + logger.error("Error in getIncentiveMaster: ", e); } return null; - } @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + try { + if (request.getVillageID() != StateCode.CG.getStateCode()) { + checkMonthlyAshaIncentive(request.getAshaId()); + } + } catch (Exception e) { + logger.error("Error in checkMonthlyAshaIncentive: ", e); + } - if(request.getVillageID()!= StateCode.CG.getStateCode()){ + 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()); } - List dtos = new ArrayList<>(); + // Step 1: Fetch all records for this ASHA List entities = recordRepo.findRecordsByAsha(request.getAshaId()); - if(request.getVillageID()==StateCode.CG.getStateCode()){ - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),true)!=null).collect(Collectors.toList()); - }else { - entities = entities.stream().filter(entitie-> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(),false)!=null).collect(Collectors.toList()); + 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()); + } } - entities.forEach(entry -> { - if(entry.getName()==null){ - if(entry.getBenId()!=0 && entry.getBenId()>0L){ - Long regId = beneficiaryRepo.getBenRegIdFromBenId(entry.getBenId()); - logger.info("rmnchBeneficiaryDetailsRmnch"+regId); - BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(regId)).getBenDetailsId(); - RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); - String beneName = rmnchBeneficiaryDetails.getFirstName()+" "+rmnchBeneficiaryDetails.getLastName(); - entry.setName(beneName); - - }else{ - entry.setName(""); + // 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(""); } - } - - dtos.add(modelMapper.map(entry, IncentiveRecordDTO.class)); - - }); + 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()); + Optional incentivePendingActivity = incentivePendingActivityRepository.findByUserIdAndModuleNameAndActivityId(pendingActivityDTO.getUserId(), pendingActivityDTO.getModuleName(), pendingActivityDTO.getId()); - if(incentivePendingActivity.isPresent()){ + if (incentivePendingActivity.isPresent()) { IncentivePendingActivity existingIncentivePendingActivity = incentivePendingActivity.get(); - if(existingIncentivePendingActivity.getModuleName().equals("MAA_MEETING")){ - if(pendingActivityDTO.getImages()!=null){ + 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){ + } catch (Exception e) { return e.getMessage(); } } } } - return null; + return null; } - private void checkMonthlyAshaIncentive(Integer 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); + 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"); + IncentiveActivity ncdFollowupTreatment = activityMap.get("NCD_FOLLOWUP_TREATMENT"); + + CompletableFuture> benReferFuture = + CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); + CompletableFuture> cbacFuture = + CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); + + List benReferDetails = benReferFuture.get(); + List cbacDetailsImer = cbacFuture.get(); + + List recordsToSave = new ArrayList<>(); + + if (ncdFollowupTreatment != null && !benReferDetails.isEmpty()) { + + List benIds = benReferDetails.stream() + .map(BenReferDetails::getBeneficiaryRegID) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + Set existingKeys = recordRepo + .findExistingRecords(ncdFollowupTreatment.getId(), benIds, ashaId) + .stream() + .map(r -> r.getActivityId() + "_" + r.getBenId() + "_" + r.getCreatedDate()) + .collect(Collectors.toSet()); + + final IncentiveActivity activity = ncdFollowupTreatment; + benReferDetails.forEach(ref -> { + Long benId = ref.getBeneficiaryRegID(); + if (benId != null) { + String key = activity.getId() + "_" + benId + "_" + ref.getCreatedDate(); + if (!existingKeys.contains(key)) { + recordsToSave.add(addNCDandCBACIncentiveRecord(activity, ashaId, benId, ref.getCreatedDate(), userName)); + } + } + }); + } + + 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); } - if(ADDITIONAL_ASHA_INCENTIVE!=null){ - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE,ashaId); + } + // 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); + 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){ - 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(userRepo.getUserNamedByUserId(ashaId)); - record.setStartDate(timestamp); - record.setEndDate(timestamp); - record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(ashaId)); - record.setBenId(0L); - record.setAshaId(ashaId); - record.setAmount(Long.valueOf(incentiveActivity.getRate())); - recordRepo.save(record); + 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); + } + } From 44f9b6d4056a314034186922479f513ac7d88b2d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 19 Mar 2026 21:50:48 +0530 Subject: [PATCH 217/450] fix production issues --- .../flw/controller/IRSRoundController.java | 12 +++++-- .../flw/domain/iemr/FilariasisCampaign.java | 2 +- .../com/iemr/flw/domain/iemr/IRSRound.java | 6 ++++ .../flw/domain/iemr/ScreeningKalaAzar.java | 4 +-- .../flw/domain/iemr/ScreeningLeprosy.java | 36 +++++++++---------- .../iemr/flw/dto/iemr/DeliveryOutcomeDTO.java | 1 - .../com/iemr/flw/service/IRSRoundService.java | 2 +- .../impl/DeliveryOutcomeServiceImpl.java | 7 ++-- .../flw/service/impl/IRSRoundServiceImpl.java | 4 +-- 9 files changed, 44 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IRSRoundController.java b/src/main/java/com/iemr/flw/controller/IRSRoundController.java index 4425cdeb7..f138a0eff 100644 --- a/src/main/java/com/iemr/flw/controller/IRSRoundController.java +++ b/src/main/java/com/iemr/flw/controller/IRSRoundController.java @@ -4,6 +4,7 @@ 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; @@ -24,12 +25,19 @@ public class IRSRoundController { @Autowired private IRSRoundService irsRoundService; + @Autowired + private JwtUtil jwtUtil; + @PostMapping(value = "/add") - public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto) { + public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto,@RequestHeader("jwtToken") String token) { Map response = new LinkedHashMap<>(); try { if (dto.getRounds().size() != 0) { - List s = irsRoundService.addRounds(dto.getRounds()); + 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); diff --git a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java index b9f98ee8e..869e96961 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java +++ b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java @@ -34,7 +34,7 @@ public class FilariasisCampaign { * Store JSON array like ["img1.jpg","img2.jpg"] * MySQL JSON column */ - @Column(name = "mda_photos", columnDefinition = "json") + @Column(name = "campaign_photos", columnDefinition = "json") private String campaignPhotos; @Column(name = "created_by", length = 200) diff --git a/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java b/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java index 0f078f5f1..6f3143e05 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IRSRound.java @@ -28,4 +28,10 @@ public class IRSRound { @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/ScreeningKalaAzar.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java index eb8b0107f..d6bcd7b6c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningKalaAzar.java @@ -45,7 +45,7 @@ public class ScreeningKalaAzar { @Column(name = "house_hold_details_Id",nullable = false) private Long houseHoldDetailsId; - @Column(name = "userID") + @Column(name = "user_id") private Integer userId; @Temporal(TemporalType.DATE) @@ -97,7 +97,7 @@ public class ScreeningKalaAzar { @Column(name = "created_by") private String createdBy; - @Column(name = "diseaseTypeID") + @Column(name = "disease_type_id") private Integer diseaseTypeId; @Column(name = "refer_to_name") diff --git a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java index a943affec..6a485eef7 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ScreeningLeprosy.java @@ -83,25 +83,25 @@ public class ScreeningLeprosy { @Column(name = "beneficiary_statusId") private Integer beneficiaryStatusId; - @Column(name = "beneficiary_status", length = 50) + @Column(name = "beneficiary_status") private String beneficiaryStatus; @Column(name = "date_of_death") private Date dateOfDeath; - @Column(name = "place_of_death", length = 50) + @Column(name = "place_of_death") private String placeOfDeath; @Column(name = "other_place_of_death", columnDefinition = "TEXT") private String otherPlaceOfDeath; - @Column(name = "reason_for_death", length = 50) + @Column(name = "reason_for_death") private String reasonForDeath; @Column(name = "other_reason_for_death", columnDefinition = "TEXT") private String otherReasonForDeath; - @Column(name = "leprosy_symptoms", length = 255) + @Column(name = "leprosy_symptoms") private String leprosySymptoms; @Column(name = "leprosy_symptoms_position") @@ -113,7 +113,7 @@ public class ScreeningLeprosy { @Column(name = "current_visit_number") private Integer currentVisitNumber; - @Column(name = "visit_label", length = 50) + @Column(name = "visit_label") private String visitLabel; @Column(name = "visit_number") @@ -122,7 +122,7 @@ public class ScreeningLeprosy { @Column(name = "is_confirmed") private Boolean isConfirmed; - @Column(name = "leprosy_state", length = 50) + @Column(name = "leprosy_state", length = 255) private String leprosyState; @Temporal(TemporalType.DATE) @@ -178,40 +178,40 @@ public class ScreeningLeprosy { @Column(name = "weakness_feet_id") private Integer weaknessFeetId; - @Column(name = "recurrent_ulceration", length = 10) + @Column(name = "recurrent_ulceration") private String recurrentUlceration; - @Column(name = "recurrent_tingling", length = 10) + @Column(name = "recurrent_tingling") private String recurrentTingling; - @Column(name = "hypopigmented_patch", length = 50) + @Column(name = "hypopigmented_patch") private String hypopigmentedPatch; - @Column(name = "thickened_skin", length = 10) + @Column(name = "thickened_skin") private String thickenedSkin; - @Column(name = "skin_nodules", length = 10) + @Column(name = "skin_nodules") private String skinNodules; - @Column(name = "skin_patch_discoloration", length = 50) + @Column(name = "skin_patch_discoloration") private String skinPatchDiscoloration; - @Column(name = "recurrent_numbness", length = 10) + @Column(name = "recurrent_numbness") private String recurrentNumbness; - @Column(name = "clawing_fingers", length = 10) + @Column(name = "clawing_fingers") private String clawingFingers; - @Column(name = "tingling_numbness_extremities", length = 50) + @Column(name = "tingling_numbness_extremities") private String tinglingNumbnessExtremities; - @Column(name = "inability_close_eyelid", length = 10) + @Column(name = "inability_close_eyelid") private String inabilityCloseEyelid; - @Column(name = "difficulty_holding_objects", length = 50) + @Column(name = "difficulty_holding_objects") private String difficultyHoldingObjects; - @Column(name = "weakness_feet", length = 10) + @Column(name = "weakness_feet") private String weaknessFeet; @Column(name = "CreatedBy", length = 100) 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 941721ca1..5e94697a1 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -10,7 +10,6 @@ public class DeliveryOutcomeDTO { private Long id; private Long benId; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") private Timestamp dateOfDelivery; private String timeOfDelivery; private String placeOfDelivery; diff --git a/src/main/java/com/iemr/flw/service/IRSRoundService.java b/src/main/java/com/iemr/flw/service/IRSRoundService.java index d45cd621a..438702d5f 100644 --- a/src/main/java/com/iemr/flw/service/IRSRoundService.java +++ b/src/main/java/com/iemr/flw/service/IRSRoundService.java @@ -8,7 +8,7 @@ @Service public interface IRSRoundService { - List addRounds(List dtos); + List addRounds(List dtos,Integer userId,String userName); List getRounds(Long householdId); } 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 0e329f4bf..3ccd99736 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -108,13 +108,14 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT @Override public List getDeliveryOutcome(GetBenRequestHandler dto) { try { - String user = beneficiaryRepo.getUserName(dto.getAshaId()); - List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user, dto.getFromDate(), dto.getToDate()); + 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; } diff --git a/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java index b294a3dcb..26a5c1c74 100644 --- a/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IRSRoundServiceImpl.java @@ -17,7 +17,7 @@ public class IRSRoundServiceImpl implements IRSRoundService { private IRSRoundRepo irsRoundRepository; @Override - public List addRounds(List dtos) { + public List addRounds(List dtos,Integer userId,String userName) { // Validate input DTOs for (IRSRoundDTO dto : dtos) { if (dto.getDate() == null || dto.getHouseholdId() == null) { @@ -26,7 +26,7 @@ public List addRounds(List dtos) { } return irsRoundRepository.saveAll( dtos.stream() - .map(dto -> new IRSRound(null, dto.getDate(), dto.getRounds(), dto.getHouseholdId())) + .map(dto -> new IRSRound(null, dto.getDate(), dto.getRounds(), dto.getHouseholdId(),userName,userId)) .collect(Collectors.toList()) ); } From 8620b1a5d60a9520f2b7ad772c4fdadf9e0d2d14 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Mar 2026 11:15:49 +0530 Subject: [PATCH 218/450] fix production issues --- .../flw/controller/CampaignController.java | 12 +-- .../flw/controller/ChildCareController.java | 8 +- .../controller/DiseaseControlController.java | 4 +- .../flw/controller/GeneralOPDController.java | 2 +- .../controller/MalariaFollowUpController.java | 2 +- .../iemr/flw/domain/iemr/DeliveryOutcome.java | 1 - .../iemr/flw/domain/iemr/HbycChildVisit.java | 2 +- .../java/com/iemr/flw/dto/iemr/CdrDTO.java | 2 + .../java/com/iemr/flw/dto/iemr/HbycDTO.java | 2 +- .../java/com/iemr/flw/dto/iemr/MdsrDTO.java | 6 ++ .../iemr/flw/dto/iemr/PendingActivityDTO.java | 3 +- .../com/iemr/flw/dto/iemr/TBScreeningDTO.java | 93 +----------------- .../com/iemr/flw/masterEnum/GroupName.java | 3 + .../iemr/flw/service/UwinSessionService.java | 1 + .../flw/service/impl/CampaignServiceImpl.java | 94 +++++++++++++++++-- .../service/impl/UwinSessionServiceImpl.java | 18 +++- 16 files changed, 133 insertions(+), 120 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/CampaignController.java b/src/main/java/com/iemr/flw/controller/CampaignController.java index 93a19afdb..f5f13d698 100644 --- a/src/main/java/com/iemr/flw/controller/CampaignController.java +++ b/src/main/java/com/iemr/flw/controller/CampaignController.java @@ -123,9 +123,9 @@ public ResponseEntity> getAllOrsDistribution(@RequestHeader( response.put("data", result); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { @@ -233,9 +233,9 @@ public ResponseEntity> getAllPolioCampaign(@RequestHeader(va response.put("data", result); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { @@ -345,9 +345,9 @@ public ResponseEntity> getAllFilariasisCampaign(@RequestHead response.put("data", result); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index e1e2c91fe..36da3ba72 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -272,9 +272,9 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); response.put("message", "No SAM records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { @@ -331,9 +331,9 @@ public ResponseEntity getAllOrDistribution(@RequestBody GetBenRequestHandler response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); response.put("message", "No ORS records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index e89a53067..2464b5e57 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -63,12 +63,12 @@ public ResponseEntity> saveMalaria(@RequestBody MalariaDTO m response.put("data", diseaseControlService.saveMalaria(malariaDTO)); }else { response.put("message", "Invalid request"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); diff --git a/src/main/java/com/iemr/flw/controller/GeneralOPDController.java b/src/main/java/com/iemr/flw/controller/GeneralOPDController.java index 5e7823df3..c683a9be5 100644 --- a/src/main/java/com/iemr/flw/controller/GeneralOPDController.java +++ b/src/main/java/com/iemr/flw/controller/GeneralOPDController.java @@ -77,7 +77,7 @@ public ResponseEntity> getBeneficiaryDataByAsha(@RequestBody } catch (Exception e) { logger.error("Error in get data : " + e); - response.put("status", 500); + response.put("statusCode", 5000); response.put("message", "Error in get data : " + e); } return ResponseEntity.ok(response); diff --git a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java index 4e3ae1942..230ad5918 100644 --- a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java +++ b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java @@ -78,7 +78,7 @@ public ResponseEntity> getFollowUpsByUserId(@RequestBody Get } } catch (Exception e) { response.put("status", "Error: " + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); 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 6050fab57..2b94cc7a0 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java @@ -17,7 +17,6 @@ public class DeliveryOutcome { @Column(name = "ben_id") private Long benId; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") @Column(name = "delivery_date") private Timestamp dateOfDelivery; diff --git a/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java b/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java index bcaeabc49..205716cc9 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java +++ b/src/main/java/com/iemr/flw/domain/iemr/HbycChildVisit.java @@ -53,7 +53,7 @@ public class HbycChildVisit { private String other_place_of_death; @Column(name = "baby_weight") - private BigDecimal baby_weight; // 0.5 - 7.0 + private Integer baby_weight; // 0.5 - 7.0 @Column(name = "is_child_sick") private Boolean is_child_sick; 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 122f652d8..ed1dc34ee 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java @@ -55,6 +55,8 @@ public class CdrDTO { private String deathCertImage2; + private String cdrImage; + private Timestamp updatedDate; private String updatedBy; 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 acc54ca89..172132e07 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/HbycDTO.java @@ -47,7 +47,7 @@ public class HbycDTO { private String other_place_of_death; @SerializedName("baby_weight") - private BigDecimal baby_weight; + private Integer baby_weight; @SerializedName("is_child_sick") private String is_child_sick; 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 5b07e40a3..e59047aba 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/PendingActivityDTO.java b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java index 4d8dbd99e..5fcdd5375 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/PendingActivityDTO.java @@ -9,6 +9,7 @@ public class PendingActivityDTO { private Long id; private Integer userId; - private List Images; + private List images; private String moduleName; + private String activityName; } 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 017d73af2..36f48dfc5 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBScreeningDTO.java @@ -37,98 +37,7 @@ public class TBScreeningDTO { private Boolean bmi; private Boolean contactWithTBPatient; private Boolean historyOfTBInLastFiveYrs; - private String sympotomatic; + private String sympotomatic; private String asymptomatic; private String recommandateTest; - - - - - 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; - } } diff --git a/src/main/java/com/iemr/flw/masterEnum/GroupName.java b/src/main/java/com/iemr/flw/masterEnum/GroupName.java index 8d6736eb3..e53733b02 100644 --- a/src/main/java/com/iemr/flw/masterEnum/GroupName.java +++ b/src/main/java/com/iemr/flw/masterEnum/GroupName.java @@ -33,3 +33,6 @@ public String getDisplayName() { } + + + diff --git a/src/main/java/com/iemr/flw/service/UwinSessionService.java b/src/main/java/com/iemr/flw/service/UwinSessionService.java index 3f6ddf0ac..0756de831 100644 --- a/src/main/java/com/iemr/flw/service/UwinSessionService.java +++ b/src/main/java/com/iemr/flw/service/UwinSessionService.java @@ -1,5 +1,6 @@ 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; diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index d989df6c7..55756130d 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -3,13 +3,10 @@ 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.CampaignOrs; -import com.iemr.flw.domain.iemr.FilariasisCampaign; -import com.iemr.flw.domain.iemr.PulsePolioCampaign; +import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.iemr.*; -import com.iemr.flw.repo.iemr.FilariasisCampaignRepo; -import com.iemr.flw.repo.iemr.OrsCampaignRepo; -import com.iemr.flw.repo.iemr.PulsePolioCampaignRepo; +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; @@ -22,6 +19,9 @@ 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; @@ -42,8 +42,18 @@ public class CampaignServiceImpl implements CampaignService { @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 { @@ -91,6 +101,9 @@ public List saveOrsCampaign(List orsCampaignDTO, St if (!campaignOrsRequest.isEmpty()) { List savedCampaigns = orsCampaignRepo.saveAll(campaignOrsRequest); + savedCampaigns.forEach(ors->{ + checkMonthlyPulseOrsDistribution(ors.getUserId(),ors.getStartDate(),ors.getEndDate()); + }); return savedCampaigns; } @@ -177,6 +190,12 @@ public List savePolioCampaign(List polioCa if (!campaignPolioRequest.isEmpty()) { List savedCampaigns = pulsePolioCampaignRepo.saveAll(campaignPolioRequest); + savedCampaigns.forEach(pulsePolioCampaign -> { + checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + + });{ + + } return savedCampaigns; } @@ -255,6 +274,13 @@ public List saveFilariasisCampaign(List savedCampaigns = filariasisCampaignRepo.saveAll(campaignPolioRequest); + + savedCampaigns.forEach(filariasisCampaign -> { + checkMonthlyFilariasisIncentive(filariasisCampaign.getUserId(),filariasisCampaign.getStartDate(),filariasisCampaign.getEndDate()); + + });{ + + } return savedCampaigns; } @@ -262,6 +288,7 @@ public List saveFilariasisCampaign(List getPolioCampaign(String token) throws IEMRException { Integer userId = jwtUtil.extractUserId(token); @@ -329,6 +356,7 @@ private OrsCampaignResponseDTO convertOrsToDTO(CampaignOrs campaign) { orsCampaignListDTO.setNumberOfFamilies(Double.valueOf(campaign.getNumberOfFamilies())); dto.setId(campaign.getId()); dto.setFields(orsCampaignListDTO); + return dto; } @@ -402,7 +430,61 @@ private List parseBase64Json(String jsonString) { } } + 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/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index bb2a944c9..63dc00dd2 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -8,6 +8,7 @@ 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; @@ -130,9 +131,9 @@ public List getSessionsByAsha(Integer ashaId) throws Exc 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){ + if(incentiveActivityAM!=null && stateId!=null && stateId.equals(StateCode.AM.getStateCode())){ IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(), session.getDate(), 0L,session.getAshaId()); if (record == null) { @@ -147,11 +148,19 @@ record = new IncentiveActivityRecord(); record.setBenId(0L); record.setAshaId(session.getAshaId()); record.setAmount(Long.valueOf(incentiveActivityAM.getRate())); - recordRepo.save(record); + if(session.getAttachmentsJson()!=null){ + record.setIsEligible(true); + recordRepo.save(record); + + }else { + record.setIsEligible(false); + + } + } } - if(incentiveActivityCH!=null){ + if(incentiveActivityCH!=null && stateId!=null && stateId.equals(StateCode.CG.getStateCode())){ IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(incentiveActivityCH.getId(), session.getDate(), 0L,session.getAshaId()); if (record == null) { @@ -166,6 +175,7 @@ record = new IncentiveActivityRecord(); record.setBenId(0L); record.setAshaId(session.getAshaId()); record.setAmount(Long.valueOf(incentiveActivityCH.getRate())); + record.setIsEligible(true); recordRepo.save(record); } } From e4c9012e075a92d9fb6d7339136973c97f5a303f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Mar 2026 12:36:23 +0530 Subject: [PATCH 219/450] fix status code in disease module --- .../controller/DiseaseControlController.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 2464b5e57..816fb244f 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -86,12 +86,12 @@ public ResponseEntity> saveKalaAzar(@RequestBody KalaAzarDTO response.put("data", diseaseControlService.saveKalaAzar(kalaAzarDTO)); }else { response.put("message", "Invalid request"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); @@ -108,12 +108,12 @@ public ResponseEntity> saveAESJE(@RequestBody AesJeDTO aesJe response.put("data", diseaseControlService.saveAES(aesJeDTO)); }else { response.put("message", "Invalid request"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); @@ -130,12 +130,12 @@ public ResponseEntity> saveFilaria(@RequestBody FilariaDTO f response.put("data", diseaseControlService.saveFilaria(filariaDTO)); }else { response.put("message", "Invalid request"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); @@ -151,12 +151,12 @@ public ResponseEntity> saveLeprosy(@RequestBody LeprosyDTO l response.put("data", diseaseControlService.saveLeprosy(leprosyDTO)); }else { response.put("message", "Invalid request"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); @@ -175,11 +175,11 @@ public ResponseEntity> saveLeprosyFollowUP(@RequestBody List response.put("message", "All follow-ups saved successfully"); } else { response.put("message", "Invalid request - no follow-up data"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error: " + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); @@ -203,15 +203,15 @@ public ResponseEntity> getAllLeprosy( response.put("data", result); // ← Put list directly, no gson.toJson() } else { response.put("message", "No record found"); - response.put("statusCode", 404); + response.put("statusCode", 5000); } } else { response.put("message", "Invalid request - userName required"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error: " + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); // ← Spring serializes the whole map } @@ -233,15 +233,15 @@ public ResponseEntity> getAllLeprosyFollowUp( response.put("data", result); // ← Put list directly, no gson.toJson() } else { response.put("message", "No record found"); - response.put("statusCode", 404); + response.put("statusCode", 5000); } } else { response.put("message", "Invalid request - userName required"); - response.put("statusCode", 400); + response.put("statusCode", 5000); } } catch (Exception e) { response.put("status", "Error: " + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); // ← Spring serializes the whole map } @@ -257,7 +257,7 @@ public ResponseEntity> getAllData( } catch (Exception e) { response.put("status", "Error" + e.getMessage()); - response.put("statusCode", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); } From dac1e99c725fe9c2748bb97c73500ce20d02a6ab Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Mar 2026 13:43:32 +0530 Subject: [PATCH 220/450] fix status code in disease module --- .../com/iemr/flw/controller/BeneficiaryController.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index dd083840d..82b4cf7bf 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -91,7 +91,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List } catch (Exception e) { logger.error("Error saving eye checkup visit:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -112,14 +112,14 @@ public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler requ response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.NOT_FOUND.value()); + response.put("statusCode", 5000); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } } catch (Exception e) { logger.error("Error fetching eye checkup visit:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } From ffe7d46ab2ea815776dda02aab43e9c19647f5a9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 20 Mar 2026 16:31:57 +0530 Subject: [PATCH 221/450] fix session_date issue --- src/main/java/com/iemr/flw/domain/iemr/UwinSession.java | 3 +++ .../java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java | 1 + 2 files changed, 4 insertions(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java b/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java index f995a71dc..9ab6d5cb3 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java +++ b/src/main/java/com/iemr/flw/domain/iemr/UwinSession.java @@ -23,6 +23,9 @@ public class UwinSession { @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; diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index 63dc00dd2..156de1d84 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -73,6 +73,7 @@ public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exce 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) { From 6e4aa7cefc50a1b1e763bf0f9f30887f8eb23477 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 23 Mar 2026 19:48:09 +0530 Subject: [PATCH 222/450] fix DeliveryOutcome date formate issue --- src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java | 1 - .../java/com/iemr/flw/domain/iemr/FilariasisCampaign.java | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) 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 2b94cc7a0..d3a1b56ce 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java +++ b/src/main/java/com/iemr/flw/domain/iemr/DeliveryOutcome.java @@ -53,7 +53,6 @@ public class DeliveryOutcome { @Column(name = "still_birth") private Integer stillBirth; - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MMM dd, yyyy, h:mm:ss a") @Column(name = "discharge_date") private Timestamp dateOfDischarge; diff --git a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java index 869e96961..7e0916bdf 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java +++ b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java @@ -24,10 +24,10 @@ public class FilariasisCampaign { @Column(name = "user_id", nullable = false) private Integer userId; - @Column(name = "no_of_families", nullable = false) + @Column(name = "number_of_families", nullable = false) private Integer numberOfFamilies = 0; - @Column(name = "no_of_individuals", nullable = false) + @Column(name = "number_of_individuals", nullable = false) private Integer numberOfIndividuals = 0; /** From 28d77893faeeeeb6fced5bdd2c4cdd9344782987 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Mar 2026 11:31:35 +0530 Subject: [PATCH 223/450] fix DiseaseControl userId issue --- .../iemr/flw/controller/MicroBirthPlanController.java | 2 +- .../flw/service/impl/DiseaseControlServiceImpl.java | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java index c501b4054..c5cb04aa0 100644 --- a/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java +++ b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java @@ -55,7 +55,7 @@ public ResponseEntity> createMicroBirthPlan(@RequestBody Mic } - @RequestMapping(value = "getAll", method = RequestMethod.GET) + @RequestMapping(value = "getAll", method = RequestMethod.POST) public ResponseEntity> getAllMicroBirthPlans(@RequestParam("userId") Integer userId) { Map response = new HashMap<>(); diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index d5f009eaf..1abf70f30 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -397,7 +397,7 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Fetch and filter malaria disease records List filteredList = diseaseMalariaRepository.findAll().stream() - .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getUserId())) + .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId())) .collect(Collectors.toList()); // Check if the list is empty @@ -485,7 +485,7 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) // Fetch and filter Kala Azar disease records List filteredList = diseaseKalaAzarRepository.findAll().stream() - .filter(disease -> (Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getUserId()))) + .filter(disease -> (Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId()))) .collect(Collectors.toList()); // Check if the list is empty @@ -532,14 +532,14 @@ public Object getAllKalaAES(GetDiseaseRequestHandler getDiseaseRequestHandler) { return Collections.singletonMap("message", "No data found for AES."); } - return diseaseAESJERepository.findAll().stream().filter(diseaseAesje -> Objects.equals(diseaseAesje.getUserId(), getDiseaseRequestHandler.getUserId())).collect(Collectors.toList()); + 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.getUserId())).collect(Collectors.toList()); + 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()) { @@ -575,7 +575,7 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { // Fetch and filter Leprosy disease records List filteredList = diseaseLeprosyRepository.findAll().stream() - .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getUserId())) + .filter(disease -> Objects.equals(disease.getUserId(), getDiseaseRequestHandler.getAshaId())) .collect(Collectors.toList()); // Check if the list is empty From 71ae19741a6bc9a42b9c4b23974bb203d2c218a5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Mar 2026 11:33:19 +0530 Subject: [PATCH 224/450] fix DiseaseControl userId issue --- .../java/com/iemr/flw/controller/MicroBirthPlanController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java index c5cb04aa0..c501b4054 100644 --- a/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java +++ b/src/main/java/com/iemr/flw/controller/MicroBirthPlanController.java @@ -55,7 +55,7 @@ public ResponseEntity> createMicroBirthPlan(@RequestBody Mic } - @RequestMapping(value = "getAll", method = RequestMethod.POST) + @RequestMapping(value = "getAll", method = RequestMethod.GET) public ResponseEntity> getAllMicroBirthPlans(@RequestParam("userId") Integer userId) { Map response = new HashMap<>(); From 847e810818e23f9e7bd0b996f38189bb86fd88c2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 24 Mar 2026 15:33:48 +0530 Subject: [PATCH 225/450] fix DiseaseControl userId issue --- .../flw/service/impl/CampaignServiceImpl.java | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 55756130d..620ae6c62 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -231,8 +231,13 @@ public List saveFilariasisCampaign(List Date: Tue, 24 Mar 2026 16:37:14 +0530 Subject: [PATCH 226/450] fix eye checkup get list issue --- .../com/iemr/flw/controller/BeneficiaryController.java | 8 ++++---- .../java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java | 1 + .../java/com/iemr/flw/service/BeneficiaryService.java | 4 ++-- .../iemr/flw/service/impl/BeneficiaryServiceImpl.java | 9 +++++---- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index 82b4cf7bf..d7921ff07 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -66,7 +66,7 @@ public String getBeneficiaryDataByAsha(@RequestBody GetBenRequestHandler request } @RequestMapping(value = {"/eye_surgery/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveEyeSurgery(@RequestBody List eyeCheckupRequestDTOS) { + public ResponseEntity saveEyeSurgery(@RequestBody List eyeCheckupRequestDTOS,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("Eye Checkup Save Request: {}", eyeCheckupRequestDTOS); @@ -77,7 +77,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); } - String responseObject = beneficiaryService.saveEyeCheckupVsit(eyeCheckupRequestDTOS); + String responseObject = beneficiaryService.saveEyeCheckupVsit(eyeCheckupRequestDTOS,token); if (responseObject != null) { response.put("statusCode", HttpStatus.OK.value()); @@ -100,12 +100,12 @@ public ResponseEntity saveEyeSurgery(@RequestBody List @RequestMapping(value = {"/eye_surgery/getAll"}, method = RequestMethod.POST) - public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler request) { + 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); + List responseObject = beneficiaryService.getEyeCheckUpVisit(request,token); if (responseObject != null && !responseObject.isEmpty()) { response.put("statusCode", HttpStatus.OK.value()); diff --git a/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java index c0e3df739..fd713c445 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EyeCheckUpVisitRepo.java @@ -10,4 +10,5 @@ public interface EyeCheckUpVisitRepo extends JpaRepository { List findByUserId(Integer userId); + List findByCreatedBy(String userName); } diff --git a/src/main/java/com/iemr/flw/service/BeneficiaryService.java b/src/main/java/com/iemr/flw/service/BeneficiaryService.java index 1db3026b9..e69bc887f 100644 --- a/src/main/java/com/iemr/flw/service/BeneficiaryService.java +++ b/src/main/java/com/iemr/flw/service/BeneficiaryService.java @@ -10,7 +10,7 @@ public interface BeneficiaryService { String getBenData(GetBenRequestHandler requestDTO, String authorisation) throws Exception; - String saveEyeCheckupVsit(List eyeCheckupRequestDTOS); + String saveEyeCheckupVsit(List eyeCheckupRequestDTOS,String token); - List getEyeCheckUpVisit(GetBenRequestHandler request); + List getEyeCheckUpVisit(GetBenRequestHandler request,String token); } 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 f5a757854..9d60729db 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -521,7 +521,7 @@ public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map eyeCheckupRequestDTOS) { + public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS,String token) { try { for (EyeCheckupRequestDTO dto : eyeCheckupRequestDTOS) { @@ -529,7 +529,7 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO visit.setBeneficiaryId(dto.getBeneficiaryId()); visit.setHouseholdId(dto.getHouseHoldId()); - visit.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); // cache se lena hai + visit.setUserId(jwtUtil.extractUserId(token)); visit.setCreatedBy(dto.getUserName()); StringBuilder sb = new StringBuilder(); @@ -558,8 +558,9 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO } @Override - public List getEyeCheckUpVisit(GetBenRequestHandler request) { - List visits = eyeCheckUpVisitRepo.findByUserId(request.getAshaId()); + public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { + + List visits = eyeCheckUpVisitRepo.findByCreatedBy(jwtUtil.extractUsername(token)); return visits.stream().map(v -> { EyeCheckupRequestDTO dto = new EyeCheckupRequestDTO(); From 6ff151c5b019000823b35793dd4ca744b7e006d3 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Mar 2026 17:32:17 +0530 Subject: [PATCH 227/450] fix ncd followup incentive issue --- .../controller/MalariaFollowUpController.java | 45 ++++++++------ .../flw/service/MalariaFollowUpService.java | 2 +- .../service/impl/DeathReportsServiceImpl.java | 9 ++- .../impl/DiseaseControlServiceImpl.java | 59 ++++++++++++++++++- .../impl/MalariaFollowUpServiceImpl.java | 53 +++++++++++------ 5 files changed, 129 insertions(+), 39 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java index 230ad5918..c2b421d6f 100644 --- a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java +++ b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java @@ -28,6 +28,7 @@ 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.*; @@ -40,42 +41,52 @@ @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) { + public ResponseEntity> save(@RequestBody MalariaFollowUpDTO dto,@RequestHeader(value = "JwtToken") String token) { Map response = new HashMap<>(); try { - Boolean result = followUpService.saveFollowUp(dto); - 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", 400); + 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", 500); + response.put("statusCode", 5000); } return ResponseEntity.ok(response); } @RequestMapping(value = "get", method = RequestMethod.POST) - public ResponseEntity> getFollowUpsByUserId(@RequestBody GetDiseaseRequestHandler getDiseaseRequestHandler) { + public ResponseEntity> getFollowUpsByUserId(@RequestBody GetDiseaseRequestHandler getDiseaseRequestHandler,@RequestHeader(value = "JwtToken") String token) { Map response = new HashMap<>(); try { - List data = followUpService.getByUserId(getDiseaseRequestHandler.getUserId()); - response.put("status", "Success"); - response.put("statusCode", 200); - response.put("data", data); - if (data.isEmpty()) { - response.put("message", "No records found"); + 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); diff --git a/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java b/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java index eb979318d..324c6cd6a 100644 --- a/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java +++ b/src/main/java/com/iemr/flw/service/MalariaFollowUpService.java @@ -9,7 +9,7 @@ public interface MalariaFollowUpService { - public Boolean saveFollowUp(MalariaFollowUpDTO dto) ; + public Boolean saveFollowUp(MalariaFollowUpDTO dto,String token) ; List getByUserId(Integer userId); 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 82cee5d06..684a03b2d 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -139,7 +139,10 @@ private void checkAndAddIncentives(List cdrList) { Integer userId = userRepo.getUserIdByName(cdr.getCreatedBy()); IncentiveActivity immunizationActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); - createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); + if(immunizationActivity!=null){ + createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); + + } }); } @@ -151,8 +154,10 @@ private void checkAndAddIncentivesMdsr(List mdsrList) { 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); - createIncentiveRecord(mdsr,mdsr.getBenId(),userId,immunizationActivity); + } }); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 1abf70f30..78be64eca 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -30,6 +30,7 @@ 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; @@ -1096,11 +1097,68 @@ public List saveChronicDiseaseVisit( 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()); + if (chronicDiseaseVisitEntity.getFollowUpNo() != null + && chronicDiseaseVisitEntity.getFollowUpDate() != 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())) { + + LocalDate localDate = chronicDiseaseVisitEntity.getFollowUpDate(); + Timestamp followUpTimestamp = Timestamp.valueOf(localDate.atStartOfDay()); + + addNCDFolloupIncentiveRecord( + incentiveActivity, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } + } + + + } + private IncentiveActivityRecord addNCDFolloupIncentiveRecord(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; + } @Override public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { @@ -1131,7 +1189,6 @@ public List getCdtfVisits(GetBenRequestHandler getBenReq dtoList.add(dto); } - return dtoList; } diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index 175c3666e..3b6779bc0 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -1,10 +1,16 @@ 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; @@ -19,30 +25,41 @@ public class MalariaFollowUpServiceImpl implements MalariaFollowUpService { @Autowired private MalariaFollowUpRepository repository; - public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO) { + private final Logger logger = LoggerFactory.getLogger(MalariaFollowUpServiceImpl.class); - for(MalariaFollowListUpDTO dto : malariaFollowUpDTO.getMalariaFollowListUp()){ - if (dto.getTreatmentStartDate().after(new Date())) { - return false; - } + @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.getTreatmentCompletionDate() != null && - dto.getTreatmentCompletionDate().before(dto.getTreatmentStartDate())) { - return false; - } + if (dto.getReferralDate() != null && + dto.getReferralDate().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; + } - MalariaFollowUp entity = new MalariaFollowUp(); - BeanUtils.copyProperties(dto, entity); - repository.save(entity); - return true; - } return false; } From 2236b7944fc3dd0593362530b8a29f41819d4357 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Mar 2026 17:48:50 +0530 Subject: [PATCH 228/450] fix ncd followup incentive issue --- .../impl/DiseaseControlServiceImpl.java | 100 ++++++++++-------- .../service/impl/IncentiveServiceImpl.java | 25 ----- 2 files changed, 57 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 78be64eca..05979215d 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1107,57 +1107,71 @@ public List saveChronicDiseaseVisit( private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity,Integer ashaId){ String userName = userRepo.getUserNamedByUserId(ashaId); IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); - if (chronicDiseaseVisitEntity.getFollowUpNo() != null - && chronicDiseaseVisitEntity.getFollowUpDate() != 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())) { - - LocalDate localDate = chronicDiseaseVisitEntity.getFollowUpDate(); - Timestamp followUpTimestamp = Timestamp.valueOf(localDate.atStartOfDay()); - - addNCDFolloupIncentiveRecord( - incentiveActivity, - ashaId, - chronicDiseaseVisitEntity.getBenId(), - followUpTimestamp, - userName + if(incentiveActivity!=null){ + if (chronicDiseaseVisitEntity.getFollowUpNo() != null + && chronicDiseaseVisitEntity.getFollowUpDate() != 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())) { + + LocalDate localDate = chronicDiseaseVisitEntity.getFollowUpDate(); + Timestamp followUpTimestamp = Timestamp.valueOf(localDate.atStartOfDay()); + + addNCDFolloupIncentiveRecord( + incentiveActivity, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } } } + } - private IncentiveActivityRecord addNCDFolloupIncentiveRecord(IncentiveActivity activity, Integer ashaId, + private void addNCDFolloupIncentiveRecord(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; + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), createdDate, benId); + + Timestamp now = Timestamp.valueOf(LocalDateTime.now()); + if(record==null){ + 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())); + record .setIsEligible(true); + recordRepo.save(record); + } + }catch (Exception e){ + logger.error("Fail to save IncentiveActivityRecord " + e.getMessage()); + } + + } @Override public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { 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 e09af740c..09523a4b3 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -290,42 +290,17 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); - IncentiveActivity ncdFollowupTreatment = activityMap.get("NCD_FOLLOWUP_TREATMENT"); CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); CompletableFuture> cbacFuture = CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); - List benReferDetails = benReferFuture.get(); List cbacDetailsImer = cbacFuture.get(); List recordsToSave = new ArrayList<>(); - if (ncdFollowupTreatment != null && !benReferDetails.isEmpty()) { - List benIds = benReferDetails.stream() - .map(BenReferDetails::getBeneficiaryRegID) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - Set existingKeys = recordRepo - .findExistingRecords(ncdFollowupTreatment.getId(), benIds, ashaId) - .stream() - .map(r -> r.getActivityId() + "_" + r.getBenId() + "_" + r.getCreatedDate()) - .collect(Collectors.toSet()); - - final IncentiveActivity activity = ncdFollowupTreatment; - benReferDetails.forEach(ref -> { - Long benId = ref.getBeneficiaryRegID(); - if (benId != null) { - String key = activity.getId() + "_" + benId + "_" + ref.getCreatedDate(); - if (!existingKeys.contains(key)) { - recordsToSave.add(addNCDandCBACIncentiveRecord(activity, ashaId, benId, ref.getCreatedDate(), userName)); - } - } - }); - } if (ncdPopEnumeration != null && !cbacDetailsImer.isEmpty()) { List cbacBenIds = cbacDetailsImer.stream() From c4bdf91ca5938703a639cff7f8f6f0d7d8d9e514 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Mar 2026 19:16:06 +0530 Subject: [PATCH 229/450] fix ncd followup incentive issue --- .../impl/DiseaseControlServiceImpl.java | 85 ++++++++++++++++++- 1 file changed, 81 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 1abf70f30..a3436b906 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -30,6 +30,7 @@ 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; @@ -1077,7 +1078,10 @@ public List saveChronicDiseaseVisit( entity.setVersion(dto.getVersion()); entity.setVisitNo(dto.getVisitNo()); entity.setFollowUpNo(dto.getFollowUpNo()); - entity.setFollowUpDate(dto.getFollowUpDate()); + if(dto.getFollowUpDate()!=null){ + entity.setFollowUpDate(dto.getFollowUpDate()); + + } entity.setDiagnosisCodes(dto.getDiagnosisCodes()); entity.setFormDataJson(dto.getFormDataJson()); entity.setUserID(jwtUtil.extractUserId(token)); @@ -1096,11 +1100,82 @@ public List saveChronicDiseaseVisit( 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()); + 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 activity, Integer ashaId, + Long benId, Timestamp createdDate, String userName) { + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), createdDate, benId); + + Timestamp now = Timestamp.valueOf(LocalDateTime.now()); + if(record==null){ + 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())); + record .setIsEligible(true); + recordRepo.save(record); + } + }catch (Exception e){ + logger.error("Fail to save IncentiveActivityRecord " + e.getMessage()); + } + + + } @Override public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { @@ -1119,7 +1194,10 @@ public List getCdtfVisits(GetBenRequestHandler getBenReq dto.setVersion(entity.getVersion()); dto.setVisitNo(entity.getVisitNo()); dto.setFollowUpNo(entity.getFollowUpNo()); - dto.setFollowUpDate(entity.getFollowUpDate()); + if(entity.getFollowUpDate()!=null){ + dto.setFollowUpDate(entity.getFollowUpDate()); + + } dto.setDiagnosisCodes(entity.getDiagnosisCodes()); dto.setFormDataJson(entity.getFormDataJson()); @@ -1128,10 +1206,9 @@ public List getCdtfVisits(GetBenRequestHandler getBenReq entity.getTreatmentStartDate().toString() ); } - + checkIncentive(entity,entity.getUserID()); dtoList.add(dto); } - return dtoList; } From b4e3f2f2466c9ab0c61128262d5cf562f6a7a66e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Mar 2026 20:18:41 +0530 Subject: [PATCH 230/450] fix follow up date issue --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index a3436b906..5f261dd91 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1129,7 +1129,7 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, .map(String::trim) .anyMatch(targetDiseases::contains); - if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { + if (matchFound) { LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); From 35fdc5424bf15b7f073dc324a81b2e57d9e38613 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 25 Mar 2026 20:51:12 +0530 Subject: [PATCH 231/450] fix follow up date issue --- .../impl/DiseaseControlServiceImpl.java | 66 +++++++++++-------- 1 file changed, 37 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 5f261dd91..b005f2d66 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1110,6 +1110,7 @@ public List saveChronicDiseaseVisit( 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 @@ -1129,7 +1130,7 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, .map(String::trim) .anyMatch(targetDiseases::contains); - if (matchFound) { + if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); @@ -1149,15 +1150,16 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, } - private void addNCDFolloupIncentiveRecord(IncentiveActivity activity, Integer ashaId, + private void addNCDFolloupIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId, Long benId, Timestamp createdDate, String userName) { try { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(activity.getId(), createdDate, benId); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), createdDate, benId); Timestamp now = Timestamp.valueOf(LocalDateTime.now()); if(record==null){ - record.setActivityId(activity.getId()); + record = new IncentiveActivityRecord(); + record.setActivityId(incentiveActivity.getId()); record.setCreatedDate(createdDate); record.setCreatedBy(userName); record.setStartDate(createdDate); @@ -1166,7 +1168,7 @@ private void addNCDFolloupIncentiveRecord(IncentiveActivity activity, Integer as record.setUpdatedBy(userName); record.setBenId(benId); record.setAshaId(ashaId); - record.setAmount(Long.valueOf(activity.getRate())); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); record .setIsEligible(true); recordRepo.save(record); } @@ -1178,37 +1180,43 @@ record .setIsEligible(true); } @Override public List getCdtfVisits(GetBenRequestHandler getBenRequestHandler) { + List dtoList = new ArrayList<>(); - List entityList = chronicDiseaseVisitRepository.findByUserID(getBenRequestHandler.getAshaId()); + try { - List dtoList = new ArrayList<>(); + List entityList = chronicDiseaseVisitRepository.findByUserID(getBenRequestHandler.getAshaId()); - for (ChronicDiseaseVisitEntity entity : entityList) { - ChronicDiseaseVisitDTO dto = new ChronicDiseaseVisitDTO(); + for (ChronicDiseaseVisitEntity entity : entityList) { - 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()); + ChronicDiseaseVisitDTO dto = new ChronicDiseaseVisitDTO(); - } - dto.setDiagnosisCodes(entity.getDiagnosisCodes()); - dto.setFormDataJson(entity.getFormDataJson()); + 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){ + + } - if (entity.getTreatmentStartDate() != null) { - dto.setTreatmentStartDate( - entity.getTreatmentStartDate().toString() - ); - } - checkIncentive(entity,entity.getUserID()); - dtoList.add(dto); - } return dtoList; } From 8798c3c86249111518e84e36656922203a2a9ab6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Mar 2026 16:46:07 +0530 Subject: [PATCH 232/450] fix merge issue --- pom.xml | 2 +- .../java/com/iemr/flw/dto/iemr/CdrDTO.java | 1 - .../flw/repo/iemr/IncentiveRecordRepo.java | 1 + .../iemr/flw/repo/iemr/IncentivesRepo.java | 2 +- .../service/impl/IncentiveServiceImpl.java | 984 ++++-------------- 5 files changed, 230 insertions(+), 760 deletions(-) diff --git a/pom.xml b/pom.xml index 707e18a2b..e6e92ee2f 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.8.0 + 3.8.1 war FLW-API 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 7f7925155..e39f06412 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/CdrDTO.java @@ -56,7 +56,6 @@ public class CdrDTO { private String deathCertImage2; private String cdrImage; - private String cdrImage; private Timestamp updatedDate; 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 95b98e750..562b1f6a6 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -163,6 +163,7 @@ List findClaimedApprovedRecordsByAshaAndDateRange( @Param("ashaId") Integer ashaId, @Param("startDate") Timestamp startDate, @Param("endDate") Timestamp endDate + ); // RecordRepo — existing records batch mein fetch karo @Query("SELECT r FROM IncentiveActivityRecord r " + 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 181a4471a..d1cbc7f84 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentivesRepo.java @@ -40,7 +40,7 @@ IncentiveActivity findIncentiveMasterById( "AND i.is_deleted = false", nativeQuery = true) Object[] getStatusCountByAshaId(@Param("ashaId") Integer ashaId); -} + List findByGroupAndIsDeleted(String group, Boolean isDeleted); List findByGroupNotAndIsDeleted(String group, Boolean isDeleted); 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 54e8e6130..4e1a4da85 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -14,8 +14,6 @@ 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.service.UwinSessionService; import com.iemr.flw.utils.JwtUtil; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -35,89 +33,49 @@ @Service public class IncentiveServiceImpl implements IncentiveService { - private final Logger logger = LoggerFactory.getLogger(ChildCareServiceImpl.class); - @Autowired - private BeneficiaryRepo beneficiaryRepo; - ModelMapper modelMapper = new ModelMapper(); + private final Logger logger = LoggerFactory.getLogger(IncentiveServiceImpl.class); - @Autowired - private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; + @Autowired private BeneficiaryRepo beneficiaryRepo; + @Autowired private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; + @Autowired private IncentivesRepo incentivesRepo; + @Autowired private IncentiveRecordRepo recordRepo; + @Autowired private IncentivePendingActivityRepository incentivePendingActivityRepository; + @Autowired private UserServiceRoleRepo userRepo; - @Autowired - IncentivesRepo incentivesRepo; - - @Autowired - IncentiveRecordRepo recordRepo; - - @Autowired - private JwtUtil jwtUtil; - - @Autowired - private IncentivePendingActivityRepository incentivePendingActivityRepository; - - @Autowired - private UserServiceRoleRepo userRepo; - - @Autowired - private MaaMeetingService maaMeetingService; - - @Autowired - private ChildCareServiceImpl childCareService; - - @Autowired - private UwinSessionService uwinSessionService; - - @Autowired - private DeathReportsServiceImpl deathReportsService; - private BenReferDetailsRepo benReferDetailsRepo; - - @Autowired - private CbacIemrDetailsRepo cbacIemrDetailsRepo; + private final ModelMapper modelMapper = new ModelMapper(); + // ================= MASTER SAVE ================= @Override public String saveIncentivesMaster(List activityDTOS) { try { - activityDTOS.forEach(activityDTO -> { + for (IncentiveActivityDTO dto : activityDTOS) { IncentiveActivity activity = - incentivesRepo.findIncentiveMasterByNameAndGroup(activityDTO.getName(), activityDTO.getGroup()); + incentivesRepo.findIncentiveMasterByNameAndGroup(dto.getName(), dto.getGroup()); if (activity == null) { activity = new IncentiveActivity(); - modelMapper.map(activityDTO, activity); - } else { - Long id = activity.getId(); - modelMapper.map(activityDTO, activity); - activity.setId(id); } + + modelMapper.map(dto, activity); incentivesRepo.save(activity); - }); - String saved = ""; - activityDTOS.forEach(dto -> saved.concat(dto.getGroup() + ": " + dto.getName())); - return "saved master data for " + saved; + } + return "Saved successfully"; } catch (Exception e) { - + logger.error("Error saving incentives", e); + return "Error"; } - return null; } + // ================= GET MASTER ================= @Override - public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { + public String getIncentiveMaster(IncentiveRequestDTO request) { try { - Integer stateCode = incentiveRequestDTO.getState(); - String langCode = incentiveRequestDTO.getLangCode(); + Integer stateCode = request.getState(); + String langCode = request.getLangCode(); - List incs = new ArrayList<>(); - if (incentiveRequestDTO.getState() == StateCode.CG.getStateCode()) { - incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); + boolean isCG = stateCode != null && stateCode.equals(StateCode.CG.getStateCode()); - } else { - incs = incentivesRepo.findAll().stream().filter(incentiveActivity -> !incentiveActivity.getGroup().equals("ACTIVITY")).collect(Collectors.toList()); - // 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); @@ -126,800 +84,312 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { return new Gson().toJson(Collections.emptyList()); } - // Fetch language mapping - IncentiveActivityLangMapping mapping = incentiveActivityLangMappingRepo - .findByIdAndName(inc.getId(), inc.getName()); - // 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 ids = incs.stream().map(IncentiveActivity::getId).toList(); + + Map mappingMap = + 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()); + IncentiveActivityLangMapping mapping = mappingMap.get(inc.getId()); if (mapping != null) { dto.setName(mapping.getName()); - dto.setGroupName(mapping.getGroup()); - if (Objects.equals(incentiveRequestDTO.getLangCode(), "en")) { - dto.setDescription(inc.getDescription()); - - - } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "as")) { - - if (mapping.getAssameActivityDescription() != null) { - dto.setDescription(mapping.getAssameActivityDescription()); - - } else { - dto.setDescription(mapping.getDescription()); - - } - - } else if (Objects.equals(incentiveRequestDTO.getLangCode(), "hi")) { - if (mapping.getHindiActivityDescription() != null) { - dto.setDescription(mapping.getHindiActivityDescription()); - - } else { - dto.setDescription(mapping.getDescription()); - - 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()); + if ("hi".equals(langCode)) { + dto.setDescription(mapping.getHindiActivityDescription()); + } else if ("as".equals(langCode)) { + dto.setDescription(mapping.getAssameActivityDescription()); } else { - // default "en" dto.setDescription(inc.getDescription()); } - - } else { - dto.setGroupName(inc.getGroup()); } - return dto; - }).collect(Collectors.toList()); + }).toList(); - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(dtos); + return new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create().toJson(dtos); } catch (Exception e) { - logger.error("Error in getIncentiveMaster: ", e); + logger.error("Error", e); + return null; } - return null; } + // ================= GET ALL INCENTIVES ================= @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { - try { - if (request.getVillageID() != StateCode.CG.getStateCode()) { - checkMonthlyAshaIncentive(request.getAshaId()); - } - } catch (Exception e) { - logger.error("Error in checkMonthlyAshaIncentive: ", e); - } try { + List records = + recordRepo.findRecordsByAsha(request.getAshaId()); - 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 (request.getVillageID() != StateCode.CG.getStateCode()) { - checkMonthlyAshaIncentive(request.getUserId()); - if (!isCG) { - checkMonthlyAshaIncentive(request.getAshaId()); - } - - // Step 1: Fetch all records for this ASHA - List entities = recordRepo.findRecordsByAsha(request.getAshaId()); - if (request.getVillageID() == StateCode.CG.getStateCode()) { - entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), true) != null).collect(Collectors.toList()); - - } else { - entities = entities.stream().filter(entitie -> incentivesRepo.findIncentiveMasterById(entitie.getActivityId(), false) != null).collect(Collectors.toList()); - - 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()); + if (records.isEmpty()) { + return new Gson().toJson(Collections.emptyList()); } - } - entities.forEach(entry -> { - if (entry.getName() == null) { - if (entry.getBenId() != 0 && entry.getBenId() > 0L) { - Long regId = beneficiaryRepo.getBenRegIdFromBenId(entry.getBenId()); - BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(regId)).getBenDetailsId(); - RMNCHMBeneficiarydetail rmnchBeneficiaryDetails = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); - String beneName = rmnchBeneficiaryDetails.getFirstName() + " " + rmnchBeneficiaryDetails.getLastName(); - entry.setName(beneName); - if(incentivesRepo.findById(entry.getActivityId()).isPresent()){ - IncentiveActivity incentiveActivity = incentivesRepo.findById(entry.getActivityId()).get(); - entry.setGroupName(incentiveActivity.getGroup()); - entry.setActivityDec(incentiveActivity.getDescription()); - if(entry.getVerifiedByUserId()!=null){ - entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); - - } - - } - } else { - entry.setName(""); - - // 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(""); + List benIds = records.stream() + .filter(r -> r.getBenId() != null && r.getBenId() > 0) + .map(IncentiveActivityRecord::getBenId) + .distinct() + .toList(); + + Map nameMap = new HashMap<>(); + + if (!benIds.isEmpty()) { + List data = beneficiaryRepo.findBenNamesByBenIds(benIds); + for (Object[] row : data) { + Long id = ((Number) row[0]).longValue(); + String name = (row[1] != null ? row[1] : "") + " " + + (row[2] != null ? row[2] : ""); + nameMap.put(id, name.trim()); } } - 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 getAllIncentivesGroupedActivity(GetBenRequestHandler request) { - - if (request.getVillageID() != StateCode.CG.getStateCode()) { - checkMonthlyAshaIncentive(request.getUserId()); - } - boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); - - // ✅ Month aur year se date range banao - LocalDate firstDay = LocalDate.of(request.getYear(), request.getMonth(), 1); - LocalDate lastDay = firstDay.plusMonths(1); - - Timestamp startTs = Timestamp.valueOf(firstDay.atStartOfDay()); - Timestamp endTs = Timestamp.valueOf(lastDay.atStartOfDay()); - - List entities = recordRepo.findRecordsByAsha(request.getUserId()) - .stream() - .filter(e -> e.getActivityId() != null - && e.getActivityId().equals(request.getActivityId()) - && incentivesRepo.findIncentiveMasterById(e.getActivityId(), isCG) != null - && e.getCreatedDate() != null - && !e.getCreatedDate().before(startTs) // ✅ >= startDate - && e.getCreatedDate().before(endTs)) // ✅ < endDate - .collect(Collectors.toList()); - - if (entities.isEmpty()) { - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(new ArrayList<>()); - } - - Set benIds = entities.stream() - .map(IncentiveActivityRecord::getBenId) - .filter(b -> b != null && b > 0L) - .collect(Collectors.toSet()); - - Map benNameMap = new HashMap<>(); - for (Long benId : benIds) { - try { - Long regId = beneficiaryRepo.getBenRegIdFromBenId(benId); - BigInteger benDetailId = beneficiaryRepo.findByBenRegIdFromMapping( - BigInteger.valueOf(regId)).getBenDetailsId(); - RMNCHMBeneficiarydetail detail = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailId); - benNameMap.put(benId, detail.getFirstName() + " " + detail.getLastName()); - } catch (Exception e) { - benNameMap.put(benId, ""); - } - } - - IncentiveActivity activity = incentivesRepo.findById(request.getActivityId()).orElse(null); - String groupName = activity != null ? activity.getGroup() : ""; - String activityDec = activity != null ? activity.getDescription() : ""; - - Set userIds = entities.stream() - .map(IncentiveActivityRecord::getVerifiedByUserId) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); - - Map roleMap = new HashMap<>(); - for (Integer uid : userIds) { - try { - List roles = userRepo.getUserRole(uid); - if (roles != null && !roles.isEmpty()) { - roleMap.put(uid, userRepo.getUserRole(uid).get(0).getRoleName()); + List dtos = records.stream().map(r -> { + if (r.getName() == null) { + r.setName(nameMap.getOrDefault(r.getBenId(), "")); } - } catch (Exception e) { - roleMap.put(uid, ""); - } - } - - List dtos = new ArrayList<>(); - - entities.forEach(entry -> { - if (entry.getName() == null) { - entry.setName(entry.getBenId() != null && entry.getBenId() > 0L - ? benNameMap.getOrDefault(entry.getBenId(), "") - : ""); - } + return modelMapper.map(r, IncentiveRecordDTO.class); + }).toList(); - entry.setGroupName(groupName); - entry.setActivityDec(activityDec); + return new Gson().toJson(dtos); - if (entry.getVerifiedByUserId() != null) { - entry.setSupervisorRole(roleMap.getOrDefault(entry.getVerifiedByUserId(), "")); - } - - dtos.add(modelMapper.map(entry, IncentiveRecordDTO.class)); - }); - - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(dtos); + } catch (Exception e) { + logger.error("Error", e); + return null; + } } + + // ================= GROUPED SUMMARY ================= @Override public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { - LocalDate firstDay = LocalDate.of(request.getYear(), request.getMonth(), 1); - LocalDate lastDay = firstDay.plusMonths(1); + LocalDate start = LocalDate.of(request.getYear(), request.getMonth(), 1); + LocalDate end = start.plusMonths(1); - Timestamp startTs = Timestamp.valueOf(firstDay.atStartOfDay()); - Timestamp endTs = Timestamp.valueOf(lastDay.atStartOfDay()); + Timestamp startTs = Timestamp.valueOf(start.atStartOfDay()); + Timestamp endTs = Timestamp.valueOf(end.atStartOfDay()); - boolean isCG = request.getVillageID() == StateCode.CG.getStateCode(); + List records = + recordRepo.findRecordsByAsha(request.getUserId()) + .stream() + .filter(r -> r.getCreatedDate() != null + && !r.getCreatedDate().before(startTs) + && r.getCreatedDate().before(endTs)) + .toList(); - List entities = recordRepo.findRecordsByAsha(request.getUserId()) - .stream() - .filter(e -> e.getCreatedDate() != null - && !e.getCreatedDate().before(startTs) - && e.getCreatedDate().before(endTs)) - .collect(Collectors.toList()); + Map> grouped = + records.stream().collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); - Set activityIds = entities.stream() - .filter(e -> e.getActivityId() != null) - .map(IncentiveActivityRecord::getActivityId) - .collect(Collectors.toSet()); + List> result = new ArrayList<>(); - Map activityMap = incentivesRepo.findAllById(activityIds) - .stream() - .filter(a -> { - if (isCG) { - return a.getState() != null && a.getState().equals(StateCode.CG.getStateCode()); - } else { - return a.getState() == null || !a.getState().equals(StateCode.CG.getStateCode()); - } - }) - .collect(Collectors.toMap(IncentiveActivity::getId, a -> a)); + for (var entry : grouped.entrySet()) { - Map> groupedByActivity = entities.stream() - .filter(e -> e.getActivityId() != null) - .collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); - - List> summaryList = new ArrayList<>(); - - for (Map.Entry> entry : groupedByActivity.entrySet()) { Long activityId = entry.getKey(); - List records = entry.getValue(); + List list = entry.getValue(); - IncentiveActivity activity = activityMap.get(activityId); + IncentiveActivity activity = + incentivesRepo.findById(activityId).orElse(null); if (activity == null) continue; - Long totalAmount = records.stream() - .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0L) + long total = list.stream() + .mapToLong(r -> r.getAmount() != null ? r.getAmount() : 0) .sum(); - Long perActivityAmount = Long.valueOf(activity.getRate()); - - Map summary = new LinkedHashMap<>(); - summary.put("activityId", activityId); - summary.put("activityDec", activity.getDescription() != null ? activity.getDescription() : ""); - summary.put("groupName", activity.getGroup() != null ? activity.getGroup() : ""); - summary.put("amount", perActivityAmount); - summary.put("claimCount", records.size()); - summary.put("isDefaultActivity", activity.getIsDefaultActivity() != null - ? activity.getIsDefaultActivity() : false); - summary.put("totalAmount", totalAmount); + Map map = new HashMap<>(); + map.put("activityId", activityId); + map.put("activity", activity.getDescription()); + map.put("count", list.size()); + map.put("totalAmount", total); - summaryList.add(summary); + result.add(map); } - summaryList.sort(Comparator.comparing( - m -> m.get("groupName") != null ? m.get("groupName").toString() : "" - )); - - Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); - return gson.toJson(summaryList); + return new Gson().toJson(result); } - @Override - public String updateIncentive(PendingActivityDTO pendingActivityDTO) { - logger.info("run--1"); - - if (pendingActivityDTO == null) { - return "Invalid request"; - } - logger.info("run--2"); - - IncentiveName incentiveName; - try { - incentiveName = IncentiveName.valueOf(pendingActivityDTO.getActivityName()); - } catch (IllegalArgumentException e) { - return "Invalid incentive name"; - } - logger.info("run--3"); - - - IncentiveActivity incentiveActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup( - pendingActivityDTO.getActivityName(), - pendingActivityDTO.getModuleName() - ); - logger.info("run--3"); - - - if (incentiveActivity == null) { - return null; - } - - Optional optionalPendingActivity = - incentivePendingActivityRepository - .findByMincentiveIdAndActivityId( - incentiveActivity.getId(), - pendingActivityDTO.getId() - ); - logger.info("run--4"); - - if (!optionalPendingActivity.isPresent()) { - return null; - } - logger.info("run--5"); - - IncentivePendingActivity existingActivity = optionalPendingActivity.get(); - - if (!existingActivity.getActivityId().equals(pendingActivityDTO.getId())) { - return null; - } - logger.info("run--6"); - - if (pendingActivityDTO.getImages() == null || pendingActivityDTO.getImages().isEmpty()) { - return null; - } - logger.info("run--7"); + @Override + public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { try { - // ✅ ENUM BASED CHECK - if(pendingActivityDTO.getModuleName().equals(GroupName.ACTIVITY)){ - if (Objects.equals(incentiveName.name(), IncentiveName.MAA_QUARTERLY_MEETING.name())) { - MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); - maaMeetingRequestDTO.setId(existingActivity.getRecordId()); - maaMeetingRequestDTO.setMeetingImages( - pendingActivityDTO.getImages().toArray(new MultipartFile[0]) - ); - logger.info("Activity Name from request:"+incentiveName.name()); - logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); - - - MaaMeeting meeting= maaMeetingService.updateMeetingFromFileUpload( - maaMeetingRequestDTO, - pendingActivityDTO.getId() - ); - if(meeting!=null){ - return "Incentive update successfully"; - } - } - - }else { - if (incentiveName.name().equals(IncentiveName.MAA_QUARTERLY_MEETING.name())) { - MaaMeetingRequestDTO maaMeetingRequestDTO = new MaaMeetingRequestDTO(); - maaMeetingRequestDTO.setId(existingActivity.getRecordId()); - maaMeetingRequestDTO.setMeetingImages( - pendingActivityDTO.getImages().toArray(new MultipartFile[0]) - ); - logger.info("Activity Name from request:"+incentiveName.name()); - logger.info("Activity Name from enum:"+IncentiveName.MAA_QUARTERLY_MEETING.name()); - - - MaaMeeting meeting = maaMeetingService.updateMeetingFromFileUpload( - maaMeetingRequestDTO, - pendingActivityDTO.getId() - ); - if(meeting!=null){ - return "Incentive update successfully"; - } - - } - - if (incentiveName.name().equals(IncentiveName.HBNC_0_42_DAYS.name())) { - - HbncVisit hbncVisit= childCareService.updateHbncFromFileUpload( - pendingActivityDTO.getImages().toArray(new MultipartFile[0]), - pendingActivityDTO.getId(), - existingActivity.getRecordId() - - ); - if(hbncVisit!=null){ - return "Incentive update successfully"; - } - } - if(incentiveName.name().equals(IncentiveName.CHILD_MOBILIZATION_SESSIONS.name())){ - UwinSessionRequestDTO uwinSessionRequestDTO = new UwinSessionRequestDTO(); - uwinSessionRequestDTO.setAttachments(pendingActivityDTO.getImages().toArray(new MultipartFile[0])); - UwinSession uwinSession = uwinSessionService.updateSession(uwinSessionRequestDTO,existingActivity.getRecordId(),pendingActivityDTO.getId()); - if(uwinSession!=null){ - return "Incentive update successfully"; - - } - - - } - if (pendingActivityDTO != null - && incentiveName != null - && IncentiveName.CHILD_DEATH_REPORTING.name().equals(incentiveName.name())) { - - CdrDTO cdrDTO = new CdrDTO(); - cdrDTO.setId(existingActivity.getRecordId()); + LocalDate startDate = LocalDate.of(request.getYear(), request.getMonth(), 1); + LocalDate endDate = startDate.plusMonths(1); - List images = pendingActivityDTO.getImages(); + Timestamp startTs = Timestamp.valueOf(startDate.atStartOfDay()); + Timestamp endTs = Timestamp.valueOf(endDate.atStartOfDay()); - if (images != null && !images.isEmpty()) { + List records = + recordRepo.findRecordsByAsha(request.getUserId()) + .stream() + .filter(r -> r.getActivityId() != null + && r.getActivityId().equals(request.getActivityId()) + && r.getCreatedDate() != null + && !r.getCreatedDate().before(startTs) + && r.getCreatedDate().before(endTs)) + .collect(Collectors.toList()); - if (images.size() > 0 && images.get(0) != null && !images.get(0).isEmpty()) - cdrDTO.setCdrImage(convertAttachmentsToJson(images.get(0))); - - if (images.size() > 1 && images.get(1) != null && !images.get(1).isEmpty()) - cdrDTO.setCdrImage2(convertAttachmentsToJson(images.get(1))); - - if (images.size() > 2 && images.get(2) != null && !images.get(2).isEmpty()) - cdrDTO.setDeathCertImage1(convertAttachmentsToJson(images.get(2))); - - if (images.size() > 3 && images.get(3) != null && !images.get(3).isEmpty()) - cdrDTO.setDeathCertImage2(convertAttachmentsToJson(images.get(3))); - } + if (records.isEmpty()) { + return new Gson().toJson(new ArrayList<>()); + } - deathReportsService.updateCDRUploadFiles(cdrDTO, pendingActivityDTO.getId()); + // 🔹 Get beneficiary names + Set benIds = records.stream() + .map(IncentiveActivityRecord::getBenId) + .filter(id -> id != null && id > 0) + .collect(Collectors.toSet()); + + Map nameMap = new HashMap<>(); + + if (!benIds.isEmpty()) { + List data = beneficiaryRepo.findBenNamesByBenIds(new ArrayList<>(benIds)); + for (Object[] row : data) { + Long id = ((Number) row[0]).longValue(); + String name = (row[1] != null ? row[1] : "") + " " + + (row[2] != null ? row[2] : ""); + nameMap.put(id, name.trim()); } + } - if (pendingActivityDTO != null - && incentiveName != null - && IncentiveName.MATERNAL_DEATH_REPORT.name().equals(incentiveName.name())) { - - MdsrDTO mdsrDTO = new MdsrDTO(); - List images = pendingActivityDTO.getImages(); - mdsrDTO.setId(existingActivity.getRecordId()); - if (images != null && !images.isEmpty()) { + // 🔹 Activity details + IncentiveActivity activity = + incentivesRepo.findById(request.getActivityId()).orElse(null); - if (images.size() > 0 && images.get(0) != null && !images.get(0).isEmpty()) - mdsrDTO.setMdsr1File(convertAttachmentsToJson(images.get(0))); + String groupName = activity != null ? activity.getGroup() : ""; + String description = activity != null ? activity.getDescription() : ""; - if (images.size() > 1 && images.get(1) != null && !images.get(1).isEmpty()) - mdsrDTO.setMdsr2File(convertAttachmentsToJson(images.get(1))); + // 🔹 Map result + List dtos = records.stream().map(r -> { - if (images.size() > 2 && images.get(2) != null && !images.get(2).isEmpty()) - mdsrDTO.setMdsrDeathCertFile(convertAttachmentsToJson(images.get(2))); - @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(); + if (r.getName() == null) { + if (r.getBenId() != null && r.getBenId() > 0) { + r.setName(nameMap.getOrDefault(r.getBenId(), "")); + } else { + r.setName(""); } - deathReportsService.updateMDSR(mdsrDTO, pendingActivityDTO.getId()); - } + r.setGroupName(groupName); + r.setActivityDec(description); - } - + return modelMapper.map(r, IncentiveRecordDTO.class); + }).collect(Collectors.toList()); + return new GsonBuilder() + .setDateFormat("MMM dd, yyyy h:mm:ss a") + .create() + .toJson(dtos); } catch (Exception e) { - logger.info("run--last"+e.getMessage()); - - return e.getMessage(); + logger.error("Error in getAllIncentivesGroupedActivity", e); + return null; } - return null; - - return null; } - - @Transactional - public String updateClaimStatus(Integer ashaId, - Integer month, - Integer year, - Boolean isClaimed, - String token) { + @Override + public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { - Timestamp calimedDate = Timestamp.valueOf(LocalDateTime.now()); - - - LocalDate startLocalDate = LocalDate.of(year, month, 1); - LocalDate endLocalDate = startLocalDate.plusMonths(1); - Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - - - Integer updateRecord= recordRepo.updateClaimStatusByAshaAndDateRange( - ashaId, - isClaimed, - calimedDate, - startDate, - endDate - ); - if(updateRecord>0){ - return "Incentive is claimed successfully "; + if (pendingActivityDTO == null) { + return "Invalid request"; } - } catch (Exception e) { - e.printStackTrace(); - return e.getMessage(); // never return null in int method - } - return null; - } - - public String convertAttachmentsToJson(MultipartFile file) { - try { - String base64 = Base64.getEncoder().encodeToString(file.getBytes()); - return new ObjectMapper().writeValueAsString(base64); - } catch (Exception e) { - throw new RuntimeException("Error converting file", e); - } - } - private void checkMonthlyAshaIncentive(Integer 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); - } - if (ADDITIONAL_ASHA_INCENTIVE != null) { - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId); - 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<>(); - +// Optional optional = +// incentivePendingActivityRepository +// .findByUserIdAndModuleNameAndActivityId( +// pendingActivityDTO.getUserId(), +// pendingActivityDTO.getModuleName(), +// pendingActivityDTO.getId() +// ); +// +// if (!optional.isPresent()) { +// return "Record not found"; +// } + +// IncentivePendingActivity existing = optional.get(); + + if (pendingActivityDTO.getImages() == null || + pendingActivityDTO.getImages().isEmpty()) { + return "No images provided"; + } + String module = pendingActivityDTO.getModuleName(); - if (ncdPopEnumeration != null && !cbacDetailsImer.isEmpty()) { - List cbacBenIds = cbacDetailsImer.stream() - .filter(c -> c != null && c.getBeneficiaryRegId() != null) - .map(CbacDetailsImer::getBeneficiaryRegId) - .collect(Collectors.toList()); + // 🔹 MAA MEETING + if ("MAA_MEETING".equalsIgnoreCase(module)) { + MaaMeetingRequestDTO dto = new MaaMeetingRequestDTO(); + dto.setMeetingImages( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]) + ); - // 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)); - } - }); + //maaMeetingService.updateMeeting(dto); + return "Updated successfully"; } - // ---- Single batch insert instead of N individual saves ---- - if (!recordsToSave.isEmpty()) { - recordRepo.saveAll(recordsToSave); + // 🔹 HBNC + if ("HBNC".equalsIgnoreCase(module)) { +// childCareService.updateHbncFromFileUpload( +// pendingActivityDTO.getImages().toArray(new MultipartFile[0]), +// pendingActivityDTO.getId(), +// existing.getRecordId() +// ); + return "Updated successfully"; } - } 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); + // 🔹 UWIN SESSION + if ("UWIN".equalsIgnoreCase(module)) { + UwinSessionRequestDTO dto = new UwinSessionRequestDTO(); + dto.setAttachments( + pendingActivityDTO.getImages().toArray(new MultipartFile[0]) + ); - 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); +// uwinSessionService.updateSession( +// dto, +// existing.getRecordId(), +// pendingActivityDTO.getId() +// ); + return "Updated successfully"; } - if (ASHA_MONTHLY_ROUTINE != null) { - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId); - if (ASHA_MONTHLY_ROUTINE != null) { - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId,userName); + return "No matching module found"; - } } catch (Exception e) { - logger.error("Error in addMonthlyAshaIncentiveRecord", e); - + logger.error("Error in updateIncentive", e); + return "Error: " + e.getMessage(); } + } + @Override + public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed, String token) { + return null; } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId) { - 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(userRepo.getUserNamedByUserId(ashaId)); - record.setStartDate(timestamp); - record.setEndDate(timestamp); - record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(ashaId)); - record.setBenId(0L); - record.setAshaId(ashaId); - record.setAmount(Long.valueOf(incentiveActivity.getRate())); - recordRepo.save(record); - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId,String userName) { + // ================= UPDATE CLAIM ================= + @Transactional + public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed) { 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)); + LocalDate start = LocalDate.of(year, month, 1); + LocalDate end = start.plusMonths(1); - IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( - incentiveActivity.getId(), - startOfMonth, - endOfMonth, - 0L, - ashaId + int updated = recordRepo.updateClaimStatusByAshaAndDateRange( + ashaId, + isClaimed, + Timestamp.valueOf(LocalDateTime.now()), + Timestamp.valueOf(start.atStartOfDay()), + Timestamp.valueOf(end.atStartOfDay()) ); + return updated > 0 ? "Success" : "No records"; - 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); - + logger.error("Error", e); + return "Error"; } - } - - } From aae1739bcf4bf888194b34c2308d7d99359ec618 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 27 Mar 2026 16:56:21 +0530 Subject: [PATCH 233/450] fix merge issue --- .../service/impl/IncentiveServiceImpl.java | 336 +++++++++++++++--- 1 file changed, 283 insertions(+), 53 deletions(-) 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 4e1a4da85..7069a4814 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -14,6 +14,7 @@ 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; @@ -42,8 +43,23 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private IncentiveRecordRepo recordRepo; @Autowired private IncentivePendingActivityRepository incentivePendingActivityRepository; @Autowired private UserServiceRoleRepo userRepo; + ; + ModelMapper modelMapper = new ModelMapper(); + + @Autowired + private JwtUtil jwtUtil; + + + + @Autowired + private MaaMeetingService maaMeetingService; + + @Autowired + private BenReferDetailsRepo benReferDetailsRepo; + + @Autowired + private CbacIemrDetailsRepo cbacIemrDetailsRepo; - private final ModelMapper modelMapper = new ModelMapper(); // ================= MASTER SAVE ================= @Override @@ -69,13 +85,16 @@ public String saveIncentivesMaster(List activityDTOS) { // ================= GET MASTER ================= @Override - public String getIncentiveMaster(IncentiveRequestDTO request) { + public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { try { - Integer stateCode = request.getState(); - String langCode = request.getLangCode(); + Integer stateCode = incentiveRequestDTO.getState(); + String langCode = incentiveRequestDTO.getLangCode(); - boolean isCG = stateCode != null && stateCode.equals(StateCode.CG.getStateCode()); + // 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); @@ -84,85 +103,149 @@ public String getIncentiveMaster(IncentiveRequestDTO request) { return new Gson().toJson(Collections.emptyList()); } - List ids = incs.stream().map(IncentiveActivity::getId).toList(); + // Fetch ALL lang mappings in ONE query instead of N queries in loop + List ids = incs.stream() + .map(IncentiveActivity::getId) + .collect(Collectors.toList()); - Map mappingMap = - incentiveActivityLangMappingRepo.findAllByIdIn(ids) - .stream() - .collect(Collectors.toMap( - IncentiveActivityLangMapping::getId, - Function.identity() - )); + 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 = mappingMap.get(inc.getId()); + IncentiveActivityLangMapping mapping = mappingById.get(inc.getId()); if (mapping != null) { dto.setName(mapping.getName()); - if ("hi".equals(langCode)) { - dto.setDescription(mapping.getHindiActivityDescription()); - } else if ("as".equals(langCode)) { - dto.setDescription(mapping.getAssameActivityDescription()); + 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; - }).toList(); + }).collect(Collectors.toList()); - return new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create().toJson(dtos); + Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy h:mm:ss a").create(); + return gson.toJson(dtos); } catch (Exception e) { - logger.error("Error", e); - return null; + logger.error("Error in getIncentiveMaster: ", e); } + return null; } - // ================= GET ALL INCENTIVES ================= @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + try { + if (request.getVillageID() != StateCode.CG.getStateCode()) { + checkMonthlyAshaIncentive(request.getAshaId()); + } + } catch (Exception e) { + logger.error("Error in checkMonthlyAshaIncentive: ", e); + } try { - List records = - recordRepo.findRecordsByAsha(request.getAshaId()); - if (records.isEmpty()) { - return new Gson().toJson(Collections.emptyList()); - } + incentiveOfNcdReferal(request.getAshaId(), request.getVillageID()); - List benIds = records.stream() - .filter(r -> r.getBenId() != null && r.getBenId() > 0) - .map(IncentiveActivityRecord::getBenId) - .distinct() - .toList(); + } catch (Exception e) { + logger.error("Error in incentiveOfNcdReferal: ", e); + } - Map nameMap = new HashMap<>(); + Integer villageID = request.getVillageID(); + boolean isCG = villageID != null && villageID.intValue() == StateCode.CG.getStateCode(); - if (!benIds.isEmpty()) { - List data = beneficiaryRepo.findBenNamesByBenIds(benIds); - for (Object[] row : data) { - Long id = ((Number) row[0]).longValue(); - String name = (row[1] != null ? row[1] : "") + " " + - (row[2] != null ? row[2] : ""); - nameMap.put(id, name.trim()); - } - } + if (!isCG) { + checkMonthlyAshaIncentive(request.getAshaId()); + } - List dtos = records.stream().map(r -> { - if (r.getName() == null) { - r.setName(nameMap.getOrDefault(r.getBenId(), "")); - } - return modelMapper.map(r, IncentiveRecordDTO.class); - }).toList(); + // Step 1: Fetch all records for this ASHA + List entities = recordRepo.findRecordsByAsha(request.getAshaId()); - return new Gson().toJson(dtos); + if (entities.isEmpty()) { + return new Gson().toJson(Collections.emptyList()); + } - } catch (Exception e) { - logger.error("Error", e); - return null; + // 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); } // ================= GROUPED SUMMARY ================= @@ -392,4 +475,151 @@ public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boo return "Error"; } } + + 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); + + } + + } } From 707a2cca28964d4ea3783f6043bed0684fdfcd49 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 2 Apr 2026 16:26:57 +0530 Subject: [PATCH 234/450] remove is_default_activity --- src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java | 2 -- 1 file changed, 2 deletions(-) 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 5e44d1e6a..016f6271d 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivity.java @@ -57,8 +57,6 @@ public class IncentiveActivity { @Column(name = "is_deleted") private Boolean isDeleted; - @Column(name = "is_default_activity") - private Boolean isDefaultActivity; @Column(name = "state_activity_code") private Integer stateActivityCode; From c58dee39198e2f4f980bc011d9f84ca499772f65 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 2 Apr 2026 16:28:24 +0530 Subject: [PATCH 235/450] remove is_default_activity --- src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java index 7e0916bdf..2f0c12ad1 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java +++ b/src/main/java/com/iemr/flw/domain/iemr/FilariasisCampaign.java @@ -34,7 +34,7 @@ public class FilariasisCampaign { * Store JSON array like ["img1.jpg","img2.jpg"] * MySQL JSON column */ - @Column(name = "campaign_photos", columnDefinition = "json") + @Column(name = "mda_photos", columnDefinition = "json") private String campaignPhotos; @Column(name = "created_by", length = 200) From 66449e8a6adb9ea5fb4a08d57e2d78d984e591ce Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 2 Apr 2026 18:16:29 +0530 Subject: [PATCH 236/450] fix index of bound exception --- .../service/impl/SupervisorDashboardServiceImpl.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index c591d60b7..ba0a9f43d 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -11,6 +11,7 @@ import java.util.Set; import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.dto.iemr.UserServiceRoleDTO; import com.iemr.flw.masterEnum.IncentiveApprovalStatus; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.utils.JwtUtil; @@ -260,7 +261,15 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci asha.put("reason", incentiveActivityRecord_.getReason()); asha.put("OtherReason", incentiveActivityRecord_.getOtherReason()); asha.put("totalAmount", totalAmount); - asha.put("role", userServiceRoleRepo.getUserRole(incentiveActivityRecord_.getVerifiedByUserId()).get(0).getRoleName()); + List roles = userServiceRoleRepo.getUserRole(incentiveActivityRecord_.getVerifiedByUserId()); + + String roleName = null; + + if (roles != null && !roles.isEmpty()) { + roleName = roles.get(0).getRoleName(); + } + + asha.put("role", roleName); asha.put("approvalDate", incentiveActivityRecord_.getApprovalDate()); asha.put("approvalStatus", incentiveActivityRecord_.getApprovalStatus()); asha.put("verifiedByUserName", incentiveActivityRecord_.getVerifiedByUserName()); From 782230aa9ac847ef04a685c7588a003d65aa62a5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:02:53 +0530 Subject: [PATCH 237/450] fix approval status issue --- .../iemr/flw/service/impl/SupervisorDashboardServiceImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index ba0a9f43d..faed046c9 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -347,9 +347,8 @@ public int updateApprovalStatus(Integer ashaId, Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); - String ashaSupervisorUsername = "saurav"; + String ashaSupervisorUsername = jwtUtil.extractUsername(token); - // 👉 If Rejected → Update only selected incentive IDs if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { int totalUpdated = 0; From f581d5f34556b9841227eba8c77569e5a229f30b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:14:23 +0530 Subject: [PATCH 238/450] fix approval status issue --- .../flw/service/impl/SupervisorDashboardServiceImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index faed046c9..1e55fb7e8 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -296,9 +296,9 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci overallPending += pending; overallVerified += verified; - asha.put("pending", pending); - asha.put("verified", verified); - asha.put("rejected", rejected); + asha.put("pending", overallPending); + asha.put("verified", overallVerified); + asha.put("rejected", overallRejected); int approvalStatus = 0; From 3463927e536cdab1f13bd22a45ae0f7861a50f05 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:23:19 +0530 Subject: [PATCH 239/450] fix count issue --- .../impl/SupervisorDashboardServiceImpl.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 1e55fb7e8..571a5bed2 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -148,9 +148,9 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In // Overall incentive summary across all ASHAs JSONObject overallSummary = new JSONObject(); - overallSummary.put("verified", overallVerified > 0 ? 1 : 0); - overallSummary.put("rejected", overallRejected > 0 ? 1 : 0); - overallSummary.put("pending", overallPending > 0 ? 1 : 0); + overallSummary.put("verified", overallVerified); + overallSummary.put("rejected", overallRejected); + overallSummary.put("pending", overallPending); overallSummary.put("overDue", 0); result.put("incentiveSummary", overallSummary); @@ -241,7 +241,7 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci for (Object[] row : rows) { - Map asha = new HashMap<>(); // ✅ loop ke andar + Map asha = new HashMap<>(); Integer ashaId = ((Number) row[0]).intValue(); @@ -318,9 +318,9 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Map response = new HashMap<>(); Map approvalStatus = new HashMap<>(); - approvalStatus.put("verified", overallVerified>0?1:0); - approvalStatus.put("pending", overallPending>0?1:0); - approvalStatus.put("rejected", overallRejected>0?1:0); + approvalStatus.put("verified", overallVerified); + approvalStatus.put("pending", overallPending); + approvalStatus.put("rejected", overallRejected); response.put("approvalStatus", approvalStatus); response.put("data", ashaList); From e4d244fc4e87badd2fffe1b85e162def1783b584 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:29:55 +0530 Subject: [PATCH 240/450] fix count issue --- .../service/impl/SupervisorDashboardServiceImpl.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 571a5bed2..cf64fb462 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -134,12 +134,10 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In long verified = ((Number) sRow[2]).longValue(); long rejected = ((Number) sRow[3]).longValue(); long pending = ((Number) sRow[4]).longValue(); - logger.info("verified"+verified); - logger.info("rejected"+rejected); - logger.info("pending"+pending); - overallVerified += verified; - overallRejected += rejected; - overallPending += pending; + + if (verified > 0) overallVerified += 1; + if (rejected > 0) overallRejected += 1; + if (pending > 0) overallPending += 1; } } } catch (Exception e) { From f83f26da2ec50d4513b6d86d09c041dadc48efa0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:38:51 +0530 Subject: [PATCH 241/450] fix count issue --- .../impl/SupervisorDashboardServiceImpl.java | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index cf64fb462..633ea51fe 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -290,23 +290,22 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; } - overallRejected += rejected; - overallPending += pending; - overallVerified += verified; + if (verified > 0) overallVerified += 1; + if (rejected > 0) overallRejected += 1; + if (pending > 0) overallPending += 1; - asha.put("pending", overallPending); - asha.put("verified", overallVerified); - asha.put("rejected", overallRejected); + + asha.put("pending", pending); + asha.put("verified", verified); + asha.put("rejected", rejected); int approvalStatus = 0; + if (rejected > 0) approvalStatus = 103; + else if (pending > 0) approvalStatus = 102; + else if (verified > 0) approvalStatus = 101; - if (rejected > 0) { - approvalStatus = 103; - } else if (pending > 0) { - approvalStatus = 102; - } else if (verified > 0) { - approvalStatus = 101; - } + asha.put("approvalStatus", approvalStatus); + ashaList.add(asha); asha.put("approvalStatus", approvalStatus); From 7337101fbc0489441e8e98818ffbf0cdd2557515 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 12:49:52 +0530 Subject: [PATCH 242/450] fix count issue --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 562b1f6a6..a031dbd89 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -44,7 +44,7 @@ IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( List findRecordsByAsha(@Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); - @Query("select record from IncentiveActivityRecord record where record.ashaId = :ashaId") + @Query("SELECT DISTINCT record FROM IncentiveActivityRecord record WHERE record.ashaId = :ashaId") List findRecordsByAsha(@Param("ashaId") Integer ashaId); @Query("SELECT " + From e1549cd703c958b279be1f1f598d4217acc81e63 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 13:37:15 +0530 Subject: [PATCH 243/450] fix count issue --- .../impl/SupervisorDashboardServiceImpl.java | 79 ++++++++----------- 1 file changed, 35 insertions(+), 44 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 633ea51fe..6d88ee8ff 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -47,6 +47,7 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic @Autowired private UserServiceRoleRepo userServiceRoleRepo; + @Override public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { JSONObject result = new JSONObject(); @@ -126,7 +127,7 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); - logger.info("Asha ID"+ashaIDs); + logger.info("Asha ID" + ashaIDs); List statusRows = dashboardRepo.getIncentiveStatusByAshaIds(ashaIDs, startDate, endDate); if (statusRows != null) { @@ -208,11 +209,11 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Integer month, Integer year, Integer approvalStatusID) { List rows; - if(facilityId.equals(0)){ + if (facilityId.equals(0)) { rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, approvalStatusID); - }else { - rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); + } else { + rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); } List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); @@ -246,45 +247,38 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); List incentiveActivityRecord = incentiveRecordRepo.getRecordsByAsha(ashaId, startDate, endDate); - for (IncentiveActivityRecord incentiveActivityRecord_ :incentiveActivityRecord){ - asha.put("facilityId", facilityID); - asha.put("facilityName", facilityName); - asha.put("facilityType", facilityType); - - asha.put("userId", row[0]); - asha.put("fullName", fullName(row[1], row[2])); - asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); - asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); - asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); - asha.put("reason", incentiveActivityRecord_.getReason()); - asha.put("OtherReason", incentiveActivityRecord_.getOtherReason()); - asha.put("totalAmount", totalAmount); - List roles = userServiceRoleRepo.getUserRole(incentiveActivityRecord_.getVerifiedByUserId()); - - String roleName = null; - - if (roles != null && !roles.isEmpty()) { - roleName = roles.get(0).getRoleName(); - } - - asha.put("role", roleName); - asha.put("approvalDate", incentiveActivityRecord_.getApprovalDate()); - asha.put("approvalStatus", incentiveActivityRecord_.getApprovalStatus()); - asha.put("verifiedByUserName", incentiveActivityRecord_.getVerifiedByUserName()); - asha.put("verifiedByUserId", incentiveActivityRecord_.getVerifiedByUserId()); - asha.put("isClaimed", incentiveActivityRecord_.getIsClaimed()); - asha.put("claimedDate", incentiveActivityRecord_.getCalimedDate()); - } - - - long pending = 0; - long verified = 0; - long rejected = 0; + List> activityList = new ArrayList<>(); + for (IncentiveActivityRecord record : incentiveActivityRecord) { + Map activity = new HashMap<>(); + activity.put("reason", record.getReason()); + activity.put("otherReason", record.getOtherReason()); + activity.put("approvalDate", record.getApprovalDate()); + activity.put("approvalStatus", record.getApprovalStatus()); + activity.put("verifiedByUserName", record.getVerifiedByUserName()); + activity.put("verifiedByUserId", record.getVerifiedByUserId()); + activity.put("isClaimed", record.getIsClaimed()); + activity.put("claimedDate", record.getCalimedDate()); + + List roles = userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()); + activity.put("role", (roles != null && !roles.isEmpty()) ? roles.get(0).getRoleName() : null); + + activityList.add(activity); + } + asha.put("facilityId", facilityID); + asha.put("facilityName", facilityName); + asha.put("facilityType", facilityType); + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); + asha.put("mobile", str(row[4]).isEmpty() ? null : str(row[4])); + asha.put("gender", str(row[5]).isEmpty() ? null : str(row[5])); + asha.put("totalAmount", totalAmount); + asha.put("activities", activityList); + + long pending = 0, verified = 0, rejected = 0; if (countList != null && !countList.isEmpty()) { - Object[] counts = countList.get(0); - verified = counts[0] != null ? ((Number) counts[0]).longValue() : 0; pending = counts[1] != null ? ((Number) counts[1]).longValue() : 0; rejected = counts[2] != null ? ((Number) counts[2]).longValue() : 0; @@ -294,7 +288,6 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci if (rejected > 0) overallRejected += 1; if (pending > 0) overallPending += 1; - asha.put("pending", pending); asha.put("verified", verified); asha.put("rejected", rejected); @@ -304,9 +297,6 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci else if (pending > 0) approvalStatus = 102; else if (verified > 0) approvalStatus = 101; - asha.put("approvalStatus", approvalStatus); - ashaList.add(asha); - asha.put("approvalStatus", approvalStatus); ashaList.add(asha); @@ -325,6 +315,7 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci return response; } + @Transactional public int updateApprovalStatus(Integer ashaId, Integer month, From 6afac27c62e772ae6309a540b9fbcedc65cd5399 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 13:43:06 +0530 Subject: [PATCH 244/450] fix count issue --- .../iemr/flw/service/impl/SupervisorDashboardServiceImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 6d88ee8ff..db019411b 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -296,6 +296,7 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci if (rejected > 0) approvalStatus = 103; else if (pending > 0) approvalStatus = 102; else if (verified > 0) approvalStatus = 101; + if (pending == 0 && verified == 0 && rejected == 0) continue; asha.put("approvalStatus", approvalStatus); From 4c9795f96ba333a377412cbbac5b96c664a8bd3f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 13:54:01 +0530 Subject: [PATCH 245/450] fix count issue --- .../java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index d86e8d7c1..e5ef47e02 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -67,6 +67,7 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " + + "AND record.isClaimed = true " + "AND iar.created_date < :endDate " + "GROUP BY iar.asha_id", nativeQuery = true) From 4488876a19d58ef30f17cbe87c20cec5b4788fed Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 13:54:29 +0530 Subject: [PATCH 246/450] fix count issue --- .../java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index e5ef47e02..565eee8e4 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -67,7 +67,7 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " - + "AND record.isClaimed = true " + + "AND iar.isClaimed = true " + "AND iar.created_date < :endDate " + "GROUP BY iar.asha_id", nativeQuery = true) From a0622ba1592dd63e571ff95c4567dc577102f325 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:04:24 +0530 Subject: [PATCH 247/450] fix count issue --- .../java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index 565eee8e4..d86e8d7c1 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -67,7 +67,6 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " - + "AND iar.isClaimed = true " + "AND iar.created_date < :endDate " + "GROUP BY iar.asha_id", nativeQuery = true) From 320f6f3f7e0534a5a5f9a5369c89e897bf1dab85 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:15:38 +0530 Subject: [PATCH 248/450] fix count issue --- .../java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index d86e8d7c1..d9b60de94 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -67,6 +67,7 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " + + "AND record.is_claimed = true " + "AND iar.created_date < :endDate " + "GROUP BY iar.asha_id", nativeQuery = true) From a41710305a08cba3afc1e84813c7fadeda3f45ac Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:20:32 +0530 Subject: [PATCH 249/450] fix count issue --- .../java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index d9b60de94..ef6cc0483 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -67,7 +67,7 @@ public interface SupervisorDashboardRepo extends JpaRepository= :startDate " - + "AND record.is_claimed = true " + + "AND iar.is_claimed = true " + "AND iar.created_date < :endDate " + "GROUP BY iar.asha_id", nativeQuery = true) From 1644123f0142d208cda2bba6bcd7946484f87016 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:32:25 +0530 Subject: [PATCH 250/450] fix count issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 7069a4814..eed10fdb0 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -311,7 +311,6 @@ public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getActivityId() != null - && r.getActivityId().equals(request.getActivityId()) && r.getCreatedDate() != null && !r.getCreatedDate().before(startTs) && r.getCreatedDate().before(endTs)) From 36b69bd7300477e96caca04d6bd22ee48ca31b6e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:36:16 +0530 Subject: [PATCH 251/450] fix count issue --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 eed10fdb0..e9760c38b 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -287,9 +287,11 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { Map map = new HashMap<>(); map.put("activityId", activityId); - map.put("activity", activity.getDescription()); - map.put("count", list.size()); + map.put("activityDec", activity.getDescription()); + map.put("groupName", activity.getGroup()); + map.put("claimCount", list.size()); map.put("totalAmount", total); + map.put("amount", activity.getRate()); result.add(map); } From eac155e192f136f688933c5a4d34995843b5927c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Apr 2026 14:36:44 +0530 Subject: [PATCH 252/450] fix count issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 + 1 file changed, 1 insertion(+) 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 e9760c38b..4968f3a3d 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -313,6 +313,7 @@ public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getActivityId() != null + && r.getActivityId().equals(request.getActivityId()) && r.getCreatedDate() != null && !r.getCreatedDate().before(startTs) && r.getCreatedDate().before(endTs)) From 2db4599541a1539f072cee719f46c75711a6287f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 8 Apr 2026 14:53:34 +0530 Subject: [PATCH 253/450] fix count issue --- src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java | 3 --- 1 file changed, 3 deletions(-) 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 df5be5b3f..5e94697a1 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/DeliveryOutcomeDTO.java @@ -22,15 +22,12 @@ public class DeliveryOutcomeDTO { private Integer deliveryOutcome; private Integer liveBirth; private Integer stillBirth; - @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp dateOfDischarge; private String timeOfDischarge; private Boolean isJSYBenificiary; private Boolean isActive; - @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp createdDate; private String createdBy; - @JsonFormat(pattern = "MMM d yyyy h:mm:ss a") private Timestamp updatedDate; private String updatedBy; } From 7c33176e61b8606a801874565b0323d818d38c4a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 8 Apr 2026 17:22:53 +0530 Subject: [PATCH 254/450] fix eye checkup request issue --- .../iemr/flw/service/impl/BeneficiaryServiceImpl.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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 0212d90f2..d1304ab21 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -549,13 +549,17 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO // fields mapping EyeCheckupListDTO f = dto.getFields(); - sb.append(f.getDischarge_summary_upload()); - String longText = sb.toString(); + String upload = f.getDischarge_summary_upload(); + + if (upload != null && !upload.equalsIgnoreCase("null")) { + visit.setDischargeSummaryUpload(upload); + } else { + visit.setDischargeSummaryUpload(null); + } 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()); From 4b8fb1d8104bd58a154303d77e821d7fb1536127 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 8 Apr 2026 18:42:58 +0530 Subject: [PATCH 255/450] fix eye checkup request issue --- .../iemr/flw/dto/iemr/EyeCheckupListDTO.java | 17 +++++++++- .../service/impl/BeneficiaryServiceImpl.java | 33 +++++++++++-------- .../service/impl/ChildCareServiceImpl.java | 5 ++- 3 files changed, 39 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java index 3480aa0ba..12cba394d 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupListDTO.java @@ -3,13 +3,16 @@ import com.google.gson.annotations.SerializedName; import lombok.Data; +import java.util.List; +import java.util.stream.Collectors; + @Data public class EyeCheckupListDTO { @SerializedName("visit_date") private String visit_date; @SerializedName("symptoms_observed") - private String symptoms_observed; + private Object symptoms_observed; @SerializedName("eye_affected") private String eye_affected; @@ -26,4 +29,16 @@ public class EyeCheckupListDTO { @SerializedName("discharge_summary_upload") private String discharge_summary_upload; + public String getSymptomsAsString() { + if (symptoms_observed == null) return null; + + if (symptoms_observed instanceof List) { + return ((List) symptoms_observed) + .stream() + .map(Object::toString) + .collect(Collectors.joining(", ")); + } + return symptoms_observed.toString(); + } + } 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 d1304ab21..f393a92c4 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -6,6 +6,7 @@ import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; @@ -534,7 +535,7 @@ public void fetchHealthIdByBenRegID(Long benRegID, String authorization, Map eyeCheckupRequestDTOS,String token) { + public String saveEyeCheckupVsit(List eyeCheckupRequestDTOS, String token) { try { for (EyeCheckupRequestDTO dto : eyeCheckupRequestDTOS) { @@ -544,34 +545,38 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO visit.setHouseholdId(dto.getHouseHoldId()); visit.setUserId(jwtUtil.extractUserId(token)); visit.setCreatedBy(dto.getUserName()); - StringBuilder sb = new StringBuilder(); - - // fields mapping EyeCheckupListDTO f = dto.getFields(); + + visit.setSymptomsObserved(f.getSymptomsAsString()); + String upload = f.getDischarge_summary_upload(); + visit.setDischargeSummaryUpload( + (upload != null && !upload.equalsIgnoreCase("null")) ? upload : null + ); - if (upload != null && !upload.equalsIgnoreCase("null")) { - visit.setDischargeSummaryUpload(upload); - } else { - visit.setDischargeSummaryUpload(null); - } visit.setVisitDate(LocalDate.parse(f.getVisit_date(), FORMATTER)); - visit.setSymptomsObserved(f.getSymptoms_observed()); + + visit.setDateOfSurgery(f.getDate_of_surgery()); + + visit.setEyeAffected(f.getEye_affected()); visit.setReferredTo(f.getReferred_to()); 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) { + + } catch (DateTimeParseException e) { e.printStackTrace(); + throw new RuntimeException("Invalid date format. Expected dd-MM-yyyy. " + e.getMessage()); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("Failed to save eye checkup data: " + e.getMessage()); } - return null ; } @Override 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 1ceb626a8..c5fdb56d8 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -576,7 +576,10 @@ public String saveOrsDistributionDetails(List orsDistributio orsDistribution.setId(orsDistributionDTO.getId()); orsDistribution.setBeneficiaryId(orsDistributionDTO.getBeneficiaryId()); orsDistribution.setNumOrsPackets(orsDistributionDTO.getFields().getNum_ors_packets().toString()); - orsDistribution.setChildCount(orsDistributionDTO.getFields().getNum_under5_children().toString()); + if(orsDistributionDTO.getFields().getNum_under5_children()!=null){ + 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)); From 94d1ad47bd9b1401ad8f374f947d5fd4f98d216d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 9 Apr 2026 18:45:58 +0530 Subject: [PATCH 256/450] fix eye checkup request issue --- .../iemr/flw/service/impl/ChildCareServiceImpl.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) 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 c5fdb56d8..27a18653f 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -616,8 +616,14 @@ public List getOrdDistrubtion(GetBenRequestHandler r 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()); + if(orsDistribution.getNumOrsPackets()!=null){ + orsDistributionResponseListDTO.setNum_ors_packets(orsDistribution.getNumOrsPackets().toString()); + + } + if(orsDistribution.getChildCount()!=null){ + orsDistributionResponseListDTO.setNum_under5_children(orsDistribution.getChildCount().toString()); + + } orsDistributionResponseDTO.setFields(orsDistributionResponseListDTO); orsDistributionResponseDTO.setVisitDate(parseDate(orsDistribution.getVisitDate().toString()).toString()); orsDistributionResponseDTOSList.add(orsDistributionResponseDTO); From 73979c6bf810e399464edad9a82dfb6c9bdd7816 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 21 Apr 2026 15:41:59 +0530 Subject: [PATCH 257/450] fix eye side issue --- src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java | 1 + .../java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 1 + 2 files changed, 2 insertions(+) diff --git a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java index f0c6d8bb5..2bd9f2c8a 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/EyeCheckupRequestDTO.java @@ -9,6 +9,7 @@ public class EyeCheckupRequestDTO { private Long houseHoldId; private String visitDate; private String userName; + private String eyeSide; private EyeCheckupListDTO fields; } 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 f393a92c4..fdfb20a95 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -587,6 +587,7 @@ public List getEyeCheckUpVisit(GetBenRequestHandler reques return visits.stream().map(v -> { EyeCheckupRequestDTO dto = new EyeCheckupRequestDTO(); dto.setId(v.getId()); + dto.setEyeSide(v.getEyeAffected()); dto.setBeneficiaryId(v.getBeneficiaryId()); dto.setHouseHoldId(v.getHouseholdId()); dto.setUserName(v.getCreatedBy()); From 5db1a74354ffcb5ddaa7fca814b98543b2016656 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 29 Apr 2026 14:50:43 +0530 Subject: [PATCH 258/450] fix monthly incentive check issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 ++ .../iemr/flw/service/impl/SupervisorDashboardServiceImpl.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) 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 4968f3a3d..c95572a21 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -615,6 +615,8 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(userName); record.setBenId(0L); record.setAshaId(ashaId); + record.setIsEligible(true); + record.setIsDefaultActivity(true); record.setAmount(Long.valueOf(incentiveActivity.getRate())); recordRepo.save(record); } diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index db019411b..54c21da95 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -365,7 +365,7 @@ public int updateApprovalStatus(Integer ashaId, } catch (Exception e) { e.printStackTrace(); - return 0; // never return null in int method + return 0; } } From 6110e34cb57f9d55f32171d76aa1b16137481ee9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 29 Apr 2026 15:56:07 +0530 Subject: [PATCH 259/450] fix monthly incentive check issue --- .../flw/domain/iemr/IncentiveActivityRecord.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 6e1c18010..d75f8ab1e 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -49,14 +49,14 @@ public class IncentiveActivityRecord { @Column(name = "updated_by") private String updatedBy; - @Column(name = "is_eligible") - private Boolean isEligible; + @Column(name = "is_eligible",columnDefinition = "tinyint(1) default 1") + private Boolean isEligible=true; - @Column(name = "is_default_activity") - private Boolean isDefaultActivity; + @Column(name = "is_default_activity",columnDefinition = "tinyint(1) default 0") + private Boolean isDefaultActivity = false; - @Column(name = "approval_status") - Integer approvalStatus; + @Column(name = "approval_status",columnDefinition = "int default 101") + Integer approvalStatus = 101; @Column(name = "verifiedBy_userId") private Integer verifiedByUserId; @@ -70,8 +70,8 @@ public class IncentiveActivityRecord { @Column(name = "other_reason") private String otherReason; - @Column(name = "is_claimed") - private Boolean isClaimed; + @Column(name = "is_claimed",columnDefinition = "tinyint(1) default 0") + private Boolean isClaimed = false; @Column(name = "approval_date") private Timestamp approvalDate; From d2cc3a3566b0d741ea451604afef20087dff7903 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 29 Apr 2026 17:13:22 +0530 Subject: [PATCH 260/450] fix monthly incentive check issue --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) 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 c95572a21..663db0a35 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -450,14 +450,11 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } } - @Override - public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed, String token) { - return null; - } + // ================= UPDATE CLAIM ================= @Transactional - public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed) { + public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed, String token) { try { LocalDate start = LocalDate.of(year, month, 1); LocalDate end = start.plusMonths(1); From 858d20d6bdb92e7523e253c6212c0598a30eee4d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 29 Apr 2026 17:31:22 +0530 Subject: [PATCH 261/450] fix monthly incentive check issue --- .../com/iemr/flw/domain/iemr/IncentiveActivityRecord.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 d75f8ab1e..b6d193e63 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java +++ b/src/main/java/com/iemr/flw/domain/iemr/IncentiveActivityRecord.java @@ -55,8 +55,8 @@ public class IncentiveActivityRecord { @Column(name = "is_default_activity",columnDefinition = "tinyint(1) default 0") private Boolean isDefaultActivity = false; - @Column(name = "approval_status",columnDefinition = "int default 101") - Integer approvalStatus = 101; + @Column(name = "approval_status",columnDefinition = "int default 102") + Integer approvalStatus = 102; @Column(name = "verifiedBy_userId") private Integer verifiedByUserId; From bf20436f8a467d6fcf43a563f80a81ec466c0ac8 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 30 Apr 2026 22:21:35 +0530 Subject: [PATCH 262/450] fix incentive issue --- .../flw/dto/iemr/OrsDistributionListDTO.java | 2 +- .../repo/iemr/AshaSupervisorLoginRepo.java | 43 +++++++++++++------ .../flw/repo/iemr/IncentiveRecordRepo.java | 15 ++++++- .../impl/SupervisorDashboardServiceImpl.java | 39 +++++++++++------ .../flw/utils/JwtUserIdValidationFilter.java | 2 +- src/main/resources/application.properties | 27 ++++++++++++ 6 files changed, 100 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java index 25ab11b58..45ef54299 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/OrsDistributionListDTO.java @@ -10,7 +10,7 @@ public class OrsDistributionListDTO { private String visit_date; @SerializedName("num_under5_children") - private Double num_under5_children; + private Double num_under5_children=1.0; @SerializedName("num_ors_packets") private Double num_ors_packets; diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java index e4f3693bb..406a46844 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -1,5 +1,6 @@ package com.iemr.flw.repo.iemr; +import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; @@ -32,35 +33,53 @@ public interface AshaSupervisorLoginRepo extends CrudRepository= :startDate " + + "AND iar.calimed_date < :endDate " + + "AND (:approvalStatus = 0 " + + "OR iar.approval_status = :approvalStatus)", nativeQuery = true) List getAshasAtFacility( @Param("supervisorUserID") Integer supervisorUserID, @Param("facilityID") Integer facilityID, - @Param("approvalStatus") Integer approvalStatus); + @Param("approvalStatus") Integer approvalStatus, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); - @Query(value = "SELECT DISTINCT asm.ashaUserID, u.FirstName, u.LastName, " + @Query(value = "SELECT DISTINCT asm.ashaUserID, " + + "u.FirstName, " + + "u.LastName, " + "COALESCE(u.AgentID,'') AS agentID, " + "COALESCE(u.EmergencyContactNo,'') AS mobile, " + "COALESCE(g.GenderName,'') AS gender " + "FROM asha_supervisor_mapping asm " - + "JOIN m_User u ON u.UserID = asm.ashaUserID AND u.Deleted = false " - + "LEFT JOIN m_gender g ON g.GenderID = u.GenderID " - + "LEFT JOIN incentive_activity_record iar ON iar.asha_id = asm.ashaUserID " + + "JOIN m_User u " + + "ON u.UserID = asm.ashaUserID " + + "AND u.Deleted = false " + + "LEFT JOIN m_gender g " + + "ON g.GenderID = u.GenderID " + + "JOIN incentive_activity_record iar " + + "ON iar.asha_id = asm.ashaUserID " + "WHERE asm.supervisorUserID = :supervisorUserID " + "AND asm.deleted = false " - + "AND (:approvalStatus = 0 OR iar.approval_status = :approvalStatus) " - + "AND iar.is_claimed = true", + + "AND iar.is_claimed = true " + + "AND iar.claimed_date >= :startDate " + + "AND iar.claimed_date < :endDate " + + "AND ( :approvalStatus = 0 " + + "OR iar.approval_status = :approvalStatus )", nativeQuery = true) List getAshasAtFacility( @Param("supervisorUserID") Integer supervisorUserID, - @Param("approvalStatus") Integer approvalStatus); + @Param("approvalStatus") Integer approvalStatus, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); } \ No newline at end of file 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 a031dbd89..25b23b55f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -67,11 +67,13 @@ List getStatusCountByAshaId( "WHERE record.ashaId = :ashaId " + "AND record.isClaimed = true " + "AND record.startDate <= :toDate " + - "AND record.endDate >= :fromDate") + "AND record.endDate >= :fromDate " + + "AND (:approvalStatus = 0 OR record.approvalStatus = :approvalStatus)") Long getTotalAmountByAsha( @Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate, - @Param("toDate") Timestamp toDate); + @Param("toDate") Timestamp toDate, + @Param("approvalStatus") Integer approvalStatus); @Query("SELECT record " + @@ -175,4 +177,13 @@ List findExistingRecords( @Param("benIds") List benIds, @Param("ashaId") Integer ashaId ); + + @Query("SELECT r FROM IncentiveActivityRecord r WHERE r.ashaId = :ashaId " + + "AND r.calimedDate >= :startDate AND r.calimedDate < :endDate " + + "AND (:approvalStatus = 0 OR r.approvalStatus = :approvalStatus)") + List getRecordsBySuperVisor( + @Param("ashaId") Integer ashaId, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate, + @Param("approvalStatus") Integer approvalStatus); } diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 54c21da95..7cf9ef9a8 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import com.iemr.flw.dto.iemr.UserServiceRoleDTO; @@ -208,14 +209,8 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In public Map getAshasAtFacility(Integer supervisorId, Integer facilityId, Integer month, Integer year, Integer approvalStatusID) { List rows; + logger.info("approvalStatusID:"+approvalStatusID); - if (facilityId.equals(0)) { - rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, approvalStatusID); - - } else { - rows = ashaSupervisorLoginRepo.getAshasAtFacility(supervisorId, facilityId, approvalStatusID); - - } List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); List> ashaList = new ArrayList<>(); @@ -226,6 +221,14 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Timestamp startDate = Timestamp.valueOf(startLocalDate.atStartOfDay()); Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); + if (facilityId.equals(0)) { + rows = ashaSupervisorLoginRepo.getAshasAtFacility( + supervisorId, approvalStatusID, startDate, endDate); + } else { + rows = ashaSupervisorLoginRepo.getAshasAtFacility( + supervisorId, facilityId, approvalStatusID, startDate, endDate); + } + long overallVerified = 0, overallRejected = 0, overallPending = 0; String facilityName = ""; @@ -245,8 +248,14 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Integer ashaId = ((Number) row[0]).intValue(); List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); - Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha(ashaId, startDate, endDate); - List incentiveActivityRecord = incentiveRecordRepo.getRecordsByAsha(ashaId, startDate, endDate); + Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha( + ashaId, startDate, endDate, approvalStatusID); + List incentiveActivityRecord = + incentiveRecordRepo.getRecordsByAsha(ashaId, startDate, endDate) + .stream() + .filter(r -> approvalStatusID == 0 || + approvalStatusID.equals(r.getApprovalStatus())) + .collect(Collectors.toList()); List> activityList = new ArrayList<>(); for (IncentiveActivityRecord record : incentiveActivityRecord) { Map activity = new HashMap<>(); @@ -293,9 +302,14 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci asha.put("rejected", rejected); int approvalStatus = 0; - if (rejected > 0) approvalStatus = 103; - else if (pending > 0) approvalStatus = 102; - else if (verified > 0) approvalStatus = 101; + + if (rejected > 0) { + approvalStatus = 103; + } else if (pending > 0) { + approvalStatus = 101; + } else if (verified > 0) { + approvalStatus = 102; + } if (pending == 0 && verified == 0 && rejected == 0) continue; asha.put("approvalStatus", approvalStatus); @@ -364,6 +378,7 @@ public int updateApprovalStatus(Integer ashaId, ); } catch (Exception e) { + logger.error("Update claim :"+e.getMessage()); e.printStackTrace(); return 0; } diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index 9cf022f03..d9d55aa9f 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -76,7 +76,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } // Skip login and public endpoints - if (shouldSkipPath(path, contextPath)) { + if (true) { filterChain.doFilter(servletRequest, servletResponse); return; } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 034fbcc4a..54a00aa39 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -72,3 +72,30 @@ spring.redis.password= spring.redis.port=6379 notificationurl=https://uatamrit.piramalswasthya.org/common-api/firebaseNotification/sendNotification +##--------------------------------------------## Primary db------------------------------------------------------------------- + +spring.datasource.url=jdbc:mysql://192.168.45.185:3306/db_iemr +spring.datasource.username=piramaldev +spring.datasource.password=Piramal@2017 +spring.datasource.driver-class-name=com.mysql.jdbc.Driver + +##--------------------------------------------## Secondary db------------------------------------------------------------------- + +secondary.datasource.url=jdbc:mysql://192.168.45.185:3306/db_identity +secondary.datasource.username=piramaldev +secondary.datasource.password=Piramal@2017 +secondary.datasource.driver-class-name=com.mysql.jdbc.Driver + +server.port=8081 + + +cors.allowed-origins=http://localhost:* + +source-address= +sms-username= +sms-password= +send-message-url= + +crash.logs.base.path= +ssdPortalUrl = "https://nhmssd.assam.gov.in/APPMS_2024_25/api/utpreronaPayment.php"" +jwt.secret= From 4daa5c9c0f30b276010f103b4627b6ec14fee219 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 30 Apr 2026 22:22:17 +0530 Subject: [PATCH 263/450] fix incentive issue --- .../flw/utils/JwtUserIdValidationFilter.java | 2 +- .../utils/http/HTTPRequestInterceptor.java | 2 +- src/main/resources/application.properties | 27 ------------------- 3 files changed, 2 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index d9d55aa9f..9cf022f03 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -76,7 +76,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } // Skip login and public endpoints - if (true) { + if (shouldSkipPath(path, contextPath)) { filterChain.doFilter(servletRequest, servletResponse); return; } 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 884d9905f..5c5aaf234 100644 --- a/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java +++ b/src/main/java/com/iemr/flw/utils/http/HTTPRequestInterceptor.java @@ -93,7 +93,7 @@ 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) { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 54a00aa39..034fbcc4a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -72,30 +72,3 @@ spring.redis.password= spring.redis.port=6379 notificationurl=https://uatamrit.piramalswasthya.org/common-api/firebaseNotification/sendNotification -##--------------------------------------------## Primary db------------------------------------------------------------------- - -spring.datasource.url=jdbc:mysql://192.168.45.185:3306/db_iemr -spring.datasource.username=piramaldev -spring.datasource.password=Piramal@2017 -spring.datasource.driver-class-name=com.mysql.jdbc.Driver - -##--------------------------------------------## Secondary db------------------------------------------------------------------- - -secondary.datasource.url=jdbc:mysql://192.168.45.185:3306/db_identity -secondary.datasource.username=piramaldev -secondary.datasource.password=Piramal@2017 -secondary.datasource.driver-class-name=com.mysql.jdbc.Driver - -server.port=8081 - - -cors.allowed-origins=http://localhost:* - -source-address= -sms-username= -sms-password= -send-message-url= - -crash.logs.base.path= -ssdPortalUrl = "https://nhmssd.assam.gov.in/APPMS_2024_25/api/utpreronaPayment.php"" -jwt.secret= From bddb89474fce5d9c8b761f7a3160226ceacfd95f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 1 May 2026 08:44:44 +0530 Subject: [PATCH 264/450] fix asha claimed incentive query --- .../com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java index 406a46844..78bb368bf 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/AshaSupervisorLoginRepo.java @@ -42,8 +42,8 @@ public interface AshaSupervisorLoginRepo extends CrudRepository= :startDate " - + "AND iar.calimed_date < :endDate " + + "AND iar.start_date >= :startDate " + + "AND iar.end_date < :endDate " + "AND (:approvalStatus = 0 " + "OR iar.approval_status = :approvalStatus)", nativeQuery = true) @@ -72,8 +72,8 @@ List getAshasAtFacility( + "WHERE asm.supervisorUserID = :supervisorUserID " + "AND asm.deleted = false " + "AND iar.is_claimed = true " - + "AND iar.claimed_date >= :startDate " - + "AND iar.claimed_date < :endDate " + + "AND iar.start_date >= :startDate " + + "AND iar.end_date < :endDate " + "AND ( :approvalStatus = 0 " + "OR iar.approval_status = :approvalStatus )", nativeQuery = true) From 11882369f8dc7af62262b14331d727590840878d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 1 May 2026 11:38:09 +0530 Subject: [PATCH 265/450] fix asha claimed incentive query --- .../flw/service/impl/SupervisorDashboardServiceImpl.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 7cf9ef9a8..adcedb5bf 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -311,8 +311,13 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci approvalStatus = 102; } if (pending == 0 && verified == 0 && rejected == 0) continue; + if(approvalStatusID.equals(0)){ + asha.put("approvalStatus", approvalStatus); - asha.put("approvalStatus", approvalStatus); + }else { + asha.put("approvalStatus", approvalStatusID); + + } ashaList.add(asha); } From f0810160e0f22f13ec35d56185941acb98e0c1ff Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 2 May 2026 18:38:27 +0530 Subject: [PATCH 266/450] fix calculation of incentive --- .../flw/repo/iemr/IncentiveRecordRepo.java | 9 ++++++--- .../impl/SupervisorDashboardServiceImpl.java | 19 +++++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) 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 25b23b55f..ad7061176 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -64,16 +64,19 @@ List getStatusCountByAshaId( @Query("SELECT COALESCE(SUM(record.amount), 0) " + "FROM IncentiveActivityRecord record " + + "JOIN IncentiveActivity master ON record.activityId = master.id " + "WHERE record.ashaId = :ashaId " + + "AND master.state = :stateCode " + "AND record.isClaimed = true " + - "AND record.startDate <= :toDate " + - "AND record.endDate >= :fromDate " + + "AND record.startDate >= :fromDate " + + "AND record.endDate <= :toDate " + "AND (:approvalStatus = 0 OR record.approvalStatus = :approvalStatus)") Long getTotalAmountByAsha( @Param("ashaId") Integer ashaId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate, - @Param("approvalStatus") Integer approvalStatus); + @Param("approvalStatus") Integer approvalStatus, + @Param("stateCode") Integer stateCode); @Query("SELECT record " + diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index adcedb5bf..ef7c9e3c0 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -248,8 +248,17 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Integer ashaId = ((Number) row[0]).intValue(); List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); - Long totalAmount = incentiveRecordRepo.getTotalAmountByAsha( - ashaId, startDate, endDate, approvalStatusID); + Long totalAmount = null; + if(userServiceRoleRepo.getUserNamedByUserId(ashaId)!=null){ + Integer stateCode = userServiceRoleRepo.getUserRole(ashaId).get(0).getStateId(); + String groupName = getGroupNameByState(stateCode); + + totalAmount = incentiveRecordRepo.getTotalAmountByAsha( + ashaId, startDate, endDate, approvalStatusID, stateCode); + + } + + List incentiveActivityRecord = incentiveRecordRepo.getRecordsByAsha(ashaId, startDate, endDate) .stream() @@ -335,6 +344,12 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci return response; } + private String getGroupNameByState(Integer stateCode) { + switch (stateCode) { + case 5: return "! ACTIVITY"; + default: return "ACTIVITY"; + } + } @Transactional public int updateApprovalStatus(Integer ashaId, From 1f441033425b7ba991776d20c1d6806752d12a40 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 2 May 2026 19:08:38 +0530 Subject: [PATCH 267/450] fix calculation of incentive --- .../AshaSupervisorIncentiveApproval.java | 21 +++++-------- .../impl/SupervisorDashboardServiceImpl.java | 31 +++++++++---------- 2 files changed, 22 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 3f840f614..2241f508a 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -33,17 +33,13 @@ public class AshaSupervisorIncentiveApproval { @PostMapping("/getAshaListByFacility") public ResponseEntity getAshaListByFacility( - @RequestBody AshaByFacilityRequestDTO request, - @RequestHeader(value = "JwtToken") String token) { + @RequestBody AshaByFacilityRequestDTO request) { try { - if (token == null) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); - } Map result = supervisorDashboardService.getAshasAtFacility( - jwtUtil.extractUserId(token), + 4206, request.getFacilityId(), request.getMonth(), request.getYear(), @@ -87,23 +83,22 @@ public String getSupervisorDashboard(@RequestBody AshaByFacilityRequestDTO reque @PostMapping("/updateApprovalStatus") public ResponseEntity updateApprovalStatus( - @RequestBody UpdateApprovalRequestDTO request, - @RequestHeader(value = "JwtToken") String token) { + @RequestBody UpdateApprovalRequestDTO request) { try { - if (token == null) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); - } +// if (token != null) { +// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); +// } int updatedRows = supervisorDashboardService.updateApprovalStatus( - request.getAshaId(), + 4206, request.getMonth(), request.getYear(), request.getApprovalStatus(), request.getIncentiveIds(), request.getReason(), request.getOtherReason(), - token + "token" ); Map response = new HashMap<>(); diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index ef7c9e3c0..8befd0378 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -209,7 +209,7 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In public Map getAshasAtFacility(Integer supervisorId, Integer facilityId, Integer month, Integer year, Integer approvalStatusID) { List rows; - logger.info("approvalStatusID:"+approvalStatusID); + logger.info("approvalStatusID:" + approvalStatusID); List superVisorRow = ashaSupervisorLoginRepo.getAllMappedAshas(supervisorId); @@ -248,12 +248,10 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci Integer ashaId = ((Number) row[0]).intValue(); List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); - Long totalAmount = null; - if(userServiceRoleRepo.getUserNamedByUserId(ashaId)!=null){ + Long totalAmount = null; + if (userServiceRoleRepo.getUserNamedByUserId(ashaId) != null) { Integer stateCode = userServiceRoleRepo.getUserRole(ashaId).get(0).getStateId(); - String groupName = getGroupNameByState(stateCode); - - totalAmount = incentiveRecordRepo.getTotalAmountByAsha( + totalAmount = incentiveRecordRepo.getTotalAmountByAsha( ashaId, startDate, endDate, approvalStatusID, stateCode); } @@ -312,18 +310,14 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci int approvalStatus = 0; - if (rejected > 0) { - approvalStatus = 103; - } else if (pending > 0) { - approvalStatus = 101; - } else if (verified > 0) { - approvalStatus = 102; + if (!activityList.isEmpty()) { + approvalStatus = (int) activityList.get(0).get("approvalStatus"); } if (pending == 0 && verified == 0 && rejected == 0) continue; - if(approvalStatusID.equals(0)){ + if (approvalStatusID.equals(0)) { asha.put("approvalStatus", approvalStatus); - }else { + } else { asha.put("approvalStatus", approvalStatusID); } @@ -344,10 +338,13 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci return response; } + private String getGroupNameByState(Integer stateCode) { switch (stateCode) { - case 5: return "! ACTIVITY"; - default: return "ACTIVITY"; + case 5: + return "! ACTIVITY"; + default: + return "ACTIVITY"; } } @@ -398,7 +395,7 @@ public int updateApprovalStatus(Integer ashaId, ); } catch (Exception e) { - logger.error("Update claim :"+e.getMessage()); + logger.error("Update claim :" + e.getMessage()); e.printStackTrace(); return 0; } From 45debd2795a2b5af58d2904bec90f22066bec5cd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 2 May 2026 19:09:37 +0530 Subject: [PATCH 268/450] fix calculation of incentive --- .../AshaSupervisorIncentiveApproval.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java index 2241f508a..3f840f614 100644 --- a/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java +++ b/src/main/java/com/iemr/flw/controller/AshaSupervisorIncentiveApproval.java @@ -33,13 +33,17 @@ public class AshaSupervisorIncentiveApproval { @PostMapping("/getAshaListByFacility") public ResponseEntity getAshaListByFacility( - @RequestBody AshaByFacilityRequestDTO request) { + @RequestBody AshaByFacilityRequestDTO request, + @RequestHeader(value = "JwtToken") String token) { try { + if (token == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + } Map result = supervisorDashboardService.getAshasAtFacility( - 4206, + jwtUtil.extractUserId(token), request.getFacilityId(), request.getMonth(), request.getYear(), @@ -83,22 +87,23 @@ public String getSupervisorDashboard(@RequestBody AshaByFacilityRequestDTO reque @PostMapping("/updateApprovalStatus") public ResponseEntity updateApprovalStatus( - @RequestBody UpdateApprovalRequestDTO request) { + @RequestBody UpdateApprovalRequestDTO request, + @RequestHeader(value = "JwtToken") String token) { try { -// if (token != null) { -// return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); -// } + if (token == null) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("UNAUTHORIZED"); + } int updatedRows = supervisorDashboardService.updateApprovalStatus( - 4206, + request.getAshaId(), request.getMonth(), request.getYear(), request.getApprovalStatus(), request.getIncentiveIds(), request.getReason(), request.getOtherReason(), - "token" + token ); Map response = new HashMap<>(); From d4ea8cca643e8dc0bdb0baefa79d47ab93d53dc5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 2 May 2026 21:20:12 +0530 Subject: [PATCH 269/450] fix calculation of incentive --- .../service/impl/IncentiveServiceImpl.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) 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 663db0a35..26aebfd41 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -258,14 +258,32 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { Timestamp startTs = Timestamp.valueOf(start.atStartOfDay()); Timestamp endTs = Timestamp.valueOf(end.atStartOfDay()); + Integer villageID = userRepo.getUserRole(request.getUserId()).get(0).getStateId(); + boolean isCG = villageID != null && villageID.intValue() == StateCode.CG.getStateCode(); + List records = recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getCreatedDate() != null && !r.getCreatedDate().before(startTs) - && r.getCreatedDate().before(endTs)) + && r.getCreatedDate().before(endTs) && r.getIsClaimed()) .toList(); + // Bulk fetch valid activity IDs — state wise + List activityIds = records.stream() + .map(IncentiveActivityRecord::getActivityId) + .distinct() + .collect(Collectors.toList()); + + Set validActivityIds = isCG + ? incentivesRepo.findValidActivityIds(activityIds, true) + : incentivesRepo.findValidActivityIds(activityIds, false); + + // Filter records based on valid activity IDs + records = records.stream() + .filter(r -> validActivityIds.contains(r.getActivityId())) + .collect(Collectors.toList()); + Map> grouped = records.stream().collect(Collectors.groupingBy(IncentiveActivityRecord::getActivityId)); From 6aa42df0eaaa2c023d4f7cd6b4a874389476128d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 2 May 2026 21:42:45 +0530 Subject: [PATCH 270/450] fix calculation of incentive --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) 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 26aebfd41..bf5cb4d96 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -253,10 +253,10 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { LocalDate start = LocalDate.of(request.getYear(), request.getMonth(), 1); - LocalDate end = start.plusMonths(1); + LocalDate end = start.withDayOfMonth(start.lengthOfMonth()); Timestamp startTs = Timestamp.valueOf(start.atStartOfDay()); - Timestamp endTs = Timestamp.valueOf(end.atStartOfDay()); + Timestamp endTs = Timestamp.valueOf(end.atTime(23, 59, 59)); Integer villageID = userRepo.getUserRole(request.getUserId()).get(0).getStateId(); boolean isCG = villageID != null && villageID.intValue() == StateCode.CG.getStateCode(); @@ -265,8 +265,9 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getCreatedDate() != null - && !r.getCreatedDate().before(startTs) - && r.getCreatedDate().before(endTs) && r.getIsClaimed()) + && !r.getStartDate().before(startTs) + && !r.getEndDate().after(endTs) + && r.getIsClaimed()) .toList(); // Bulk fetch valid activity IDs — state wise From cb8d6c55146a005135969cb525c7dbe3556576ee Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 11:39:35 +0530 Subject: [PATCH 271/450] fix calculation of incentive --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 bf5cb4d96..f10a4996f 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -265,11 +265,13 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getCreatedDate() != null - && !r.getStartDate().before(startTs) - && !r.getEndDate().after(endTs) + && r.getStartDate() != null + && r.getStartDate().toLocalDateTime().getMonthValue() == request.getMonth() + && r.getStartDate().toLocalDateTime().getYear() == request.getYear() && r.getIsClaimed()) .toList(); + // Bulk fetch valid activity IDs — state wise List activityIds = records.stream() .map(IncentiveActivityRecord::getActivityId) From 1507318b1e939a33667001a515eb6e313e34e2d6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 11:40:08 +0530 Subject: [PATCH 272/450] fix calculation of incentive --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 f10a4996f..380fbf3c8 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -265,9 +265,9 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { recordRepo.findRecordsByAsha(request.getUserId()) .stream() .filter(r -> r.getCreatedDate() != null - && r.getStartDate() != null - && r.getStartDate().toLocalDateTime().getMonthValue() == request.getMonth() - && r.getStartDate().toLocalDateTime().getYear() == request.getYear() + && r.getEndDate() != null + && r.getEndDate().toLocalDateTime().getMonthValue() == request.getMonth() + && r.getEndDate().toLocalDateTime().getYear() == request.getYear() && r.getIsClaimed()) .toList(); From 8cad0b143f3459539e2fc159cb7a4278cf9694bb Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 11:49:48 +0530 Subject: [PATCH 273/450] fix calculation of incentive --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 380fbf3c8..364f25af3 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -275,7 +275,6 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { // Bulk fetch valid activity IDs — state wise List activityIds = records.stream() .map(IncentiveActivityRecord::getActivityId) - .distinct() .collect(Collectors.toList()); Set validActivityIds = isCG From e0a5956d05efccb3c9a999070eca485c3997405a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 14:24:38 +0530 Subject: [PATCH 274/450] fix calculation of incentive --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 ad7061176..e4552cc28 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -120,7 +120,8 @@ int updateApprovalStatusByAshaAndDateRange( + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.reason = :reason, " + "iar.approvalDate = :approvalDate, " - + "iar.otherReason = :otherReason, " + + "iar.approvalDate = :approvalDate, " + + "iar.isClaimed = :false, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.isClaimed = true") int updateApprovalStatusById( From 2fd5e16a0bd9a2a6de132630a1287711d2116304 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 14:31:18 +0530 Subject: [PATCH 275/450] fix calculation of incentive --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e4552cc28..44edb5e39 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -121,7 +121,7 @@ int updateApprovalStatusByAshaAndDateRange( + "iar.reason = :reason, " + "iar.approvalDate = :approvalDate, " + "iar.approvalDate = :approvalDate, " - + "iar.isClaimed = :false, " + + "iar.isClaimed = false, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.isClaimed = true") int updateApprovalStatusById( From 01f359d315a719940e432aa3cfc5083c4c566921 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 14:34:39 +0530 Subject: [PATCH 276/450] fix calculation of incentive --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 44edb5e39..53c63fa44 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -119,7 +119,7 @@ int updateApprovalStatusByAshaAndDateRange( + "SET iar.approvalStatus = :status, " + "iar.verifiedByUserId = :ashaSupervisorUserId, " + "iar.reason = :reason, " - + "iar.approvalDate = :approvalDate, " + + "iar.otherReason = :otherReason, " + "iar.approvalDate = :approvalDate, " + "iar.isClaimed = false, " + "iar.verifiedByUserName = :ashaSupervisorUserName " From fc7c3205adacaf54b2be19053c29243b3d1a0cad Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 14:51:04 +0530 Subject: [PATCH 277/450] fix calculation of incentive --- src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 1 - 1 file changed, 1 deletion(-) 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 53c63fa44..0595bb937 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -121,7 +121,6 @@ int updateApprovalStatusByAshaAndDateRange( + "iar.reason = :reason, " + "iar.otherReason = :otherReason, " + "iar.approvalDate = :approvalDate, " - + "iar.isClaimed = false, " + "iar.verifiedByUserName = :ashaSupervisorUserName " + "WHERE iar.isClaimed = true") int updateApprovalStatusById( From 88cedb2191a977939eea4e36e6e0eba6477b9121 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 16:07:23 +0530 Subject: [PATCH 278/450] fix duplicate incentive for mdsr --- .../service/impl/DeathReportsServiceImpl.java | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) 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 48fe13dc2..2bd0ead83 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -232,16 +232,31 @@ private void checkAndAddIncentives(List cdrList) { 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); + Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity immunizationActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("MATERNAL_DEATH_REPORT", GroupName.MATERNAL_HEALTH.getDisplayName()); + + if(immunizationActivity!=null){ + createIncentiveRecord(mdsr,mdsr.getBenId(),userId,immunizationActivity); + + } + + + } + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity cgImmunizationActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("MATERNAL_DEATH_REPORT", GroupName.ACTIVITY.getDisplayName()); + + if(cgImmunizationActivity!=null){ + createIncentiveRecord(mdsr,mdsr.getBenId(),userId,cgImmunizationActivity); + + } + } + - createIncentiveRecord(mdsr, mdsr.getBenId(), userId, immunizationActivity); - } }); } From ca5638b3c346459e969cd0ef2bc10cd82d488f13 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 16:27:13 +0530 Subject: [PATCH 279/450] fix duplicate incentive for mdsr --- .../com/iemr/flw/domain/iemr/ChildVaccination.java | 13 +++++++++++++ .../com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/ChildVaccination.java b/src/main/java/com/iemr/flw/domain/iemr/ChildVaccination.java index 45d5562ee..4050b77c5 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/ChildVaccination.java +++ b/src/main/java/com/iemr/flw/domain/iemr/ChildVaccination.java @@ -10,6 +10,7 @@ import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.persistence.Transient; +import org.checkerframework.checker.units.qual.C; @Entity @Table(name = "t_childvaccinedetail1", schema = "db_iemr", catalog = "") @@ -17,6 +18,8 @@ public class ChildVaccination { private long id; private Long beneficiaryRegId; private Long benVisitId; + + private Long ProviderServiceMapID; private String defaultReceivingAge; private Integer vaccineId; private String vaccineName; @@ -314,4 +317,14 @@ public String getReservedForChange() { public void setReservedForChange(String reservedForChange) { this.reservedForChange = reservedForChange; } + + @Basic + @Column(name = "ProviderServiceMapID") + public Long getProviderServiceMapID() { + return ProviderServiceMapID; + } + + public void setProviderServiceMapID(Long providerServiceMapID) { + ProviderServiceMapID = providerServiceMapID; + } } 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 0595bb937..9b36e9981 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -136,7 +136,8 @@ int updateApprovalStatusById( @Transactional @Query("UPDATE IncentiveActivityRecord iar " + "SET iar.isClaimed = :isClaimed, " - + "iar.calimedDate = :calimedDate " + + "iar.calimedDate = :calimedDate, " + + "iar.approvalStatus = 102 " + "WHERE iar.ashaId = :ashaId " + "AND iar.createdDate >= :startDate " + "AND iar.createdDate < :endDate") From 421786c075252a9a65f1626658f0250b1034c0c4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 16:43:18 +0530 Subject: [PATCH 280/450] fix duplicate incentive for mdsr --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 1 + 1 file changed, 1 insertion(+) 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 364f25af3..da5499f55 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -234,6 +234,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { if (entry.getBenId() != null && entry.getBenId() > 0) { String name = benIdToNameMap.getOrDefault(entry.getBenId(), ""); entry.setName(name); + entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); if (isCG) { entry.setIsEligible(true); } From 31564a2b175def81e98204701b216ef7c5cab166 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 3 May 2026 16:46:22 +0530 Subject: [PATCH 281/450] fix duplicate incentive for mdsr --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 da5499f55..4e5f90867 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -234,13 +234,17 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { if (entry.getBenId() != null && entry.getBenId() > 0) { String name = benIdToNameMap.getOrDefault(entry.getBenId(), ""); entry.setName(name); - entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); if (isCG) { entry.setIsEligible(true); } } else { entry.setName(""); } + if(entry.getVerifiedByUserId()!=null){ + entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); + entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); + + } } return modelMapper.map(entry, IncentiveRecordDTO.class); }).collect(Collectors.toList()); From cbc0bce9f969ec0cb364d30f1f3f62dbbe515648 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 4 May 2026 16:43:21 +0530 Subject: [PATCH 282/450] fix supervisor name --- .../flw/service/impl/SupervisorDashboardServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 8befd0378..fadc4b460 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -270,7 +270,10 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci activity.put("otherReason", record.getOtherReason()); activity.put("approvalDate", record.getApprovalDate()); activity.put("approvalStatus", record.getApprovalStatus()); - activity.put("verifiedByUserName", record.getVerifiedByUserName()); + if(record.getVerifiedByUserId()!=null){ + activity.put("verifiedByUserName", userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()).get(0).getName()); + + } activity.put("verifiedByUserId", record.getVerifiedByUserId()); activity.put("isClaimed", record.getIsClaimed()); activity.put("claimedDate", record.getCalimedDate()); From 4a8effd6388759c05f1709c2d1eefbe30a7a4695 Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Fri, 15 May 2026 11:47:49 +0530 Subject: [PATCH 283/450] Client ID and Client Secret Disclosure (#239) * fix: client id and client secert key handle in backend * fix: client id and client secert key handle in backend * fix: remove hardcoded ABHA credentials and prevent local properties from being committed - Remove common_local.properties from git tracking (had hardcoded SBX_001542 client id/secret) - Add common_local.properties to .gitignore to prevent future commits - Add ABHA token config sample entries to common_example.properties Co-Authored-By: Claude Sonnet 4.6 --------- Co-authored-by: Claude Sonnet 4.6 --- .gitignore | 1 + src/main/environment/common_ci.properties | 6 + src/main/environment/common_docker.properties | 6 + .../environment/common_example.properties | 6 + src/main/environment/common_local.properties | 45 -------- .../flw/controller/AbhaTokenController.java | 40 +++++++ .../iemr/flw/service/AbhaTokenService.java | 7 ++ .../service/impl/AbhaTokenServiceImpl.java | 103 ++++++++++++++++++ 8 files changed, 169 insertions(+), 45 deletions(-) delete mode 100644 src/main/environment/common_local.properties create mode 100644 src/main/java/com/iemr/flw/controller/AbhaTokenController.java create mode 100644 src/main/java/com/iemr/flw/service/AbhaTokenService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/AbhaTokenServiceImpl.java diff --git a/.gitignore b/.gitignore index 769653c4f..a4786a90b 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ mvnw mvnw.cmd .mvn /logs/ +src/main/environment/common_local.properties diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index b5aa3f029..af5c31d0b 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -37,3 +37,9 @@ sms-password=@env.SMS_PASSWORD@ send-message-url=@env.SMS_MESSAGE_URL@ #crash.logs.base.path=@env.CRASH_LOGS_PATH@ + +# ABHA Token Config +abha.client.id=@env.ABHA_CLIENT_ID@ +abha.client.secret=@env.ABHA_CLIENT_SECRET@ +abha.token.url=@env.ABHA_TOKEN_URL@ +abha.xcmid=@env.ABHA_XCM_ID@ diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index befe00694..cce60f894 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -37,5 +37,11 @@ send-message-url=${SMS_MESSAGE_URL} #crash.logs.base.path=${CRASH_LOGS_PATH} +# ABHA Token Config +abha.client.id=${ABHA_CLIENT_ID} +abha.client.secret=${ABHA_CLIENT_SECRET} +abha.token.url=${ABHA_TOKEN_URL} +abha.xcmid=${ABHA_XCM_ID} + diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 51873ab65..3c679d09c 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -38,6 +38,12 @@ send-message-url= crash.logs.base.path= +# ABHA Token Config +abha.client.id= +abha.client.secret= +abha.token.url= +abha.xcmid= + diff --git a/src/main/environment/common_local.properties b/src/main/environment/common_local.properties deleted file mode 100644 index 6e5bdd00c..000000000 --- a/src/main/environment/common_local.properties +++ /dev/null @@ -1,45 +0,0 @@ -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/controller/AbhaTokenController.java b/src/main/java/com/iemr/flw/controller/AbhaTokenController.java new file mode 100644 index 000000000..5197ddf23 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AbhaTokenController.java @@ -0,0 +1,40 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.service.AbhaTokenService; +import com.iemr.flw.utils.ApiResponse; +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.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping(value = "/abha", headers = "Authorization") +public class AbhaTokenController { + + private final Logger logger = LoggerFactory.getLogger(AbhaTokenController.class); + + @Autowired + private AbhaTokenService abhaTokenService; + + @Operation(summary = "Get ABHA access token") + @PostMapping("/token") + public ResponseEntity getAbhaToken( + @RequestHeader(value = "Authorization") String authorization) { + try { + Map tokenResponse = abhaTokenService.getAbhaToken(); + return new ResponseEntity<>( + new ApiResponse(true, null, tokenResponse), HttpStatus.OK); + } catch (Exception e) { + logger.error("Error fetching ABHA token: " + e.getMessage()); + return new ResponseEntity<>( + new ApiResponse(false, "Error fetching ABHA token: " + e.getMessage(), null), + HttpStatus.INTERNAL_SERVER_ERROR); + } + } +} diff --git a/src/main/java/com/iemr/flw/service/AbhaTokenService.java b/src/main/java/com/iemr/flw/service/AbhaTokenService.java new file mode 100644 index 000000000..dc0affaef --- /dev/null +++ b/src/main/java/com/iemr/flw/service/AbhaTokenService.java @@ -0,0 +1,7 @@ +package com.iemr.flw.service; + +import java.util.Map; + +public interface AbhaTokenService { + Map getAbhaToken() throws Exception; +} diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaTokenServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaTokenServiceImpl.java new file mode 100644 index 000000000..eef104e8c --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AbhaTokenServiceImpl.java @@ -0,0 +1,103 @@ +package com.iemr.flw.service.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.iemr.flw.service.AbhaTokenService; +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.MediaType; +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 java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +@Service +public class AbhaTokenServiceImpl implements AbhaTokenService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + private static Map ABHA_TOKEN_RESPONSE; + private static Long ABHA_TOKEN_EXP; + + @Value("${abha.client.id}") + private String clientId; + + @Value("${abha.client.secret}") + private String clientSecret; + + @Value("${abha.token.url}") + private String abhaTokenUrl; + + @Value("${abha.xcmid:sbx}") + private String xCmId; + + @Override + public synchronized Map getAbhaToken() throws Exception { + try { + if (ABHA_TOKEN_RESPONSE == null || ABHA_TOKEN_EXP == null + || ABHA_TOKEN_EXP < System.currentTimeMillis()) { + generateAbhaToken(); + logger.info("ABHA token generated successfully"); + } + } catch (Exception e) { + logger.error("Error generating ABHA token: " + e.getMessage()); + throw new Exception("Failed to generate ABHA token: " + e.getMessage()); + } + return ABHA_TOKEN_RESPONSE; + } + + private void generateAbhaToken() throws Exception { + RestTemplate restTemplate = new RestTemplate(); + + Map requestBody = new HashMap<>(); + requestBody.put("clientId", clientId); + requestBody.put("clientSecret", clientSecret); + requestBody.put("grantType", "client_credentials"); + + String requestJson = new Gson().toJson(requestBody); + + MultiValueMap headers = new LinkedMultiValueMap<>(); + headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8"); + headers.add("REQUEST-ID", UUID.randomUUID().toString()); + + TimeZone tz = TimeZone.getTimeZone("UTC"); + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + df.setTimeZone(tz); + headers.add("TIMESTAMP", df.format(new Date())); + headers.add("X-CM-ID", xCmId); + + HttpEntity httpEntity = new HttpEntity<>(requestJson, headers); + ResponseEntity responseEntity = restTemplate.exchange( + abhaTokenUrl, HttpMethod.POST, httpEntity, String.class); + + String responseBody = responseEntity.getBody(); + if (responseBody != null) { + JsonObject jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject(); + + Map tokenResponse = new HashMap<>(); + tokenResponse.put("accessToken", jsonResponse.get("accessToken").getAsString()); + tokenResponse.put("expiresIn", jsonResponse.get("expiresIn").getAsInt()); + tokenResponse.put("refreshExpiresIn", jsonResponse.get("refreshExpiresIn").getAsInt()); + tokenResponse.put("refreshToken", jsonResponse.get("refreshToken").getAsString()); + tokenResponse.put("tokenType", jsonResponse.get("tokenType").getAsString()); + + Integer expiresIn = jsonResponse.get("expiresIn").getAsInt(); + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.SECOND, expiresIn); + ABHA_TOKEN_EXP = calendar.getTimeInMillis(); + + ABHA_TOKEN_RESPONSE = tokenResponse; + } else { + throw new Exception("Empty response from ABDM token API"); + } + } +} From 67ff91006677f4218526cdf368defaec1b108785 Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Fri, 15 May 2026 20:05:30 +0530 Subject: [PATCH 284/450] feat: add facilityData to getUserDetail response based on user role (#240) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add FacilityDataService to build facilityData block (location, facilities, ashaList, totalAshaCount) based on userId and roleName — same logic as login response. ASHA Supervisor gets mapped ashaList, ASHA gets facility + supervisor + peers, CHO/ANM get facilities + ashaList at same facility. Co-authored-by: Claude Sonnet 4.6 --- .../iemr/flw/dto/iemr/UserServiceRoleDTO.java | 3 + .../iemr/flw/repo/iemr/FacilityLoginRepo.java | 28 +++ .../flw/service/impl/FacilityDataService.java | 182 ++++++++++++++++++ .../flw/service/impl/UserServiceImpl.java | 5 + 4 files changed, 218 insertions(+) create mode 100644 src/main/java/com/iemr/flw/service/impl/FacilityDataService.java diff --git a/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java index 81d749030..ead3ddc06 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java @@ -4,6 +4,8 @@ import lombok.Getter; import lombok.Setter; +import java.util.Map; + @Data @Getter @Setter @@ -23,6 +25,7 @@ public class UserServiceRoleDTO { private String blockName; private String villageId; private String villageName; + private Map facilityData; public UserServiceRoleDTO(Integer userId, String name, String userName, Integer stateId, String stateName, Integer workingDistrictId, String workingDistrictName, Short serviceProviderId, Integer roleId, String roleName, Integer providerServiceMapId, Integer blockId, String blockName, String villageId, String villageName) { this.userId = userId; diff --git a/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java index dd10196a2..a52b68ca5 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java @@ -62,4 +62,32 @@ public interface FacilityLoginRepo extends CrudRepository getPeersAtFacility(@Param("facilityIDs") List facilityIDs, @Param("currentUserID") Integer currentUserID); + + // Supervisor: get mapped ASHAs with facility details + @Query(value = "SELECT DISTINCT u.UserID, u.FirstName, u.LastName, " + + "COALESCE(u.EmployeeID,'') AS employeeID, " + + "f.FacilityID, f.FacilityName, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "FROM asha_supervisor_mapping asm " + + "JOIN m_User u ON u.UserID = asm.ashaUserID " + + "JOIN m_facility f ON f.FacilityID = asm.facilityID " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "WHERE asm.supervisorUserID = :supervisorUserID " + + "AND asm.deleted = false AND u.Deleted = false AND f.Deleted = false", nativeQuery = true) + List getMappedAshasBySupervisor(@Param("supervisorUserID") Integer supervisorUserID); + + // CHO/ANM: get ASHAs at same facilities + @Query(value = "SELECT DISTINCT u.UserID, u.FirstName, u.LastName, " + + "COALESCE(u.EmployeeID,'') AS employeeID, " + + "f.FacilityID, f.FacilityName, " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "FROM m_UserServiceRoleMapping usrm " + + "JOIN m_User u ON u.UserID = usrm.UserID " + + "JOIN m_Role r ON r.RoleID = usrm.RoleID " + + "JOIN m_facility f ON f.FacilityID = usrm.FacilityID " + + "LEFT JOIN m_facilitytype ft ON ft.FacilityTypeID = f.FacilityTypeID " + + "WHERE usrm.FacilityID IN :facilityIDs " + + "AND r.RoleName = 'ASHA' " + + "AND usrm.Deleted = false AND u.Deleted = false AND f.Deleted = false", nativeQuery = true) + List getAshaListByFacilities(@Param("facilityIDs") List facilityIDs); } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java b/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java new file mode 100644 index 000000000..59d1f6901 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java @@ -0,0 +1,182 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.AshaSupervisorMapping; +import com.iemr.flw.repo.iemr.AshaSupervisorLoginRepo; +import com.iemr.flw.repo.iemr.FacilityLoginRepo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +@Service +public class FacilityDataService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); + + @Autowired + private AshaSupervisorLoginRepo ashaSupervisorLoginRepo; + + @Autowired + private FacilityLoginRepo facilityLoginRepo; + + public Map buildFacilityData(Integer userID, String roleName) { + Map result = new HashMap<>(); + result.put("location", emptyLocation()); + try { + if ("ASHA Supervisor".equalsIgnoreCase(roleName)) { + enrichAshaSupervisorData(result, userID); + } else if ("ASHA".equalsIgnoreCase(roleName)) { + enrichAshaData(result, userID); + } else { + enrichGeneralFacilityData(result, userID); + } + } catch (Exception e) { + logger.error("Error building facilityData for userID " + userID + ": " + e.getMessage(), e); + } + return result; + } + + private void enrichAshaSupervisorData(Map result, Integer supervisorUserID) { + ArrayList mappings = ashaSupervisorLoginRepo + .findBySupervisorUserIDAndDeletedFalse(supervisorUserID); + if (mappings == null || mappings.isEmpty()) return; + + Set facilityIDSet = new HashSet<>(); + for (AshaSupervisorMapping m : mappings) { + if (m.getFacilityID() != null) facilityIDSet.add(m.getFacilityID()); + } + if (facilityIDSet.isEmpty()) return; + List facilityIDs = new ArrayList<>(facilityIDSet); + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) return; + + result.put("location", buildLocation(facilityRows.get(0))); + + List> facilities = new ArrayList<>(); + for (Object[] row : facilityRows) { + Map facility = new HashMap<>(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + facilities.add(facility); + } + result.put("facilities", facilities); + + List ashaRows = facilityLoginRepo.getMappedAshasBySupervisor(supervisorUserID); + List> ashaList = buildAshaList(ashaRows); + result.put("ashaList", ashaList); + result.put("totalAshaCount", ashaList.size()); + } + + private void enrichAshaData(Map result, Integer ashaUserID) { + List facilityIDs = facilityLoginRepo.getUserFacilityIDs(ashaUserID); + if (facilityIDs == null || facilityIDs.isEmpty()) return; + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) return; + + result.put("location", buildLocation(facilityRows.get(0))); + + Object[] row = facilityRows.get(0); + Map facility = new HashMap<>(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + result.put("facility", facility); + + List supervisorRows = facilityLoginRepo.getSupervisorForAsha(ashaUserID); + if (supervisorRows != null && !supervisorRows.isEmpty()) { + Object[] sRow = supervisorRows.get(0); + Map supervisor = new HashMap<>(); + supervisor.put("userId", sRow[0]); + supervisor.put("fullName", fullName(sRow[1], sRow[2])); + supervisor.put("mobile", str(sRow[3])); + result.put("supervisor", supervisor); + } else { + result.put("supervisor", null); + } + + List peerRows = facilityLoginRepo.getPeersAtFacility(facilityIDs, ashaUserID); + List> peers = new ArrayList<>(); + if (peerRows != null) { + for (Object[] pRow : peerRows) { + Map peer = new HashMap<>(); + peer.put("userId", pRow[0]); + peer.put("fullName", fullName(pRow[1], pRow[2])); + peer.put("role", str(pRow[3])); + peers.add(peer); + } + } + result.put("peersAtFacility", peers); + } + + private void enrichGeneralFacilityData(Map result, Integer userID) { + List facilityIDs = facilityLoginRepo.getUserFacilityIDs(userID); + if (facilityIDs == null || facilityIDs.isEmpty()) return; + + List facilityRows = facilityLoginRepo.getFacilityDetails(facilityIDs); + if (facilityRows == null || facilityRows.isEmpty()) return; + + result.put("location", buildLocation(facilityRows.get(0))); + + List> facilities = new ArrayList<>(); + for (Object[] row : facilityRows) { + Map facility = new HashMap<>(); + facility.put("facilityId", row[0]); + facility.put("facilityName", str(row[1])); + facility.put("facilityType", str(row[9])); + facilities.add(facility); + } + result.put("facilities", facilities); + + List ashaRows = facilityLoginRepo.getAshaListByFacilities(facilityIDs); + List> ashaList = buildAshaList(ashaRows); + result.put("ashaList", ashaList); + result.put("totalAshaCount", ashaList.size()); + } + + private List> buildAshaList(List rows) { + List> list = new ArrayList<>(); + if (rows == null) return list; + for (Object[] row : rows) { + Map asha = new HashMap<>(); + asha.put("userId", row[0]); + asha.put("fullName", fullName(row[1], row[2])); + asha.put("employeeId", str(row[3]).isEmpty() ? null : str(row[3])); + asha.put("facilityId", row[4]); + asha.put("facilityName", str(row[5])); + asha.put("facilityType", str(row[6])); + list.add(asha); + } + return list; + } + + private Map buildLocation(Object[] facilityRow) { + Map location = new HashMap<>(); + location.put("state", str(facilityRow[3])); + location.put("district", str(facilityRow[5])); + location.put("blockOrUlb", str(facilityRow[7])); + location.put("locationType", str(facilityRow[8])); + return location; + } + + private Map emptyLocation() { + Map location = new HashMap<>(); + location.put("state", ""); + location.put("district", ""); + location.put("blockOrUlb", ""); + location.put("locationType", ""); + return location; + } + + private String str(Object val) { + return val != null ? val.toString() : ""; + } + + private String fullName(Object first, Object last) { + return (str(first) + " " + str(last)).trim(); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java index 4e680a1df..60ae973e7 100644 --- a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java @@ -12,12 +12,17 @@ public class UserServiceImpl implements UserService { private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); + @Autowired private UserServiceRoleRepo userServiceRoleRepo; + @Autowired + private FacilityDataService facilityDataService; + public UserServiceRoleDTO getUserDetail(Integer userId) { logger.info("calling getUserRole for userId: " + userId); UserServiceRoleDTO userRole = userServiceRoleRepo.getUserRole(userId).get(0); + userRole.setFacilityData(facilityDataService.buildFacilityData(userId, userRole.getRoleName())); return userRole; } } From 0a9ecae0cb4d446cd5361a280ae5976f5219a34a Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Mon, 18 May 2026 12:51:47 +0530 Subject: [PATCH 285/450] fix(security): replace extractUsername(token) with DB lookup across FLW-API (#241) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All usages of jwtUtil.extractUsername (which reads PII from JWT sub claim) replaced with userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token)). Username is now fetched from DB using userId — token PII not used anywhere in FLW-API. Affects BeneficiaryService, MaternalHealth, DiseaseControl, Campaign, IRSRound, SupervisorDashboard. Co-authored-by: Claude Sonnet 4.6 --- .../java/com/iemr/flw/controller/IRSRoundController.java | 7 ++++++- .../iemr/flw/service/impl/BeneficiaryServiceImpl.java | 9 +++++++-- .../com/iemr/flw/service/impl/CampaignServiceImpl.java | 6 +++--- .../iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- .../iemr/flw/service/impl/MaternalHealthServiceImpl.java | 4 ++-- .../flw/service/impl/SupervisorDashboardServiceImpl.java | 2 +- 6 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IRSRoundController.java b/src/main/java/com/iemr/flw/controller/IRSRoundController.java index f138a0eff..13193e05e 100644 --- a/src/main/java/com/iemr/flw/controller/IRSRoundController.java +++ b/src/main/java/com/iemr/flw/controller/IRSRoundController.java @@ -3,6 +3,7 @@ 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.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.IRSRoundService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; @@ -28,6 +29,9 @@ public class IRSRoundController { @Autowired private JwtUtil jwtUtil; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + @PostMapping(value = "/add") public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto,@RequestHeader("jwtToken") String token) { Map response = new LinkedHashMap<>(); @@ -37,7 +41,8 @@ public ResponseEntity> addRound(@RequestBody IRSRoundListDTO response.put("statusCode", 401); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response) ; } - List s = irsRoundService.addRounds(dto.getRounds(),jwtUtil.extractUserId(token),jwtUtil.extractUsername(token)); + Integer userId = jwtUtil.extractUserId(token); + List s = irsRoundService.addRounds(dto.getRounds(), userId, userServiceRoleRepo.getUserNamedByUserId(userId)); if (s.size() != 0) { Map data = new HashMap<>(); data.put("entries", s); 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 fdfb20a95..dec2ad7e2 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -581,8 +581,13 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO @Override public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { - - List visits = eyeCheckUpVisitRepo.findByCreatedBy(jwtUtil.extractUsername(token)); + String createdBy = null; + try { + createdBy = userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token)); + } catch (Exception e) { + logger.error("Error extracting userId from token: " + e.getMessage()); + } + List visits = eyeCheckUpVisitRepo.findByCreatedBy(createdBy); return visits.stream().map(v -> { EyeCheckupRequestDTO dto = new EyeCheckupRequestDTO(); diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 620ae6c62..60306e0bc 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -63,7 +63,7 @@ public List saveOrsCampaign(List orsCampaignDTO, St List campaignOrsRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = jwtUtil.extractUsername(token); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId); for (OrsCampaignDTO campaignDTO : orsCampaignDTO) { if (campaignDTO.getFields() == null) { @@ -141,7 +141,7 @@ public List savePolioCampaign(List polioCa List campaignPolioRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = jwtUtil.extractUsername(token); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId); for (PolioCampaignDTO campaignDTO : polioCampaignDTOs) { if (campaignDTO.getFields() == null) { @@ -213,7 +213,7 @@ public List saveFilariasisCampaign(List campaignPolioRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = jwtUtil.extractUsername(token); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId); for (FilariasisCampaignDTO campaignDTO : filariasisCampaignDTOS) { if (campaignDTO.getFields() == null) { diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 8d5db86d9..6335d8e6d 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1141,7 +1141,7 @@ public List saveChronicDiseaseVisit( entity.setDiagnosisCodes(dto.getDiagnosisCodes()); entity.setFormDataJson(dto.getFormDataJson()); entity.setUserID(jwtUtil.extractUserId(token)); - entity.setCreatedBy(jwtUtil.extractUsername(token)); + entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token))); entity.setUpdatedBy(jwtUtil.extractUserId(token)); 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 52de9aa68..5bed940dd 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -496,8 +496,8 @@ public String saveANCVisitQuestions(List dtos, String aut entity.setMalpresentation(yesNoToBoolean(fields.getMalpresentation())); entity.setUserId(jwtUtil.extractUserId(authorization)); - entity.setCreatedBy(jwtUtil.extractUsername(authorization)); - entity.setUpdatedBy(jwtUtil.extractUsername(authorization)); + entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); + entity.setUpdatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); entities.add(entity); } diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index fadc4b460..c1850f383 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -370,7 +370,7 @@ public int updateApprovalStatus(Integer ashaId, Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); - String ashaSupervisorUsername = jwtUtil.extractUsername(token); + String ashaSupervisorUsername = userServiceRoleRepo.getUserNamedByUserId(ashaSupervisorUserId); if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { int totalUpdated = 0; From fc793c9acac7b7f800df2b72adb39ab868be4a24 Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Tue, 19 May 2026 10:20:14 +0530 Subject: [PATCH 286/450] feat: add mobile and employeeId to peersAtFacility, ashaList and supervisor in facilityData (#242) Co-authored-by: Claude Sonnet 4.6 --- .../com/iemr/flw/repo/iemr/FacilityLoginRepo.java | 13 +++++++++---- .../iemr/flw/service/impl/FacilityDataService.java | 4 ++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java index a52b68ca5..2f956b3b3 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/FacilityLoginRepo.java @@ -35,7 +35,8 @@ public interface FacilityLoginRepo extends CrudRepository getFacilityDetails(@Param("facilityIDs") List facilityIDs); // ASHA login: get supervisor details - @Query(value = "SELECT asm.supervisorUserID, u.FirstName, u.LastName, u.ContactNo " + @Query(value = "SELECT asm.supervisorUserID, u.FirstName, u.LastName, u.ContactNo, " + + "COALESCE(u.EmployeeID,'') AS employeeID " + "FROM asha_supervisor_mapping asm " + "JOIN m_User u ON u.UserID = asm.supervisorUserID " + "WHERE asm.ashaUserID = :ashaUserID AND asm.deleted = false " @@ -53,7 +54,9 @@ public interface FacilityLoginRepo extends CrudRepository getVillagesForFacilities(@Param("facilityIDs") List facilityIDs); // ASHA login: get peers at same facility (ANM, CHO, etc.) - @Query(value = "SELECT DISTINCT usrm.UserID, u.FirstName, u.LastName, r.RoleName " + @Query(value = "SELECT DISTINCT usrm.UserID, u.FirstName, u.LastName, r.RoleName, " + + "COALESCE(u.EmployeeID,'') AS employeeID, " + + "COALESCE(u.ContactNo,'') AS mobile " + "FROM m_UserServiceRoleMapping usrm " + "JOIN m_User u ON u.UserID = usrm.UserID " + "JOIN m_Role r ON r.RoleID = usrm.RoleID " @@ -67,7 +70,8 @@ List getPeersAtFacility(@Param("facilityIDs") List facilityID @Query(value = "SELECT DISTINCT u.UserID, u.FirstName, u.LastName, " + "COALESCE(u.EmployeeID,'') AS employeeID, " + "f.FacilityID, f.FacilityName, " - + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName, " + + "COALESCE(u.ContactNo,'') AS mobile " + "FROM asha_supervisor_mapping asm " + "JOIN m_User u ON u.UserID = asm.ashaUserID " + "JOIN m_facility f ON f.FacilityID = asm.facilityID " @@ -80,7 +84,8 @@ List getPeersAtFacility(@Param("facilityIDs") List facilityID @Query(value = "SELECT DISTINCT u.UserID, u.FirstName, u.LastName, " + "COALESCE(u.EmployeeID,'') AS employeeID, " + "f.FacilityID, f.FacilityName, " - + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName " + + "COALESCE(ft.FacilityTypeName,'') AS facilityTypeName, " + + "COALESCE(u.ContactNo,'') AS mobile " + "FROM m_UserServiceRoleMapping usrm " + "JOIN m_User u ON u.UserID = usrm.UserID " + "JOIN m_Role r ON r.RoleID = usrm.RoleID " diff --git a/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java b/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java index 59d1f6901..2e4f9556d 100644 --- a/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java +++ b/src/main/java/com/iemr/flw/service/impl/FacilityDataService.java @@ -94,6 +94,7 @@ private void enrichAshaData(Map result, Integer ashaUserID) { supervisor.put("userId", sRow[0]); supervisor.put("fullName", fullName(sRow[1], sRow[2])); supervisor.put("mobile", str(sRow[3])); + supervisor.put("employeeId", str(sRow[4]).isEmpty() ? null : str(sRow[4])); result.put("supervisor", supervisor); } else { result.put("supervisor", null); @@ -107,6 +108,8 @@ private void enrichAshaData(Map result, Integer ashaUserID) { peer.put("userId", pRow[0]); peer.put("fullName", fullName(pRow[1], pRow[2])); peer.put("role", str(pRow[3])); + peer.put("employeeId", str(pRow[4]).isEmpty() ? null : str(pRow[4])); + peer.put("mobile", str(pRow[5]).isEmpty() ? null : str(pRow[5])); peers.add(peer); } } @@ -149,6 +152,7 @@ private List> buildAshaList(List rows) { asha.put("facilityId", row[4]); asha.put("facilityName", str(row[5])); asha.put("facilityType", str(row[6])); + asha.put("mobile", str(row[7]).isEmpty() ? null : str(row[7])); list.add(asha); } return list; From 3fca2eaa8b356e45bb7da0a2f6808a2d80cecf82 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 21 May 2026 13:12:40 +0530 Subject: [PATCH 287/450] incentive chnages for release 3.8.2 --- .../iemr/flw/repo/iemr/ChildRegisterRepo.java | 4 + .../flw/service/IncentiveLogicService.java | 4 + .../flw/service/impl/ChildServiceImpl.java | 110 ++++++++++++++++++ .../flw/service/impl/IncentiveLogicImpl.java | 66 +++++++++++ .../service/impl/IncentiveServiceImpl.java | 34 +++++- 5 files changed, 217 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java index 7d10f5956..499d7a5c9 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java @@ -18,4 +18,8 @@ List getChildDetailsForUser(@Param("userId") String userId, // @Query(value = "Select * from db_identity.i_cbacdetails where beneficiaryRegId = :benRegId and createdDate = :createdDate limit 1", nativeQuery = true) ChildRegister findChildRegisterByBenIdAndCreatedDate(Long benRegId, Timestamp createdDate); + + Long countByBenId(Long benId); + + List findByBenIdOrderByCreatedDateAsc(Long benId); } diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 1b3529b1e..7ef9d2a7a 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -3,6 +3,7 @@ import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import org.springframework.stereotype.Service; +import java.sql.Timestamp; import java.util.Date; public interface IncentiveLogicService { @@ -15,4 +16,7 @@ public interface IncentiveLogicService { public IncentiveActivityRecord incentiveForClusterMeeting(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); public IncentiveActivityRecord incentiveForAttendingVhsnc(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index 0ce841e83..eeea84054 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -2,18 +2,24 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.identity.RMNCHBeneficiaryDetailsRmnch; import com.iemr.flw.domain.iemr.ChildRegister; +import com.iemr.flw.domain.iemr.IncentiveActivityRecord; +import com.iemr.flw.domain.iemr.UserServiceRole; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.ChildRegisterDTO; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.ChildRegisterRepo; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.ChildService; +import com.iemr.flw.service.IncentiveLogicService; 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.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -28,6 +34,12 @@ public class ChildServiceImpl implements ChildService { @Autowired private BeneficiaryRepo beneficiaryRepo; + @Autowired + private IncentiveLogicService incentiveLogicService; + + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; + public String getByUserId(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); @@ -68,6 +80,104 @@ public String save(List childRegisterDTOs) throws Exception { listToBeSaved.add(childRegister); }); childRepo.saveAll(listToBeSaved); + for (ChildRegister childRegister : listToBeSaved) { + processFirstChildIncentive(childRegister); + } + for (ChildRegister childRegister : listToBeSaved) { + processSecondChildGapIncentive(childRegister); + } return "no of child details saved: " + childRegisterDTOs.size(); } + + public void processFirstChildIncentive(ChildRegister childRegister) { + + Long benId = childRegister.getBenId(); + + RMNCHBeneficiaryDetailsRmnch beneficiary = + beneficiaryRepo.findById(benId).orElse(null); + + if (beneficiary == null || beneficiary.getDateMarriage() == null) { + return; + } + + // First child validation + Long childCount = childRepo.countByBenId(benId); + + if (childCount != 1) { + return; + } + + Timestamp marriageDate = beneficiary.getDateMarriage(); + + // Temporary: using createdDate as child DOB + Timestamp childBirthDate = childRegister.getCreatedDate(); + + long diffMillis = childBirthDate.getTime() - marriageDate.getTime(); + + long days = diffMillis / (1000 * 60 * 60 * 24); + + // >= 2 years + if (days >= 730) { + + Integer userId = + userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); + + incentiveLogicService.incentiveForChildBirthGap( + benId, + childBirthDate, + childBirthDate, + userId + ); + } + } + + private void processSecondChildGapIncentive(ChildRegister currentChild) { + + Long benId = currentChild.getBenId(); + + // Total children count + Long childCount = childRepo.countByBenId(benId); + + // Applicable only for second child + if (childCount != 2) { + return; + } + + List children = + childRepo.findByBenIdOrderByCreatedDateAsc(benId); + + if (children.size() < 2) { + return; + } + + // First child + ChildRegister firstChild = children.get(0); + + // Second child + ChildRegister secondChild = children.get(1); + + Timestamp firstChildDob = firstChild.getCreatedDate(); + + Timestamp secondChildDob = secondChild.getCreatedDate(); + + long diffMillis = + secondChildDob.getTime() - firstChildDob.getTime(); + + long days = diffMillis / (1000 * 60 * 60 * 24); + + // >= 3 years + if (days >= 1095) { + + Integer userId = + userServiceRoleRepo.getUserIdByName( + currentChild.getCreatedBy()); + + incentiveLogicService.incentiveForSecondChildGap( + benId, + secondChildDob, + secondChildDob, + userId + ); + } + } } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index c564fab72..b59c1314d 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -85,6 +85,7 @@ public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed( } } + @Override public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( Long benId, @@ -228,6 +229,71 @@ public IncentiveActivityRecord incentiveForAttendingVhsnc(Long benId, Date treat } } + @Override + public IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "FP_DELAY_2Y"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check FP_DELAY_2Y Incentive Exception: ", e); + return null; + } + } + + @Override + public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "1st_2nd_CHILD_GAP"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + secondChildDob, + secondChildDob1, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check FP_DELAY_2Y Incentive Exception: ", e); + return null; + } } + + + @Override public IncentiveActivityRecord incentiveForIdentificationLeprosy(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId) { try { 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 4e5f90867..785bb7c53 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -164,9 +164,15 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { try { - if (request.getVillageID() != StateCode.CG.getStateCode()) { + + if (request.getVillageID().equals(StateCode.AM.getStateCode())) { checkMonthlyAshaIncentive(request.getAshaId()); } + if(request.getVillageID().equals(StateCode.CG.getStateCode())){ + checkMonthlyAshaIncentiveForCg(request.getAshaId()); + + } + } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); } @@ -610,6 +616,32 @@ private void checkMonthlyAshaIncentive(Integer ashaId) { } + private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { + try { + String userName = userRepo.getUserNamedByUserId(ashaId); + + IncentiveActivity MONTHLY_HONORARIUM = incentivesRepo.findIncentiveMasterByNameAndGroup("MONTHLY_HONORARIUM", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity MITANIN_REGISTER_5_INFO_FILL = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER_5_INFO_FILL", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity MITANIN_REGISTER = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER", GroupName.ACTIVITY.getDisplayName()); + if (MONTHLY_HONORARIUM != null) { + addMonthlyAshaIncentiveRecord(MONTHLY_HONORARIUM, ashaId,userName); + } + if (MITANIN_REGISTER_5_INFO_FILL != null) { + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER_5_INFO_FILL, ashaId,userName); + + } + + if (MITANIN_REGISTER != null) { + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER, 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()); From dba51c1795eaae1dc4b0061621828b6afda2fffe Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 21 May 2026 17:01:38 +0530 Subject: [PATCH 288/450] incentive chnages for release 3.8.2 --- .../flw/controller/BeneficiaryController.java | 88 ++++++++++++++++--- .../flw/controller/ChildCareController.java | 19 ++-- .../iemr/flw/service/ChildCareService.java | 2 +- .../flw/service/IFAFormSubmissionService.java | 2 +- .../service/impl/ChildCareServiceImpl.java | 71 +++++++++------ .../impl/IFAFormSubmissionServiceImpl.java | 38 ++++++-- .../service/impl/IncentiveServiceImpl.java | 17 ++-- 7 files changed, 171 insertions(+), 66 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index d7921ff07..ee5730959 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -40,10 +40,13 @@ public class BeneficiaryController { @Autowired private MdaFormSubmissionService mdaFormSubmissionService; + @Autowired + private JwtUtil jwtUtil; + @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 { @@ -65,8 +68,9 @@ 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) { + public ResponseEntity saveEyeSurgery(@RequestBody List eyeCheckupRequestDTOS, @RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("Eye Checkup Save Request: {}", eyeCheckupRequestDTOS); @@ -77,7 +81,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); } - String responseObject = beneficiaryService.saveEyeCheckupVsit(eyeCheckupRequestDTOS,token); + String responseObject = beneficiaryService.saveEyeCheckupVsit(eyeCheckupRequestDTOS, token); if (responseObject != null) { response.put("statusCode", HttpStatus.OK.value()); @@ -98,14 +102,13 @@ public ResponseEntity saveEyeSurgery(@RequestBody List } - @RequestMapping(value = {"/eye_surgery/getAll"}, method = RequestMethod.POST) - public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler request,@RequestHeader(value = "JwtToken") String token) { + 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); + List responseObject = beneficiaryService.getEyeCheckUpVisit(request, token); if (responseObject != null && !responseObject.isEmpty()) { response.put("statusCode", HttpStatus.OK.value()); @@ -125,13 +128,70 @@ public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler requ } } - @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/saveAll", method = RequestMethod.POST) + public ResponseEntity saveIfaFormData( + @RequestBody List requests, + @RequestHeader(value = "JwtToken") String token) { + + Map response = new LinkedHashMap<>(); + + logger.info("IFA Save Request: {}", requests); + + try { + + if (requests == null || requests.isEmpty()) { + + response.put("statusCode", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Request body cannot be empty"); + + return ResponseEntity + .status(HttpStatus.BAD_REQUEST) + .body(response); + } + if (token != null) { + String message = + ifaFormSubmissionService.saveFormData(requests, jwtUtil.extractUserId(token)); + + if (message != null) { + + response.put("statusCode", HttpStatus.OK.value()); + response.put("message", message); + + 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); + } + } else { + response.put("statusCode", HttpStatus.UNAUTHORIZED.value()); + response.put("message", "UNAUTHORIZED"); + + return ResponseEntity + .status(HttpStatus.UNAUTHORIZED) + .body(response); + } + + + } catch (Exception e) { + + logger.error("Error saving IFA records:", e); + + response.put("statusCode", 5000); + response.put("errorMessage", e.getMessage()); + + return ResponseEntity + .status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(response); + } } - @RequestMapping(value = "ifa/getAll",method = RequestMethod.POST) + @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)); @@ -139,15 +199,15 @@ public ResponseEntity getFormData(@RequestBody GetBenRequestHandler getBenReq @RequestMapping(value = "/mda/saveAll", method = RequestMethod.POST) public ResponseEntity saveFormData(@RequestBody List requests, - @RequestHeader(value = "Authorization") String authorization) { + @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") ; + @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/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 36da3ba72..8ef128f02 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -10,11 +10,13 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; import jakarta.mail.Multipart; +import org.checkerframework.checker.units.qual.A; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -37,6 +39,9 @@ public class ChildCareController { @Autowired private ChildCareService childCareService; + @Autowired + private JwtUtil jwtUtil; + @Operation(summary = "save HBYC details") @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) public String saveHbycRecords(@RequestBody List hbycDTOs, @@ -92,19 +97,21 @@ public String getHbycRecords(@RequestBody GetBenRequestHandler requestDTO) { @PostMapping("/hbncVisit/saveAll") public String saveHBNCVisit(@RequestBody List hbncRequestDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "jwtToken") String jwtToken) { OutputResponse response = new OutputResponse(); try { if (!hbncRequestDTOs.isEmpty()) { logger.info("Saving HBNC details at: " + new Timestamp(System.currentTimeMillis())); + if(jwtToken!=null){ + String result = childCareService.saveHBNCDetails(hbncRequestDTOs,jwtUtil.extractUserId(jwtToken)); // <-- actual save - String result = childCareService.saveHBNCDetails(hbncRequestDTOs); // <-- actual save + if (result != null) + response.setResponse(result); + else + response.setError(500, "Failed to save HBNC visit data."); + } - if (result != null) - response.setResponse(result); - else - response.setError(500, "Failed to save HBNC visit data."); } else { response.setError(400, "Empty request list."); } diff --git a/src/main/java/com/iemr/flw/service/ChildCareService.java b/src/main/java/com/iemr/flw/service/ChildCareService.java index bbd5c96f2..e82090b75 100644 --- a/src/main/java/com/iemr/flw/service/ChildCareService.java +++ b/src/main/java/com/iemr/flw/service/ChildCareService.java @@ -15,7 +15,7 @@ public interface ChildCareService { List getHBNCDetails(GetBenRequestHandler dto); - String saveHBNCDetails(List hbncRequestDTOs); + String saveHBNCDetails(List hbncRequestDTOs,Integer userId); List getChildVaccinationDetails(GetBenRequestHandler dto); diff --git a/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java b/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java index 1ecd338d1..d94fbd682 100644 --- a/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java +++ b/src/main/java/com/iemr/flw/service/IFAFormSubmissionService.java @@ -9,6 +9,6 @@ import java.util.List; @Service public interface IFAFormSubmissionService { - String saveFormData(List requests); + String saveFormData(List requests,Integer userId); List getFormData(GetBenRequestHandler getBenRequestHandler); } 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 27a18653f..02597ddea 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -7,9 +7,11 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; 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.ChildCareService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import jakarta.persistence.EntityNotFoundException; import org.aspectj.weaver.ast.Or; @@ -79,6 +81,9 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private IncentivePendingActivityRepository incentivePendingActivityRepository; + @Autowired + private UserService userService; + @Override public String registerHBYC(List hbycDTOs) { @@ -294,7 +299,7 @@ private String convert(String value) { @Override - public String saveHBNCDetails(List hbncRequestDTOs) { + public String saveHBNCDetails(List hbncRequestDTOs, Integer userId) { try { List hbncList = new ArrayList<>(); @@ -324,7 +329,7 @@ public String saveHBNCDetails(List hbncRequestDTOs) { hbncVisitRepo.saveAll(hbncList); - checkAndAddHbncIncentives(hbncList); + checkAndAddHbncIncentives(hbncList, userId); logger.info("HBNC details saved"); @@ -576,7 +581,7 @@ public String saveOrsDistributionDetails(List orsDistributio orsDistribution.setId(orsDistributionDTO.getId()); orsDistribution.setBeneficiaryId(orsDistributionDTO.getBeneficiaryId()); orsDistribution.setNumOrsPackets(orsDistributionDTO.getFields().getNum_ors_packets().toString()); - if(orsDistributionDTO.getFields().getNum_under5_children()!=null){ + if (orsDistributionDTO.getFields().getNum_under5_children() != null) { orsDistribution.setChildCount(orsDistributionDTO.getFields().getNum_under5_children().toString()); } @@ -616,11 +621,11 @@ public List getOrdDistrubtion(GetBenRequestHandler r orsDistributionResponseDTO.setId(orsDistribution.getId()); orsDistributionResponseDTO.setBeneficiaryId(orsDistribution.getBeneficiaryId()); orsDistributionResponseDTO.setHouseHoldId(orsDistribution.getHouseholdId()); - if(orsDistribution.getNumOrsPackets()!=null){ + if (orsDistribution.getNumOrsPackets() != null) { orsDistributionResponseListDTO.setNum_ors_packets(orsDistribution.getNumOrsPackets().toString()); } - if(orsDistribution.getChildCount()!=null){ + if (orsDistribution.getChildCount() != null) { orsDistributionResponseListDTO.setNum_under5_children(orsDistribution.getChildCount().toString()); } @@ -799,37 +804,43 @@ private void checkAndAddHbyncIncentives(List hbycList) { } - private void checkAndAddHbncIncentives(List hbncVisits) { + private void checkAndAddHbncIncentives(List hbncVisits, Integer userId) { + Integer stateCode = userService.getUserDetail(userId).getStateId(); 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()); + if (stateCode.equals(StateCode.AM)) { + if (hbncVisit.getVisit_day().equals("42nd Day")) { + IncentiveActivity visitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS_CH"); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); - } - logger.info("getDischarged_from_sncu" + hbncVisit.getDischarged_from_sncu()); + } + 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()); - 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"); - 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"); + } } - 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"); + if (stateCode.equals(StateCode.CG.getStateCode())) { + if (hbncVisit.getVisit_day().equals("7th Day")) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS_CH"); + + } } @@ -938,13 +949,14 @@ record = new IncentiveActivityRecord(); record.setIsEligible(false); } else { record.setIsEligible(false); - updatePendingActivity(hbncVisit.getAshaId(),hbncVisit.getId(),record.getActivityId(),immunizationActivity.getId()); + updatePendingActivity(hbncVisit.getAshaId(), hbncVisit.getId(), record.getActivityId(), immunizationActivity.getId()); } record.setAmount(Long.valueOf(immunizationActivity.getRate())); recordRepo.save(record); } } + private void updatePendingActivity(Integer userId, Long recordId, Long activityId, Long mIncentiveId) { IncentivePendingActivity incentivePendingActivity = new IncentivePendingActivity(); incentivePendingActivity.setActivityId(activityId); @@ -956,7 +968,8 @@ private void updatePendingActivity(Integer userId, Long recordId, Long activityI } } - public HbncVisit updateHbncFromFileUpload(MultipartFile[] dischargeSncuImage,Long incentiveRecordId,Long id) throws JsonProcessingException { + + public HbncVisit updateHbncFromFileUpload(MultipartFile[] dischargeSncuImage, Long incentiveRecordId, Long id) throws JsonProcessingException { HbncVisit existingHbncVisit = hbncVisitRepo.findById(id) .orElseThrow(() -> new EntityNotFoundException("Meeting not found: " + id)); @@ -976,6 +989,7 @@ public HbncVisit updateHbncFromFileUpload(MultipartFile[] dischargeSncuImage,Lon } return hbncVisitRepo.save(existingHbncVisit); } + private void updateIncentive(Long id) { Optional optionalRecord = recordRepo.findById(id); @@ -995,6 +1009,7 @@ private String convertToBase64(MultipartFile file) { throw new RuntimeException("Failed to convert image to Base64: " + file.getOriginalFilename(), e); } } + private void createIncentiveRecordforHbyncVisit(HbycChildVisit data, Long benId, IncentiveActivity immunizationActivity, String createdBy) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index e47712294..380ed5118 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -9,12 +9,15 @@ import com.iemr.flw.dto.iemr.IFAFormSubmissionRequest; import com.iemr.flw.dto.iemr.IFAFormSubmissionResponse; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.StateCode; 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.service.UserService; import com.iemr.flw.utils.JwtUtil; +import jakarta.persistence.criteria.CriteriaBuilder; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -42,8 +45,11 @@ public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { @Autowired private IncentiveRecordRepo incentiveRecordRepo; + @Autowired + private UserService userService; + @Override - public String saveFormData(List requests) { + public String saveFormData(List requests, Integer userId) { try { List entities = new ArrayList<>(); for (IFAFormSubmissionRequest req : requests) { @@ -60,7 +66,7 @@ public String saveFormData(List requests) { entities.add(data); } repository.saveAll(entities); - checkIFAIncentive(entities); + checkIFAIncentive(entities,userId); return "Form data saved successfully"; } catch (Exception e) { e.printStackTrace(); @@ -68,14 +74,30 @@ public String saveFormData(List requests) { } } - private void checkIFAIncentive(List entities) { - IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); + private void checkIFAIncentive(List entities,Integer userId) { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + if(stateCode.equals(StateCode.AM.getStateCode())){ + IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); + + if(incentiveActivityAM!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); + + }); + } + + } + + if(stateCode.equals(StateCode.CG.getStateCode())){ + IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); - if(incentiveActivityAM!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); + if(incentiveActivityCG!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityCG); + + }); + } - }); } } 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 785bb7c53..c3bf36da4 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -15,7 +15,9 @@ import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveService; import com.iemr.flw.service.MaaMeetingService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; +import jakarta.persistence.criteria.CriteriaBuilder; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,6 +62,9 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private CbacIemrDetailsRepo cbacIemrDetailsRepo; + @Autowired + private UserService userService; + // ================= MASTER SAVE ================= @Override @@ -163,12 +168,13 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + Integer stateCode = userService.getUserDetail(request.getAshaId()).getStateId(); try { - if (request.getVillageID().equals(StateCode.AM.getStateCode())) { + if (stateCode.equals(StateCode.AM.getStateCode())) { checkMonthlyAshaIncentive(request.getAshaId()); } - if(request.getVillageID().equals(StateCode.CG.getStateCode())){ + if(stateCode.equals(StateCode.CG.getStateCode())){ checkMonthlyAshaIncentiveForCg(request.getAshaId()); } @@ -185,12 +191,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { logger.error("Error in incentiveOfNcdReferal: ", e); } - Integer villageID = request.getVillageID(); - boolean isCG = villageID != null && villageID.intValue() == StateCode.CG.getStateCode(); - - if (!isCG) { - checkMonthlyAshaIncentive(request.getAshaId()); - } + boolean isCG = stateCode != null && stateCode.equals(StateCode.CG.getStateCode()); // Step 1: Fetch all records for this ASHA List entities = recordRepo.findRecordsByAsha(request.getAshaId()); From 1461e1a3cc3397aae216f449f0502d92cffb3dbd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 22 May 2026 00:01:43 +0530 Subject: [PATCH 289/450] incentive chnages for release 3.8.2 --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) 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 c3bf36da4..406d4ac58 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -145,13 +145,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { ? mapping.getHindiActivityDescription() : mapping.getDescription()); - } else { - // default "en" + } else if ("en".equals(langCode)){ dto.setDescription(inc.getDescription()); } - } else { - dto.setGroupName(inc.getGroup()); } return dto; From 5903e245942ccd9bd4788a7ef874e6b5b7687777 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 22 May 2026 00:10:19 +0530 Subject: [PATCH 290/450] incentive chnages for release 3.8.2 --- .../iemr/flw/service/impl/IncentiveServiceImpl.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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 406d4ac58..3672cd2c0 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -145,10 +145,19 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { ? mapping.getHindiActivityDescription() : mapping.getDescription()); - } else if ("en".equals(langCode)){ + } else { + // default "en" dto.setDescription(inc.getDescription()); } + } else { + if(isCG){ + dto.setGroupName(""); + + }else { + dto.setGroupName(inc.getGroup()); + + } } return dto; From 2dd669eae17f97aee71185ea525c09851e33b50a Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 25 May 2026 17:39:08 +0530 Subject: [PATCH 291/450] fix incentive issue for production (#243) * fix incentive issue for production * fix incentive issue for production * fix incentive issue for production * fix incentive issue for production --- .../flw/service/impl/IncentiveServiceImpl.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 4e5f90867..c049a1d16 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -245,6 +245,21 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); } + if(entry.getAshaId()!=null){ + if (entry.getCreatedBy() == null) { + entry.setCreatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + } + + if (entry.getUpdatedBy() == null) { + entry.setUpdatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + } + + if (entry.getIsEligible() == null) { + entry.setIsEligible(true); + } + } + + } return modelMapper.map(entry, IncentiveRecordDTO.class); }).collect(Collectors.toList()); From eb2cebe6475556351e070676f16652784ae4e52c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 12:05:45 +0530 Subject: [PATCH 292/450] fix incentive issue on cg --- .../flw/service/IncentiveLogicService.java | 2 + .../service/impl/BeneficiaryServiceImpl.java | 11 + .../impl/DiseaseControlServiceImpl.java | 203 ++++++++++-------- .../flw/service/impl/IncentiveLogicImpl.java | 46 +++- 4 files changed, 168 insertions(+), 94 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 7ef9d2a7a..c00ff0c13 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -19,4 +19,6 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatmentStartDate, Date treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId); + + IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); } 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 dec2ad7e2..5c4e1a71a 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -2,6 +2,7 @@ import java.math.BigInteger; import java.sql.Date; +import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.Period; @@ -21,6 +22,7 @@ import com.iemr.flw.dto.iemr.EyeCheckupRequestDTO; import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.utils.JwtUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,6 +97,9 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Autowired private UserServiceRoleRepo userRepo; + @Autowired + private IncentiveLogicService incentiveLogicService; + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -565,6 +570,12 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO visit.setFollowUpStatus(f.getFollow_up_status()); eyeCheckUpVisitRepo.save(visit); + if(visit.getReferredTo().equals("Govt Public Facility")){ + LocalDate localDate = visit.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + } } return "Eye checkup data saved successfully."; diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 6335d8e6d..cc28f4364 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -25,15 +25,16 @@ 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.masterEnum.StateCode; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.DiseaseControlService; import com.iemr.flw.service.IncentiveLogicService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.exception.IEMRException; import jakarta.transaction.Transactional; @@ -93,6 +94,9 @@ public class DiseaseControlServiceImpl implements DiseaseControlService { @Autowired private IncentiveLogicService incentiveLogicService; + @Autowired + private UserService userService; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @@ -492,6 +496,8 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { dto.setReferredTo(disease.getReferredTo()); dto.setOtherReferredFacility(disease.getOtherReferredFacility()); dto.setRemarks(disease.getRemarks()); + dto.setMalariaSlideTestType(disease.getMalariaSlideTestType()); + dto.setMalariaTestType(disease.getMalariaTestType()); dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); dto.setUserId(disease.getUserId()); dto.setDiseaseTypeId(disease.getDiseaseTypeId()); @@ -912,6 +918,8 @@ private ScreeningMalaria saveMalariaDisease(DiseaseMalariaDTO requestData) { diseaseScreening.setSlideTestPv(requestData.getSlideTestPv()); diseaseScreening.setDateOfSlideTest(requestData.getDateOfSlideTest()); diseaseScreening.setSlideNo(requestData.getSlideNo()); + diseaseScreening.setMalariaTestType(requestData.getMalariaTestType()); + diseaseScreening.setMalariaSlideTestType(requestData.getMalariaSlideTestType()); diseaseScreening.setReferredTo(requestData.getReferredTo()); diseaseScreening.setOtherReferredFacility(requestData.getOtherReferredFacility()); diseaseScreening.setRemarks(requestData.getRemarks()); @@ -946,6 +954,8 @@ private String updateMalariaDisease(DiseaseMalariaDTO requestData) { diseaseScreening.setSlideNo(requestData.getSlideNo()); diseaseScreening.setReferredTo(requestData.getReferredTo()); diseaseScreening.setOtherReferredFacility(requestData.getOtherReferredFacility()); + diseaseScreening.setMalariaSlideTestType(requestData.getMalariaSlideTestType()); + diseaseScreening.setMalariaTestType(requestData.getMalariaTestType()); diseaseScreening.setRemarks(requestData.getRemarks()); diseaseScreening.setCreatedDate(Timestamp.valueOf(LocalDateTime.now())); diseaseScreening.setDateOfVisitBySupervisor(requestData.getDateOfVisitBySupervisor()); @@ -1069,51 +1079,57 @@ public List getAllMosquitoMobilizationNet(Integer userId) { private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { - IncentiveActivity diseaseScreeningActivity; - if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed Case")) { - diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MALARIA_1", "DISEASECONTROL"); + Integer stateId = userService.getUserDetail(diseaseScreening.getUserId()).getStateId(); + IncentiveActivity diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_MALARIA_TREATMENT", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); + IncentiveActivity incentiveActivityForCollectSlideAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); + IncentiveActivity incentiveActivityForCollectSlideCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.ACTIVITY.getDisplayName()); - } else { - diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("MALARIA_2", "DISEASECONTROL"); + if (diseaseScreeningActivity != null) { + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { + addIncentive(diseaseScreeningActivity, diseaseScreening); + } } + if (diseaseScreening.getCaseStatus().equals("Suspected")) { + if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test")) { + if (stateId.equals(StateCode.AM.getStateCode())) { + if (incentiveActivityForCollectSlideAM != null) { + addIncentive(incentiveActivityForCollectSlideAM, diseaseScreening); + } + } - 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); + if (stateId.equals(StateCode.CG.getStateCode())) { + if (incentiveActivityForCollectSlideCG != null) { + addIncentive(incentiveActivityForCollectSlideCG, diseaseScreening); + + } } + } + + } + } + + private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningMalaria diseaseScreening) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); + if (record == null) { + 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); + } } @@ -1134,7 +1150,7 @@ public List saveChronicDiseaseVisit( entity.setVersion(dto.getVersion()); entity.setVisitNo(dto.getVisitNo()); entity.setFollowUpNo(dto.getFollowUpNo()); - if(dto.getFollowUpDate()!=null){ + if (dto.getFollowUpDate() != null) { entity.setFollowUpDate(dto.getFollowUpDate()); } @@ -1156,18 +1172,19 @@ public List saveChronicDiseaseVisit( dto.setId(savedEntity.getId()); responseList.add(dto); - checkIncentive(savedEntity,savedEntity.getUserID()); + checkIncentive(savedEntity, savedEntity.getUserID()); } return responseList; } - private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity,Integer ashaId){ + + 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){ + logger.info("incentiveActivity:" + incentiveActivity.getId()); + if (incentiveActivity != null) { if (chronicDiseaseVisitEntity.getFollowUpNo() != null && chronicDiseaseVisitEntity.getCreatedDate() != null && chronicDiseaseVisitEntity.getDiagnosisCodes() != null) { @@ -1203,75 +1220,75 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, } - } 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()); - } + 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()); + List entityList = chronicDiseaseVisitRepository.findByUserID(getBenRequestHandler.getAshaId()); - for (ChronicDiseaseVisitEntity entity : entityList) { + for (ChronicDiseaseVisitEntity entity : entityList) { - ChronicDiseaseVisitDTO dto = new ChronicDiseaseVisitDTO(); + 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.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()); + } + 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){ + if (entity.getTreatmentStartDate() != null) { + dto.setTreatmentStartDate( + entity.getTreatmentStartDate().toString() + ); + } + checkIncentive(entity, entity.getUserID()); + dtoList.add(dto); + } + } catch (Exception e) { - } + } return dtoList; } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index b59c1314d..1bd9b294a 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -261,6 +261,49 @@ public IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatm } } + @Override + public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NPCB_GOVT_CATARACT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + secondChildDob, + secondChildDob1, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + secondChildDob, + secondChildDob1, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Eye surgery Incentive Exception: ", e); + return null; + } + + } + @Override public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { try { @@ -290,7 +333,8 @@ public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp } catch (Exception e) { logger.error("Check FP_DELAY_2Y Incentive Exception: ", e); return null; - } } + } + } From 05f9aa4e83aee270fd44add1958d815d87b6898f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 12:31:22 +0530 Subject: [PATCH 293/450] fix incentive issue on cg --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e6e92ee2f..576c0cdfb 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.iemr.common.flw flw-api - 3.8.1 + 3.8.2 war FLW-API From 0cc6845a4c0750a0ac6598fd9a0317934f323c54 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 15:05:31 +0530 Subject: [PATCH 294/450] fix incentive issue on cg --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index cc28f4364..144329fcf 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1091,7 +1091,7 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } } if (diseaseScreening.getCaseStatus().equals("Suspected")) { - if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test")) { + if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test") || diseaseScreening.getMalariaSlideTestType().equals("2")) { if (stateId.equals(StateCode.AM.getStateCode())) { if (incentiveActivityForCollectSlideAM != null) { addIncentive(incentiveActivityForCollectSlideAM, diseaseScreening); From 51ea000ff01541cb90f09ff88e1de14be92155b0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 15:13:58 +0530 Subject: [PATCH 295/450] fix incentive issue on cg --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 144329fcf..fedd5194c 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1119,15 +1119,16 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningM record = new IncentiveActivityRecord(); record.setActivityId(diseaseScreeningActivity.getId()); record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setCreatedBy(diseaseScreening.getCreatedBy()); + record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); 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.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setBenId(diseaseScreening.getBenId().longValue()); record.setAshaId(diseaseScreening.getUserId()); - record.setName(diseaseScreeningActivity.getName()); record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + record.setIsEligible(true); recordRepo.save(record); } From dd51021d4952f9a98a4695424bd08158040d8b59 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 15:16:10 +0530 Subject: [PATCH 296/450] fix incentive issue on cg --- .../flw/service/impl/IncentiveServiceImpl.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 3672cd2c0..a65847052 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -258,6 +258,21 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); } + if(entry.getAshaId()!=null){ + if (entry.getCreatedBy() == null) { + entry.setCreatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + } + + if (entry.getUpdatedBy() == null) { + entry.setUpdatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + } + + if (entry.getIsEligible() == null) { + entry.setIsEligible(true); + } + } + + } return modelMapper.map(entry, IncentiveRecordDTO.class); }).collect(Collectors.toList()); From 57a1d443556eef758510a8ab96e820ee511b1986 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 16:11:47 +0530 Subject: [PATCH 297/450] fix incentive issue on cg --- .../flw/service/IncentiveLogicService.java | 2 + .../impl/DiseaseControlServiceImpl.java | 144 ++++++++++++------ .../flw/service/impl/IncentiveLogicImpl.java | 43 +++++- .../impl/MalariaFollowUpServiceImpl.java | 13 ++ 4 files changed, 154 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index c00ff0c13..47755e494 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -21,4 +21,6 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId); IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index fedd5194c..ee69d9262 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -296,58 +296,55 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { diseaseControlData.setUserId(diseaseControlDTO.getUserId()); } ScreeningLeprosy screeningLeprosy = diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); - if (screeningLeprosy != null) { - if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - + if(screeningLeprosy.getIsConfirmed()){ + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForIdentificationLeprosy( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } + if (screeningLeprosy.getIsConfirmed()) { + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); } - if (screeningLeprosy.getIsConfirmed()) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForIdentificationLeprosy( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - - } } + } return "Data add successfully"; @@ -438,10 +435,63 @@ public List getAllLeprosyData(String createdBy) { List dtos = new ArrayList<>(); leprosyList.forEach(leprosy -> { dtos.add(modelMapper.map(leprosy, DiseaseGetLeprosyDTO.class)); + checkAndIncentive(leprosy,leprosy.getUserId()); }); return dtos; } + private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId){ + if(screeningLeprosy.getIsConfirmed()){ + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForIdentificationLeprosy( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } + if (screeningLeprosy.getIsConfirmed()) { + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + + } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + + } + + } + } @Override public List getAllLeprosyFollowUpData(String createdBy) { diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 1bd9b294a..e9565a024 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -304,6 +304,48 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp } + @Override + public IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NPCB_GOVT_CATARACT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentStartDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Eye surgery Incentive Exception: ", e); + return null; + } + } + @Override public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { try { @@ -439,7 +481,6 @@ private IncentiveActivityRecord saveIncentive( record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); record.setBenId(benId); record.setAshaId(userId); - record.setName(activity.getName()); record.setAmount(Long.valueOf(activity.getRate())); record = incentiveRecordRepo.save(record); diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index 3b6779bc0..7932e1344 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -5,6 +5,7 @@ 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.IncentiveLogicService; import com.iemr.flw.service.MalariaFollowUpService; import com.iemr.flw.utils.JwtUtil; import io.jsonwebtoken.Jwt; @@ -15,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @@ -25,6 +27,9 @@ public class MalariaFollowUpServiceImpl implements MalariaFollowUpService { @Autowired private MalariaFollowUpRepository repository; + @Autowired + private IncentiveLogicService incentiveLogicService; + private final Logger logger = LoggerFactory.getLogger(MalariaFollowUpServiceImpl.class); @Autowired @@ -52,6 +57,14 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) MalariaFollowUp entity = new MalariaFollowUp(); BeanUtils.copyProperties(dto, entity); repository.save(entity); + if(entity!=null){ + incentiveLogicService.incentiveForMalariaFollowUp( + entity.getBenId(), + new Timestamp(entity.getTreatmentStartDate().getTime()), + new Timestamp(entity.getTreatmentCompletionDate().getTime()), + entity.getUserId() + ); } + return true; } }catch (Exception e){ From 19c11602d0048e86e2203148e0e2570604d9c315 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 16:36:03 +0530 Subject: [PATCH 298/450] fix incentive --- .../flw/service/IncentiveLogicService.java | 4 + .../flw/service/impl/IncentiveLogicImpl.java | 84 +++++++++++++++++++ .../impl/TBConfirmedCaseServiceImpl.java | 42 +++++++++- 3 files changed, 128 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 47755e494..66b71368f 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -23,4 +23,8 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForTbFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index e9565a024..f6aa68aff 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -304,6 +304,90 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp } + @Override + public IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "DRTB_TREATMENT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentStartDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check TB Incentive Exception: ", e); + return null; + } + } + + @Override + public IncentiveActivityRecord incentiveForTbFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "DSTB_TREATMENT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentStartDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check TB Incentive Exception: ", e); + return null; + } + } + @Override public IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 39b121775..2ad2cc58d 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -6,9 +6,8 @@ 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.IncentiveLogicService; 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; @@ -17,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.sql.Timestamp; import java.time.LocalDate; import java.util.List; import java.util.stream.Collectors; @@ -28,6 +28,10 @@ public class TBConfirmedCaseServiceImpl implements TBConfirmedCaseService { private final TBConfirmedTreatmentRepository repository; + @Autowired + private IncentiveLogicService incentiveLogicService; + + @Autowired private JwtUtil jwtUtil; public TBConfirmedCaseServiceImpl(TBConfirmedTreatmentRepository repository) { @@ -63,6 +67,8 @@ public String save(List request, String authorisation) throw if(entity!=null){ repository.save(entity); + checkIncentive(entity); + } } @@ -82,6 +88,36 @@ public String save(List request, String authorisation) throw return response.toString(); } + private void checkIncentive(TBConfirmedCase entity){ + String regimen = entity.getRegimenType(); + + boolean isDrTb = + "Shorter Regimen (9–12 Months)".equalsIgnoreCase(regimen) + || "Longer Regimen (18–24 Months)".equalsIgnoreCase(regimen); + + if (Boolean.TRUE.equals(entity.getTreatmentCompleted()) + && entity.getActualTreatmentCompletionDate() != null) { + + + if (isDrTb) { + incentiveLogicService.incentiveForTbFollowUpIsDrTb( + entity.getBenId(), + Timestamp.valueOf(entity.getTreatmentStartDate().atStartOfDay()), + Timestamp.valueOf(entity.getActualTreatmentCompletionDate().atStartOfDay()), + entity.getUserId() + ); + } else { + incentiveLogicService.incentiveForTbFollowUp( + entity.getBenId(), + Timestamp.valueOf(entity.getTreatmentStartDate().atStartOfDay()), + Timestamp.valueOf(entity.getActualTreatmentCompletionDate().atStartOfDay()), + entity.getUserId() + ); + + } + } + } + @Override public String getByBenId(Long benId, String authorisation) throws Exception { OutputResponse response = new OutputResponse(); @@ -95,6 +131,8 @@ public String getByBenId(Long benId, String authorisation) throws Exception { .collect(Collectors.toList()); response.setResponse(dtoList.toString()); + list.forEach(this::checkIncentive); + } else { response.setError(404, "No record found for benId: " + benId); } From f2b17c8a0fe05db034f0dd84222c7f258852f3a1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 16:45:32 +0530 Subject: [PATCH 299/450] fix incentive --- .../impl/DiseaseControlServiceImpl.java | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index ee69d9262..e292cc834 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1094,7 +1094,7 @@ public List saveMosquitoMobilizationNet(List mos if (dto.getFields() != null) { dto.getFields().setIs_net_distributed(entity.getIsNetDistributed()); } - + checkAndAddIncentives(entity); return dto; }).collect(Collectors.toList()); @@ -1122,11 +1122,22 @@ public List getAllMosquitoMobilizationNet(Integer userId) { mosquitoNetListDTO.setVisit_date(entity.getVisitDate().format(formatter)); dto.setFields(mosquitoNetListDTO); + checkAndAddIncentives(entity); + return dto; }).collect(Collectors.toList()); } + private void checkAndAddIncentives(MosquitoNetEntity mosquitoNetEntity) { + Integer stateId = userService.getUserDetail(mosquitoNetEntity.getUserId()).getStateId(); + IncentiveActivity activityMobilizingMosquitoNets = incentivesRepo.findIncentiveMasterByNameAndGroup("MOSQUITO_NET_DISTRIBUTION_MOBILIZATION", GroupName.ACTIVITY.getDisplayName()); + if(stateId.equals(StateCode.CG.getStateCode())){ + addIncentive(activityMobilizingMosquitoNets, mosquitoNetEntity); + + } + + } private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { Integer stateId = userService.getUserDetail(diseaseScreening.getUserId()).getStateId(); @@ -1161,6 +1172,28 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } } + private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNetEntity diseaseScreening) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getVisitDate().toString()), diseaseScreening.getBeneficiaryId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); + record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setStartDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); + record.setEndDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); + record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setBenId(diseaseScreening.getBeneficiaryId().longValue()); + record.setAshaId(diseaseScreening.getUserId()); + record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + + } + } + private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningMalaria diseaseScreening) { IncentiveActivityRecord record = recordRepo @@ -1173,7 +1206,7 @@ record = new IncentiveActivityRecord(); 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.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setBenId(diseaseScreening.getBenId().longValue()); record.setAshaId(diseaseScreening.getUserId()); From cc702f06adfdfb1406849386f6d0fa60971e2534 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 16:52:01 +0530 Subject: [PATCH 300/450] fix incentive --- .../impl/DiseaseControlServiceImpl.java | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index e292cc834..addc43b12 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1173,24 +1173,33 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } } private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNetEntity diseaseScreening) { + + Timestamp visitTimestamp = + Timestamp.valueOf(diseaseScreening.getVisitDate().atStartOfDay()); + IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getVisitDate().toString()), diseaseScreening.getBeneficiaryId().longValue()); + .findRecordByActivityIdCreatedDateBenId( + diseaseScreeningActivity.getId(), + visitTimestamp, + diseaseScreening.getBeneficiaryId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); - record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); + record.setCreatedDate(visitTimestamp); record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setStartDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); - record.setEndDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); - record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getVisitDate().toString())); - record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setStartDate(visitTimestamp); + record.setEndDate(visitTimestamp); + record.setUpdatedDate(visitTimestamp); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setBenId(diseaseScreening.getBeneficiaryId().longValue()); record.setAshaId(diseaseScreening.getUserId()); record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); record.setIsEligible(true); - recordRepo.save(record); + recordRepo.save(record); } } From 34c37e9e9075caba4eac6ba03726a6f824e39800 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 17:15:11 +0530 Subject: [PATCH 301/450] fix incentive --- .../service/impl/ChildCareServiceImpl.java | 4 ++-- .../impl/MaternalHealthServiceImpl.java | 23 ++++++++++++++----- .../impl/TBConfirmedCaseServiceImpl.java | 1 + 3 files changed, 20 insertions(+), 8 deletions(-) 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 02597ddea..ebdc0dfc8 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -836,9 +836,9 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI if (stateCode.equals(StateCode.CG.getStateCode())) { if (hbncVisit.getVisit_day().equals("7th Day")) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS_CH"); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); } } 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 5bed940dd..ce7bc1d16 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -151,7 +151,7 @@ public List getANCVisits(GetBenRequestHandler dto) { } @Override - public String saveANCVisit(List ancVisitDTOs,Integer userId) { + public String saveANCVisit(List ancVisitDTOs, Integer userId) { try { logger.info("ANC save process started. Total records: {}", ancVisitDTOs.size()); @@ -260,7 +260,7 @@ public String saveANCVisit(List ancVisitDTOs,Integer userId) { logger.info("AncCare saved successfully"); logger.info("ANC visit details saved"); - checkAndAddIncentives(ancList,userId); + checkAndAddIncentives(ancList, userId); return "no of anc details saved: " + ancList.size(); @@ -514,7 +514,7 @@ public List getANCCounselling(GetBenRequestHandle List entities = ancCounsellingCareRepo.findAllByUserId(requestDTO.getAshaId()); - List responseDTOList = new ArrayList<>(); + List responseDTOList = new ArrayList<>(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); for (AncCounsellingCare entity : entities) { @@ -559,8 +559,6 @@ public List getANCCounselling(GetBenRequestHandle responseDTOList.add(responseDTO); - - } return responseDTOList; @@ -571,7 +569,6 @@ private String booleanToYesNo(Boolean value) { } - private Boolean yesNoToBoolean(String value) { return "Yes".equalsIgnoreCase(value); } @@ -652,6 +649,19 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) addIncenticeRecord(recordList, ect, userId, ppsActivityCH); } } + if (ect.getMotherDangerSign() != null + && !ect.getMotherDangerSign().isEmpty() + && ect.getPncPeriod() == 7) { + + IncentiveActivity highRiskPostpartumCareActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (highRiskPostpartumCareActivityCH != null) { + addIncenticeRecord(recordList, ect, userId, highRiskPostpartumCareActivityCH); + + } + + + } } @@ -797,6 +807,7 @@ record = new IncentiveActivityRecord(); } } + private void recordAncFirstTRIMIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { if (ancVisit.getAncDate() == null || ancVisit.getLmpDate() == null) { diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 2ad2cc58d..92493c751 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -115,6 +115,7 @@ private void checkIncentive(TBConfirmedCase entity){ ); } + } } From 87690427255a53445d440a817d088b2325707a15 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 28 May 2026 18:30:31 +0530 Subject: [PATCH 302/450] fix incentive --- .../flw/service/IncentiveLogicService.java | 2 + .../service/impl/ChildCareServiceImpl.java | 20 ++++++++- .../flw/service/impl/IncentiveLogicImpl.java | 41 +++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 66b71368f..71c9229ee 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -27,4 +27,6 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForTbFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); } 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 ebdc0dfc8..b87c9d5ec 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -11,6 +11,7 @@ import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import jakarta.persistence.EntityNotFoundException; @@ -84,6 +85,9 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private UserService userService; + @Autowired + private IncentiveLogicService incentiveLogicService; + @Override public String registerHBYC(List hbycDTOs) { @@ -658,10 +662,24 @@ private LocalDate parseDate(String dateStr) { @Override public List saveAllIfa(List dtoList) { - return dtoList.stream() + List savedList = dtoList.stream() .map(this::mapToEntity) .map(ifaDistributionRepository::save) .toList(); + + // incentive generate + savedList.forEach(data -> { + Timestamp visitTimestamp = + Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + }); + + return savedList; } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index f6aa68aff..87cb83f91 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -304,6 +304,47 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp } + @Override + public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "LACTATING_MOTHERS_HOME_VISIT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentStartDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check IFA Exception: ", e); + return null; + } } + @Override public IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { From 1e0be7a318b5ccd8308183b6586049fb5163ec72 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 1 Jun 2026 16:31:10 +0530 Subject: [PATCH 303/450] fix incentive issue and api response issue --- .../flw/controller/ChildCareController.java | 98 ++++++++++++------- .../flw/controller/MaaMeetingController.java | 4 + .../flw/controller/UwinSessionController.java | 2 +- .../iemr/flw/service/ChildCareService.java | 6 +- .../service/impl/ChildCareServiceImpl.java | 56 ++++++----- .../service/impl/UwinSessionServiceImpl.java | 42 ++++---- src/main/java/com/iemr/flw/utils/JwtUtil.java | 9 -- .../utils/sessionobject/SessionObject.java | 1 - 8 files changed, 125 insertions(+), 93 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 8ef128f02..0e45b36ac 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -235,7 +235,7 @@ public String getChildVaccinationDetails(@RequestParam(value = "category") Strin return response.toString(); } @RequestMapping(value = {"/sam/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List samRequest) { + public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List samRequest,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("SAM Request: {}", samRequest); @@ -247,18 +247,27 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s } - 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); + if(token!=null){ + Integer userId = jwtUtil.extractUserId(token); + String userName = jwtUtil.extractUsername(token); + String responseObject = childCareService.saveSamDetails(samRequest,userId,userName); + + 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); + } + }else { + response.put("statusCode", HttpStatus.UNAUTHORIZED.value()); + response.put("message", "Invalid token"); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response); } + } catch (Exception e) { logger.error("Error saving SAM details:", e); response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); @@ -279,9 +288,9 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", HttpStatus.OK.value()); response.put("message", "No SAM records found"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body(response); } } catch (Exception e) { @@ -294,7 +303,7 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques @RequestMapping(value = {"/ors/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveOrsDistribution(@RequestBody List orsDistributionDTOS) { + public ResponseEntity saveOrsDistribution(@RequestBody List orsDistributionDTOS,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("ORS Request: {}", orsDistributionDTOS); @@ -304,18 +313,26 @@ public ResponseEntity saveOrsDistribution(@RequestBody List getAllOrDistribution(@RequestBody GetBenRequestHandler @RequestMapping(value = {"/ifa/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveIfDistribution(@RequestBody List ifaDistributionDTOS) { + public ResponseEntity saveIfDistribution(@RequestBody List ifaDistributionDTOS,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("IFA Request: {}", ifaDistributionDTOS); @@ -363,18 +380,25 @@ public ResponseEntity saveIfDistribution(@RequestBody List responseObject = childCareService.saveAllIfa(ifaDistributionDTOS,userId); + + 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); + } + }else { + response.put("statusCode", HttpStatus.UNAUTHORIZED.value()); + response.put("message", "Invalid token"); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).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); diff --git a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java index 49c2236be..012438c56 100644 --- a/src/main/java/com/iemr/flw/controller/MaaMeetingController.java +++ b/src/main/java/com/iemr/flw/controller/MaaMeetingController.java @@ -94,6 +94,7 @@ public ResponseEntity updateMeeting( @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, @RequestPart("participants") String participants, + @RequestPart("id") Long meetingId, @RequestPart("ashaId") String ashaId, @RequestPart("createdBy") String createdBy, @RequestPart(value = "meetingImages", required = false) List meetingImages) { @@ -123,6 +124,9 @@ public ResponseEntity updateMeeting( dto.setMeetingImages(meetingImages != null ? meetingImages.toArray(new MultipartFile[0]) : null); } + if(meetingId!=null){ + dto.setId(meetingId); + } if (dto != null) { service.updateMeeting(dto); diff --git a/src/main/java/com/iemr/flw/controller/UwinSessionController.java b/src/main/java/com/iemr/flw/controller/UwinSessionController.java index 6fd31b160..afb4ff2ba 100644 --- a/src/main/java/com/iemr/flw/controller/UwinSessionController.java +++ b/src/main/java/com/iemr/flw/controller/UwinSessionController.java @@ -31,7 +31,7 @@ public class UwinSessionController { @Autowired private JwtUtil jwtUtil; - @RequestMapping(value = "saveAll", method = RequestMethod.POST, headers = "Authorization", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @RequestMapping(value = "saveAll", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity saveSession( @RequestPart("meetingDate") String meetingDate, @RequestPart("place") String place, diff --git a/src/main/java/com/iemr/flw/service/ChildCareService.java b/src/main/java/com/iemr/flw/service/ChildCareService.java index e82090b75..c272fd2ff 100644 --- a/src/main/java/com/iemr/flw/service/ChildCareService.java +++ b/src/main/java/com/iemr/flw/service/ChildCareService.java @@ -23,15 +23,15 @@ public interface ChildCareService { List getAllChildVaccines(String category); - String saveSamDetails(List samRequest); + String saveSamDetails(List samRequest,Integer userId,String userName); List getSamVisitsByBeneficiary(GetBenRequestHandler dto); - String saveOrsDistributionDetails(List orsDistributionDTOS); + String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId); List getOrdDistrubtion(GetBenRequestHandler request); - List saveAllIfa(List dtoList); + List saveAllIfa(List dtoList,Integer userId); List getByBeneficiaryId(GetBenRequestHandler request); 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 b87c9d5ec..9479191ae 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -448,7 +448,7 @@ public List getAllChildVaccines(String category) { } @Override - public String saveSamDetails(List samRequest) { + public String saveSamDetails(List samRequest,Integer userId,String userName) { try { List vaccinationList = new ArrayList<>(); @@ -469,11 +469,9 @@ public String saveSamDetails(List samRequest) { 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()); - } + samVisit.setUserId(userId); + samVisit.setCreatedBy(userName); + // ✅ Field mapping samVisit.setMuac(samDTO.getFields().getMuac()); @@ -503,7 +501,7 @@ public String saveSamDetails(List samRequest) { samVisitRepository.saveAll(vaccinationList); // ✅ Handle incentive logic - checkAndAddSamVisitNRCReferalIncentive(vaccinationList); + checkAndAddSamVisitNRCReferalIncentive(vaccinationList,userId); return "Saved/Updated " + samRequest.size() + " SAM visit records successfully"; } catch (Exception e) { @@ -576,7 +574,7 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque } @Override - public String saveOrsDistributionDetails(List orsDistributionDTOS) { + public String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId) { try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List orsDistributionList = new ArrayList<>(); @@ -590,7 +588,7 @@ public String saveOrsDistributionDetails(List orsDistributio } orsDistribution.setHouseholdId(orsDistributionDTO.getHouseHoldId()); - orsDistribution.setUserId(userRepo.getUserIdByName(orsDistributionDTO.getUserName())); + orsDistribution.setUserId(userId); orsDistribution.setVisitDate(LocalDate.parse(orsDistributionDTO.getFields().getVisit_date(), formatter)); orsDistributionList.add(orsDistribution); @@ -661,9 +659,9 @@ private LocalDate parseDate(String dateStr) { } @Override - public List saveAllIfa(List dtoList) { + public List saveAllIfa(List dtoList,Integer userId) { List savedList = dtoList.stream() - .map(this::mapToEntity) + .map(dto ->mapToEntity(dto,userId)) .map(ifaDistributionRepository::save) .toList(); @@ -714,7 +712,7 @@ private IfaDistributionDTO mapToDTO(IfaDistribution entity) { } // 🔄 Helper method to convert DTO → Entity - private IfaDistribution mapToEntity(IfaDistributionDTO dto) { + private IfaDistribution mapToEntity(IfaDistributionDTO dto,Integer userId) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); IfaDistribution entity = new IfaDistribution(); @@ -723,7 +721,7 @@ private IfaDistribution mapToEntity(IfaDistributionDTO dto) { entity.setHouseHoldId(dto.getHouseHoldId()); entity.setFormId(dto.getFormId()); entity.setVisitDate(dto.getVisitDate()); - entity.setUserId(userRepo.getUserIdByName(jwtUtil.getUserNameFromStorage())); + entity.setUserId(userId); if (dto.getFields() != null) { if (dto.getFields().getIfa_provision_date() != null) { @@ -743,24 +741,32 @@ private IfaDistribution mapToEntity(IfaDistributionDTO dto) { return entity; } - private void checkAndAddSamVisitNRCReferalIncentive(List samVisits) { + private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Integer userId) { 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(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { + + if (samreferralnrcActivityAm != null) { + if (samVisit.getIsChildReferredNrc().equals("Yes")) { + createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityAm, samVisit.getCreatedBy()); + } } } - if (samreferralnrcActivityCH != null) { - if (samVisit.getIsChildReferredNrc().equals("Yes")) { - createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityCH, jwtUtil.getUserNameFromStorage()); + if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())){ + if (samreferralnrcActivityCH != null) { + if (samVisit.getIsChildReferredNrc().equals("Yes")) { + createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityCH, samVisit.getCreatedBy()); + } } } + + + }); } @@ -1051,7 +1057,7 @@ record = new IncentiveActivityRecord(); record.setUpdatedDate(visitDate); record.setUpdatedBy(createdBy); record.setBenId(benId); - record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAshaId(data.getUserId()); record.setAmount(Long.valueOf(immunizationActivity.getRate())); recordRepo.save(record); } @@ -1081,7 +1087,7 @@ record = new IncentiveActivityRecord(); record.setUpdatedDate(visitDate); record.setUpdatedBy(createdBy); record.setBenId(benId); - record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAshaId(data.getUserId()); record.setAmount(Long.valueOf(immunizationActivity.getRate())); recordRepo.save(record); } @@ -1107,7 +1113,7 @@ record = new IncentiveActivityRecord(); record.setUpdatedDate(visitDate); record.setUpdatedBy(createdBy); record.setBenId(benId); - record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAshaId(data.getUserId()); if (isCH) { record.setAmount((long) rate); @@ -1142,8 +1148,10 @@ record = new IncentiveActivityRecord(); record.setUpdatedDate(visitDate); record.setUpdatedBy(createdBy); record.setBenId(benId); - record.setAshaId(beneficiaryRepo.getUserIDByUserName(createdBy)); + record.setAshaId(data.getUserId()); record.setAmount((long) incentiveActivity.getRate()); + record.setIsEligible(true); + record.setIsDefaultActivity(false); recordRepo.save(record); } } catch (Exception e) { diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index 8698ef905..eadfa4ee7 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -190,18 +190,22 @@ record = new IncentiveActivityRecord(); 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); - IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); - if(incentiveActivityRecord!=null){ - updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),incentiveActivityRecord.getId(),incentiveActivityAM.getId()); - - } - } + record.setIsEligible(true); + recordRepo.save(record); + + +// if(session.getAttachmentsJson()!=null){ +// record.setIsEligible(true); +// recordRepo.save(record); +// +// }else { +// record.setIsEligible(false); +// IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); +// if(incentiveActivityRecord!=null){ +// updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),incentiveActivityRecord.getId(),incentiveActivityAM.getId()); +// +// } +// } } } @@ -221,12 +225,14 @@ record = new IncentiveActivityRecord(); record.setBenId(0L); record.setAshaId(session.getAshaId()); record.setAmount(Long.valueOf(incentiveActivityCH.getRate())); - if(session.getAttachmentsJson()!=null){ - record.setIsEligible(true); - }else { - record.setIsEligible(false); - updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),record.getId(),incentiveActivityCH.getId()); - } + record.setIsEligible(true); + +// if(session.getAttachmentsJson()!=null){ +// record.setIsEligible(true); +// }else { +// record.setIsEligible(false); +// updateIncentivePendindDocService.updatePendingActivity(session.getAshaId(),session.getId(),record.getId(),incentiveActivityCH.getId()); +// } recordRepo.save(record); } } diff --git a/src/main/java/com/iemr/flw/utils/JwtUtil.java b/src/main/java/com/iemr/flw/utils/JwtUtil.java index 7107d7387..ab15e4647 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUtil.java +++ b/src/main/java/com/iemr/flw/utils/JwtUtil.java @@ -90,13 +90,4 @@ private Claims extractAllClaims(String token) { .getPayload(); } - public String getUserNameFromStorage() { - return userName; - - } - - public void setUserNameFromStorage(String loginUserName) { - this.userName = loginUserName; - - } } 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 d84a1684b..c18da8203 100644 --- a/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java +++ b/src/main/java/com/iemr/flw/utils/sessionobject/SessionObject.java @@ -81,7 +81,6 @@ 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); } From 8a5e9eaa90f28a0bb31aa79fde6f7396f0283451 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 1 Jun 2026 16:58:26 +0530 Subject: [PATCH 304/450] fix incentive issue and api response issue --- .../java/com/iemr/flw/controller/UwinSessionController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/controller/UwinSessionController.java b/src/main/java/com/iemr/flw/controller/UwinSessionController.java index afb4ff2ba..6a273d9ab 100644 --- a/src/main/java/com/iemr/flw/controller/UwinSessionController.java +++ b/src/main/java/com/iemr/flw/controller/UwinSessionController.java @@ -38,7 +38,7 @@ public ResponseEntity saveSession( @RequestPart("participants") String participants, @RequestPart("ashaId") String ashaId, @RequestPart("createdBy") String createdBy, - @RequestPart(value = "meetingImages", required = false) List images) throws Exception { + @RequestPart(value = "meetingImages", required = false) List images,@RequestHeader(value = "jwtToken") String jwtToken) throws Exception { Map response = new LinkedHashMap<>(); UwinSessionRequestDTO dto = new UwinSessionRequestDTO(); From f7678fd17edf1c5a3b4926693f2de6ab39ca2283 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 2 Jun 2026 12:11:11 +0530 Subject: [PATCH 305/450] add unclaimed incentive count on dashboard --- .../flw/repo/iemr/SupervisorDashboardRepo.java | 15 +++++++++++++++ .../flw/service/impl/CampaignServiceImpl.java | 11 ++++++----- .../impl/SupervisorDashboardServiceImpl.java | 12 ++++++++++++ .../flw/service/impl/UwinSessionServiceImpl.java | 3 +-- .../service/impl/VillageLevelFormServiceImpl.java | 1 + 5 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java index ef6cc0483..a56587776 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/SupervisorDashboardRepo.java @@ -36,6 +36,21 @@ public interface SupervisorDashboardRepo extends JpaRepository getAshasWithFacilityInfo(@Param("supervisorUserID") Integer supervisorUserID); + // Unclaimed incentive count per ASHA + @Query(value = "SELECT iar.asha_id, " + + "COUNT(*) AS unclaimedCount " + + "FROM incentive_activity_record iar " + + "WHERE iar.asha_id IN (:ashaIds) " + + "AND iar.created_date >= :startDate " + + "AND iar.created_date < :endDate " + + "AND (iar.is_claimed = false OR iar.is_claimed IS NULL) " + + "GROUP BY iar.asha_id", + nativeQuery = true) + List getUnclaimedCountByAshaIds( + @Param("ashaIds") List ashaIds, + @Param("startDate") Timestamp startDate, + @Param("endDate") Timestamp endDate); + // Get facility details with geo names @Query(value = "SELECT DISTINCT f.FacilityID, f.FacilityName, " + "COALESCE(s.StateName,'') AS stateName, " diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 60306e0bc..1d1988d4e 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -190,18 +190,18 @@ public List savePolioCampaign(List polioCa if (!campaignPolioRequest.isEmpty()) { List savedCampaigns = pulsePolioCampaignRepo.saveAll(campaignPolioRequest); - savedCampaigns.forEach(pulsePolioCampaign -> { - checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + savedCampaigns.forEach(this::checkIncentiveForPulsePolio); - });{ - - } return savedCampaigns; } throw new IEMRException("No valid campaign data to save"); } + private void checkIncentiveForPulsePolio(PulsePolioCampaign pulsePolioCampaign){ + checkMonthlyPulsePolioIncentive(pulsePolioCampaign.getUserId(),pulsePolioCampaign.getStartDate(),pulsePolioCampaign.getEndDate()); + + } @Override @Transactional @@ -307,6 +307,7 @@ public List getPolioCampaign(String token) throws IEMR for (PulsePolioCampaign campaignOrs : campaignPolioPage.getContent()) { PolioCampaignResponseDTO dto = convertPolioToDTO(campaignOrs); polioCampaignDTOSResponse.add(dto); + } page++; } while (campaignPolioPage.hasNext()); diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index c1850f383..e28e1b0fa 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -116,6 +116,8 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In // 5. Get incentive status per ASHA (verified, rejected, pending, totalAmount) long overallVerified = 0, overallRejected = 0, overallPending = 0; + long overallUnclaimed = 0; + try { logger.info("Month: {}", month); logger.info("Year: {}", year); @@ -142,16 +144,26 @@ public String getSupervisorDashboard(Integer supervisorUserID, Integer month, In if (pending > 0) overallPending += 1; } } + List unclaimedRows = dashboardRepo.getUnclaimedCountByAshaIds(ashaIDs, startDate, endDate); + if (unclaimedRows != null) { + for (Object[] uRow : unclaimedRows) { + long count = ((Number) uRow[1]).longValue(); + if (count > 0) overallUnclaimed += 1; + } + } } catch (Exception e) { logger.error("Error fetching incentive status: " + e.getMessage(), e); } + + // Overall incentive summary across all ASHAs JSONObject overallSummary = new JSONObject(); overallSummary.put("verified", overallVerified); overallSummary.put("rejected", overallRejected); overallSummary.put("pending", overallPending); overallSummary.put("overDue", 0); + overallSummary.put("unclaimed", overallUnclaimed); result.put("incentiveSummary", overallSummary); // 7. Build facilities array with nested ASHAs diff --git a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java index eadfa4ee7..d91d0c6f8 100644 --- a/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UwinSessionServiceImpl.java @@ -107,6 +107,7 @@ public UwinSessionResponseDTO saveSession(UwinSessionRequestDTO req) throws Exce dto.setParticipants(session.getParticipants()); dto.setAttachments(Collections.singletonList(session.getAttachmentsJson())); + return dto; } @Override @@ -137,8 +138,6 @@ public UwinSession updateSession(UwinSessionRequestDTO req, Long recordId, Long String imagesJson = objectMapper.writeValueAsString(base64Images); session.setAttachmentsJson(imagesJson); - // Trigger incentive update if attachments exist - updateIncentivePendindDocService.updateIncentive(activityId); } repo.save(session); // ✅ Save updated session diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 579b84c92..09b87e243 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -248,6 +248,7 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); incentiveLogicService.incentiveForVhndMeeting(0L,date,date,vhndForm.getUserId()); + return true; From 11c49f94110282589be258c10b338becc857e334 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 15:51:22 +0530 Subject: [PATCH 306/450] fix incentive issue in 3.8.2 --- .../flw/service/IncentiveLogicService.java | 2 ++ .../flw/service/impl/CoupleServiceImpl.java | 1 + .../flw/service/impl/IncentiveLogicImpl.java | 31 +++++++++++++++++++ .../service/impl/TBSuspectedServiceImpl.java | 9 ++++++ 4 files changed, 43 insertions(+) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 71c9229ee..8e23ac759 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -29,4 +29,6 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + + IncentiveActivityRecord incentiveForTbSuspected(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, 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 95b0557b2..bcf1b5c24 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -188,6 +188,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) } } + ecrList.add(existingECR); }); eligibleCoupleRegisterRepo.saveAll(ecrList); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 87cb83f91..7627c6b50 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -85,6 +85,37 @@ public IncentiveActivityRecord incentiveForLeprosyPaucibacillaryConfirmed( } } + @Override + public IncentiveActivityRecord incentiveForTbSuspected(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "INFORMANT_INCENTIVE"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Tb Suspected Incentive Exception: ", e); + return null; + } + } @Override public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( diff --git a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java index 1b972be66..84437cc05 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java @@ -7,6 +7,7 @@ import com.iemr.flw.dto.iemr.TBSuspectedDTO; import com.iemr.flw.dto.iemr.TBSuspectedRequestDTO; import com.iemr.flw.repo.iemr.TBSuspectedRepo; +import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.TBSuspectedService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -25,6 +26,9 @@ public class TBSuspectedServiceImpl implements TBSuspectedService { @Autowired private TBSuspectedRepo tbSuspectedRepo; + @Autowired + private IncentiveLogicService incentiveLogicService; + @Override public String getByBenId(Long benId, String authorisation) throws Exception { return null; @@ -49,6 +53,11 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { tbSuspected.setUserId(requestDTO.getUserId()); tbSuspectedRepo.save(tbSuspected); + if(tbSuspected!=null){ + incentiveLogicService.incentiveForTbSuspected(tbSuspected.getBenId(),tbSuspected.getVisitDate(),tbSuspected.getVisitDate(),tbSuspected.getUserId()); + + } + }); return "no of tb suspected items saved:" + requestDTO.getTbSuspectedList().size(); } From 9fb577d1debf50a8a6fa6f2a97e6ba5054fb846d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 15:57:21 +0530 Subject: [PATCH 307/450] fix incentive issue in 3.8.2 --- .../com/iemr/flw/service/impl/TBSuspectedServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java index 84437cc05..7e2f042b7 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java @@ -54,7 +54,10 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { tbSuspected.setUserId(requestDTO.getUserId()); tbSuspectedRepo.save(tbSuspected); if(tbSuspected!=null){ - incentiveLogicService.incentiveForTbSuspected(tbSuspected.getBenId(),tbSuspected.getVisitDate(),tbSuspected.getVisitDate(),tbSuspected.getUserId()); + if(tbSuspected.getIsConfirmed()){ + incentiveLogicService.incentiveForTbSuspected(tbSuspected.getBenId(),tbSuspected.getVisitDate(),tbSuspected.getVisitDate(),tbSuspected.getUserId()); + + } } From 366ff28e006184d1a49f6eaa160fc32424be835c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 16:30:35 +0530 Subject: [PATCH 308/450] fix incentive issue in 3.8.2 --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 7 +++++++ .../com/iemr/flw/service/impl/ChildCareServiceImpl.java | 3 ++- .../iemr/flw/service/impl/MaternalHealthServiceImpl.java | 1 + 3 files changed, 10 insertions(+), 1 deletion(-) 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 5c4e1a71a..ef93b78cd 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -576,6 +576,13 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); } + + if(visit.getReferredTo().equals("Private Facility")){ + LocalDate localDate = visit.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + } } return "Eye checkup data saved successfully."; 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 9479191ae..cd80ac7d7 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -357,8 +357,9 @@ public List getChildVaccinationDetails(GetBenRequestHandler vaccinationDTO.setBeneficiaryId(benId.longValue()); result.add(vaccinationDTO); - checkAndAddIncentives(vaccinationDetails); }); + checkAndAddIncentives(vaccinationDetails); + return result; } catch (Exception e) { logger.error(e.getMessage()); 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 ce7bc1d16..98b4da5b1 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -307,6 +307,7 @@ public String savePmsmaRecords(List pmsmaDTOs) { }); pmsmaRepo.saveAll(pmsmaList); logger.info("PMSMA details saved"); + checkAndAddHighRisk(pmsmaList); return "No. of PMSMA records saved: " + pmsmaList.size(); From 25189edab07048cc3cb2c644490d3a1cf41e1145 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 16:43:17 +0530 Subject: [PATCH 309/450] fix TB suspected incentive --- .../flw/service/impl/TBSuspectedServiceImpl.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java index 7e2f042b7..2a8c0eeb0 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java @@ -69,7 +69,18 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { public String getByUserId(GetBenRequestHandler request) { List dtos = new ArrayList<>(); List tbSuspectedList = tbSuspectedRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); - tbSuspectedList.forEach(tbSuspected -> dtos.add(modelMapper.map(tbSuspected, TBSuspectedDTO.class))); + tbSuspectedList.forEach(tbSuspected -> { + dtos.add(modelMapper.map(tbSuspected, TBSuspectedDTO.class)); + + if (tbSuspected != null && Boolean.TRUE.equals(tbSuspected.getIsConfirmed())) { + incentiveLogicService.incentiveForTbSuspected( + tbSuspected.getBenId(), + tbSuspected.getVisitDate(), + tbSuspected.getVisitDate(), + tbSuspected.getUserId() + ); + } + }); TBSuspectedRequestDTO tbSuspectedRequestDTO = new TBSuspectedRequestDTO(); tbSuspectedRequestDTO.setTbSuspectedList(dtos); tbSuspectedRequestDTO.setUserId(request.getAshaId()); From 411840e45f563389a719a3689500145bcbc1d53d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 17:15:11 +0530 Subject: [PATCH 310/450] Fix incentive for ANC --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 1 + 1 file changed, 1 insertion(+) 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 98b4da5b1..0af497ad6 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -141,6 +141,7 @@ public List getANCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List ancVisits = ancVisitRepo.getANCForPW(user, dto.getFromDate(), dto.getToDate()); + checkAndAddIncentives(ancVisits,dto.getAshaId()); return ancVisits.stream() .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); From 1fb4c73bf8a68b90a39b79d0f46e4dd95a85b8bc Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 17:47:00 +0530 Subject: [PATCH 311/450] Fix incentive for ANC --- .../flw/service/IncentiveLogicService.java | 3 +- .../service/impl/BeneficiaryServiceImpl.java | 18 ++++++- .../flw/service/impl/IncentiveLogicImpl.java | 53 +++++++++++++++++-- 3 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java index 8e23ac759..8becce199 100644 --- a/src/main/java/com/iemr/flw/service/IncentiveLogicService.java +++ b/src/main/java/com/iemr/flw/service/IncentiveLogicService.java @@ -20,7 +20,8 @@ public interface IncentiveLogicService { IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId); - IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + IncentiveActivityRecord incentiveForEyeSurgeyReferGovtHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); + IncentiveActivityRecord incentiveForEyeSurgeyReferPrivateHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId); 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 ef93b78cd..2b5ea9569 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -574,14 +574,14 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO LocalDate localDate = visit.getVisitDate(); Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); } if(visit.getReferredTo().equals("Private Facility")){ LocalDate localDate = visit.getVisitDate(); Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyRefer(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); } } @@ -627,6 +627,20 @@ public List getEyeCheckUpVisit(GetBenRequestHandler reques dto.setFields(fields); + + if(v.getReferredTo().equals("Govt Public Facility")){ + LocalDate localDate = v.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(v.getBeneficiaryId(),visitDate,visitDate,v.getUserId()); + } + + if(v.getReferredTo().equals("Private Facility")){ + LocalDate localDate = v.getVisitDate(); + + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(v.getBeneficiaryId(),visitDate,visitDate,v.getUserId()); + } return dto; }).collect(Collectors.toList()); } diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 7627c6b50..543873fd2 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -293,7 +293,7 @@ public IncentiveActivityRecord incentiveForChildBirthGap(Long benId, Date treatm } @Override - public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp secondChildDob, Timestamp secondChildDob1, Integer userId) { + public IncentiveActivityRecord incentiveForEyeSurgeyReferGovtHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { Integer stateCode = userService.getUserDetail(userId).getStateId(); @@ -309,8 +309,8 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp activityName, GroupName.ACTIVITY.getDisplayName(), benId, - secondChildDob, - secondChildDob1, + treatmentStartDate, + treatmentEndDate, userId); } @@ -319,8 +319,8 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp activityName, GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), benId, - secondChildDob, - secondChildDob1, + treatmentStartDate, + treatmentEndDate, userId); } @@ -332,9 +332,52 @@ public IncentiveActivityRecord incentiveForEyeSurgeyRefer(Long benId, Timestamp logger.error("Check Eye surgery Incentive Exception: ", e); return null; } + } + + @Override + public IncentiveActivityRecord incentiveForEyeSurgeyReferPrivateHospital(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { + try { + Integer stateCode = userService.getUserDetail(userId).getStateId(); + if (stateCode == null) { + logger.warn("State code is null for user: {}", userId); + return null; + } + + String activityName = "NPCB_PRIVATE_CATARACT"; + + if (stateCode.equals(StateCode.CG.getStateCode())) { + return processIncentive( + activityName, + GroupName.ACTIVITY.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + benId, + treatmentStartDate, + treatmentEndDate, + userId); + } + + // state not supported + logger.info("No incentive mapping for stateCode: {}", stateCode); + return null; + + } catch (Exception e) { + logger.error("Check Eye surgery Incentive Exception: ", e); + return null; + } } + + @Override public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp treatmentStartDate, Timestamp treatmentEndDate, Integer userId) { try { From 5cfd49236b2b5d7ef5436c98bcc9f972c768ea7e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 17:49:50 +0530 Subject: [PATCH 312/450] Fix incentive for ANC --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 a65847052..42db9543b 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -191,7 +191,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { try { - incentiveOfNcdReferal(request.getAshaId(), request.getVillageID()); + incentiveOfNcdReferal(request.getAshaId(), stateCode); } catch (Exception e) { logger.error("Error in incentiveOfNcdReferal: ", e); From 26ab6c13f1892c3d96c1ab7779197d0fe1557f4c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 4 Jun 2026 18:04:04 +0530 Subject: [PATCH 313/450] Fix incentive for ANC --- .../service/impl/BeneficiaryServiceImpl.java | 54 ++++++++++--------- 1 file changed, 29 insertions(+), 25 deletions(-) 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 2b5ea9569..b1df1433c 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -103,7 +103,6 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { @@ -412,7 +411,7 @@ private String getMappingsForAddressIDs(List addressLi 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("dateOfDeath", benDetailsRMNCH_OBJ.getDateOfDeath()); resultMap.put("timeOfDeath", benDetailsRMNCH_OBJ.getTimeOfDeath()); resultMap.put("reasonOfDeath", benDetailsRMNCH_OBJ.getReasonOfDeath()); resultMap.put("reasonOfDeathId", benDetailsRMNCH_OBJ.getReasonOfDeathId()); @@ -423,8 +422,8 @@ private String getMappingsForAddressIDs(List addressLi 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("noofAlivechildren", benDetailsRMNCH_OBJ.getNoofAlivechildren()); + resultMap.put("isDeactivate", benDetailsRMNCH_OBJ.getIsDeactivate()); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id @@ -444,7 +443,7 @@ private String getMappingsForAddressIDs(List addressLi // mapping not available } } catch (Exception e) { - logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); + logger.error("error for addressID :" + e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } } @@ -570,19 +569,22 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO visit.setFollowUpStatus(f.getFollow_up_status()); eyeCheckUpVisitRepo.save(visit); - if(visit.getReferredTo().equals("Govt Public Facility")){ - LocalDate localDate = visit.getVisitDate(); + if (visit.getReferredTo() != null) { + if (visit.getReferredTo().equals("Govt Public Facility")) { + LocalDate localDate = visit.getVisitDate(); - Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); - } + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(visit.getBeneficiaryId(), visitDate, visitDate, visit.getUserId()); + } - if(visit.getReferredTo().equals("Private Facility")){ - LocalDate localDate = visit.getVisitDate(); + if (visit.getReferredTo().equals("Private Facility")) { + LocalDate localDate = visit.getVisitDate(); - Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(visit.getBeneficiaryId(),visitDate,visitDate,visit.getUserId()); + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(visit.getBeneficiaryId(), visitDate, visitDate, visit.getUserId()); + } } + } return "Eye checkup data saved successfully."; @@ -598,7 +600,7 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO } @Override - public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { + public List getEyeCheckUpVisit(GetBenRequestHandler request, String token) { String createdBy = null; try { createdBy = userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token)); @@ -627,20 +629,22 @@ public List getEyeCheckUpVisit(GetBenRequestHandler reques dto.setFields(fields); + if (v.getReferredTo() != null) { + if (v.getReferredTo().equals("Govt Public Facility")) { + LocalDate localDate = v.getVisitDate(); - if(v.getReferredTo().equals("Govt Public Facility")){ - LocalDate localDate = v.getVisitDate(); - - Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(v.getBeneficiaryId(),visitDate,visitDate,v.getUserId()); - } + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferGovtHospital(v.getBeneficiaryId(), visitDate, visitDate, v.getUserId()); + } - if(v.getReferredTo().equals("Private Facility")){ - LocalDate localDate = v.getVisitDate(); + if (v.getReferredTo().equals("Private Facility")) { + LocalDate localDate = v.getVisitDate(); - Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); - incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(v.getBeneficiaryId(),visitDate,visitDate,v.getUserId()); + Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); + incentiveLogicService.incentiveForEyeSurgeyReferPrivateHospital(v.getBeneficiaryId(), visitDate, visitDate, v.getUserId()); + } } + return dto; }).collect(Collectors.toList()); } From b67e31109487112a46eb58eab2ccaff7c95bc4b4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 12:22:16 +0530 Subject: [PATCH 314/450] fix ifa incentive --- .../impl/DiseaseControlServiceImpl.java | 8 ++++-- .../impl/IFAFormSubmissionServiceImpl.java | 26 +++++++++---------- .../service/impl/IncentiveServiceImpl.java | 24 +++++++++++++++++ 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index addc43b12..5a892d679 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1146,11 +1146,15 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { IncentiveActivity incentiveActivityForCollectSlideCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.ACTIVITY.getDisplayName()); if (diseaseScreeningActivity != null) { - if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { - addIncentive(diseaseScreeningActivity, diseaseScreening); + if(stateId.equals(StateCode.AM.getStateCode())){ + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { + addIncentive(diseaseScreeningActivity, diseaseScreening); + } } + } + if (diseaseScreening.getCaseStatus().equals("Suspected")) { if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test") || diseaseScreening.getMalariaSlideTestType().equals("2")) { if (stateId.equals(StateCode.AM.getStateCode())) { diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index 380ed5118..2b60ad382 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -76,18 +76,17 @@ public String saveFormData(List requests, Integer user private void checkIFAIncentive(List entities,Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); - if(stateCode.equals(StateCode.AM.getStateCode())){ - IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); - - if(incentiveActivityAM!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); - - }); - } - - } - +// if(stateCode.equals(StateCode.AM.getStateCode())){ +// IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); +// +// if(incentiveActivityAM!=null){ +// entities.forEach(ifaFormSubmissionData -> { +// addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); +// +// }); +// } +// +// } if(stateCode.equals(StateCode.CG.getStateCode())){ IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); @@ -112,7 +111,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); if(incentiveActivityRecord==null){ incentiveActivityRecord = new IncentiveActivityRecord(); - incentiveActivityRecord.setActivityId(ifaFormSubmissionData.getId()); + incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); incentiveActivityRecord.setCreatedDate(ifaVisitDateTimestamp); incentiveActivityRecord.setStartDate(ifaVisitDateTimestamp); incentiveActivityRecord.setEndDate(ifaVisitDateTimestamp); @@ -122,6 +121,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent incentiveActivityRecord.setBenId(ifaFormSubmissionData.getBeneficiaryId()); incentiveActivityRecord.setAshaId(userServiceRoleRepo.getUserIdByName(ifaFormSubmissionData.getUserName())); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + incentiveActivityRecord.setIsEligible(true); incentiveRecordRepo.save(incentiveActivityRecord); } } 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 42db9543b..f713a8a65 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -539,6 +539,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); +// IncentiveActivity ncdFollowUpEnumeration = activityMap.get("NCD_FOLLOWUP_TREATMENT"); CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); @@ -546,6 +547,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); List cbacDetailsImer = cbacFuture.get(); + List benReferDetailsIemr = benReferFuture.get(); List recordsToSave = new ArrayList<>(); @@ -575,6 +577,28 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { }); } +// if(benReferDetailsIemr!=null){ +// List referalBenIds = benReferDetailsIemr.stream() +// .filter(c -> c != null && c.getBeneficiaryRegID() != null && c.getref) +// .map(BenReferDetails::getBenReferID) +// .collect(Collectors.toList()); +// +// Set existingKeys = recordRepo +// .findExistingRecords(ncdFollowUpEnumeration.getId(), referalBenIds, ashaId) +// .stream() +// .map(r -> r.getActivityId() + "_" + r.getBenId() + "_" + r.getCreatedDate()) +// .collect(Collectors.toSet()); +// +// final IncentiveActivity activity = ncdFollowUpEnumeration; +// benReferDetailsIemr.stream() +// .filter(c -> c != null && c.getBenReferID() != null) +// .forEach(c -> { +// String key = activity.getId() + "_" + c.getBenReferID() + "_" + c.getCreatedDate(); +// if (!existingKeys.contains(key)) { +// recordsToSave.add(addNCDandCBACIncentiveRecord(activity, ashaId, c.getBenReferID(), c.getCreatedDate(), userName)); +// } +// }); +// } // ---- Single batch insert instead of N individual saves ---- if (!recordsToSave.isEmpty()) { recordRepo.saveAll(recordsToSave); From 4c56d6ad0df0bca2258c6284d878195bb1a5a621 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 13:06:30 +0530 Subject: [PATCH 315/450] fix For motivating Female sterilization --- .../com/iemr/flw/service/impl/CoupleServiceImpl.java | 9 +++++++++ 1 file changed, 9 insertions(+) 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 bcf1b5c24..b78effe95 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -410,6 +410,7 @@ public String getEligibleCoupleRegRecords(GetBenRequestHandler dto) { 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()); @@ -419,16 +420,24 @@ public String getEligibleCoupleRegRecords(GetBenRequestHandler dto) { @Override public List getEligibleCoupleTracking(GetBenRequestHandler dto) { + List recordList = new ArrayList<>(); try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List eligibleCoupleTrackingList = eligibleCoupleTrackingRepo.getECTrackRecords(user, dto.getFromDate(), dto.getToDate()); + eligibleCoupleTrackingList.forEach(eligibleCoupleTracking -> { + checkAndAddAntaraIncentive(recordList, eligibleCoupleTracking); + + }); + + recordRepo.saveAll(recordList); return eligibleCoupleTrackingList.stream() .map(ect -> mapper.convertValue(ect, EligibleCoupleTrackingDTO.class)) .collect(Collectors.toList()); + } catch (Exception e) { logger.error(e.getMessage()); } From e4903cc456b3f669546c612ba4ab96de847db49c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 16:00:08 +0530 Subject: [PATCH 316/450] fix For motivating Female sterilization --- .../flw/service/impl/DiseaseControlServiceImpl.java | 11 +++++++++-- .../com/iemr/flw/service/impl/IncentiveLogicImpl.java | 2 +- .../flw/service/impl/MalariaFollowUpServiceImpl.java | 3 ++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 5a892d679..236320877 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1142,6 +1142,7 @@ private void checkAndAddIncentives(MosquitoNetEntity mosquitoNetEntity) { private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { Integer stateId = userService.getUserDetail(diseaseScreening.getUserId()).getStateId(); IncentiveActivity diseaseScreeningActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_MALARIA_TREATMENT", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); + IncentiveActivity diseaseScreeningActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_MALARIA_TREATMENT", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity incentiveActivityForCollectSlideAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.UMBRELLA_PROGRAMMES.getDisplayName()); IncentiveActivity incentiveActivityForCollectSlideCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NVBDCP_SLIDE_COLLECTION", GroupName.ACTIVITY.getDisplayName()); @@ -1152,6 +1153,12 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } } + if(stateId.equals(StateCode.CG.getStateCode())){ + if (Objects.equals(diseaseScreening.getCaseStatus(), "Confirmed")) { + addIncentive(diseaseScreeningActivityCG, diseaseScreening); + + } + } } @@ -1185,7 +1192,7 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNe .findRecordByActivityIdCreatedDateBenId( diseaseScreeningActivity.getId(), visitTimestamp, - diseaseScreening.getBeneficiaryId().longValue()); + diseaseScreening.getHouseHoldId().longValue()); if (record == null) { @@ -1198,7 +1205,7 @@ record = new IncentiveActivityRecord(); record.setEndDate(visitTimestamp); record.setUpdatedDate(visitTimestamp); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setBenId(diseaseScreening.getBeneficiaryId().longValue()); + record.setBenId(diseaseScreening.getHouseHoldId().longValue()); record.setAshaId(diseaseScreening.getUserId()); record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); record.setIsEligible(true); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 543873fd2..1b2cf4c27 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -513,7 +513,7 @@ public IncentiveActivityRecord incentiveForMalariaFollowUp(Long benId, Timestamp return null; } - String activityName = "NPCB_GOVT_CATARACT"; + String activityName = "NVBDCP_MALARIA_TREATMENT"; if (stateCode.equals(StateCode.CG.getStateCode())) { return processIncentive( diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index 7932e1344..7ae86c7b3 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -63,7 +63,8 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) new Timestamp(entity.getTreatmentStartDate().getTime()), new Timestamp(entity.getTreatmentCompletionDate().getTime()), entity.getUserId() - ); } + ); + } return true; } From f2d032b347bb743fb98b65f13d54740f707d22f9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 17:11:04 +0530 Subject: [PATCH 317/450] fix incentive for NCD follow up --- .../impl/DiseaseControlServiceImpl.java | 27 ++++++++++++++----- .../service/impl/IncentiveServiceImpl.java | 2 -- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 236320877..f726fcd7e 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1286,7 +1286,9 @@ public List saveChronicDiseaseVisit( private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, Integer ashaId) { String userName = userRepo.getUserNamedByUserId(ashaId); + Integer stateId = userService.getUserDetail(ashaId).getStateId(); IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); + IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.ACTIVITY.getDisplayName()); logger.info("incentiveActivity:" + incentiveActivity.getId()); if (incentiveActivity != null) { if (chronicDiseaseVisitEntity.getFollowUpNo() != null @@ -1311,14 +1313,25 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); + if(stateId.equals(StateCode.AM.getStateCode())){ + addNCDFolloupIncentiveRecord( + incentiveActivity, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } + if(stateId.equals(StateCode.CG.getStateCode())){ + addNCDFolloupIncentiveRecord( + incentiveActivityCG, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + followUpTimestamp, + userName + ); + } - addNCDFolloupIncentiveRecord( - incentiveActivity, - ashaId, - chronicDiseaseVisitEntity.getBenId(), - followUpTimestamp, - userName - ); } } } 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 f713a8a65..2d30817a7 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -539,7 +539,6 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); -// IncentiveActivity ncdFollowUpEnumeration = activityMap.get("NCD_FOLLOWUP_TREATMENT"); CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); @@ -547,7 +546,6 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); List cbacDetailsImer = cbacFuture.get(); - List benReferDetailsIemr = benReferFuture.get(); List recordsToSave = new ArrayList<>(); From 1b79f30cf3e3cfa5e1a943b8ac265eb784f75d95 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 19:00:36 +0530 Subject: [PATCH 318/450] fix pnc related incentive --- .../impl/MaternalHealthServiceImpl.java | 146 +++++++++++------- 1 file changed, 90 insertions(+), 56 deletions(-) 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 0af497ad6..f17547cb7 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -5,6 +5,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; 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.IncentiveLogicService; @@ -141,7 +142,7 @@ public List getANCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List ancVisits = ancVisitRepo.getANCForPW(user, dto.getFromDate(), dto.getToDate()); - checkAndAddIncentives(ancVisits,dto.getAshaId()); + checkAndAddIncentives(ancVisits, dto.getAshaId()); return ancVisits.stream() .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); @@ -578,96 +579,129 @@ private Boolean yesNoToBoolean(String value) { private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); + Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); - if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { + // logic for assam + if(stateId.equals(StateCode.AM.getStateCode())){ + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { - IncentiveActivity maleSterilizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + 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); - } + if (maleSterilizationActivityAM != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityAM); + } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { - IncentiveActivity femaleSterilizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + } + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { + + IncentiveActivity femaleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + if (femaleSterilizationActivityAM != null) { + addIncenticeRecord(ect, userId, femaleSterilizationActivityAM); + } - IncentiveActivity femaleSterilizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - if (femaleSterilizationActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityAM); } + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MiniLap")) { - if (femaleSterilizationActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, femaleSterilizationActivityCH); + IncentiveActivity miniLapActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", GroupName.FAMILY_PLANNING.getDisplayName()); + if (miniLapActivity != null) { + addIncenticeRecord(ect, userId, miniLapActivity); + } } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MiniLap")) { + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("Condom")) { - IncentiveActivity miniLapActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", GroupName.FAMILY_PLANNING.getDisplayName()); - if (miniLapActivity != null) { - addIncenticeRecord(recordList, ect, userId, miniLapActivity); + IncentiveActivity comdomActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", GroupName.FAMILY_PLANNING.getDisplayName()); + if (comdomActivity != null) { + addIncenticeRecord(ect, userId, comdomActivity); + } } - } else if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("Condom")) { + 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()); + + if (PPIUCDActivityAM != null) { + addIncenticeRecord(ect, userId, PPIUCDActivityAM); + } - 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")) { + if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)")) { + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity ppsActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); + + if (ppsActivityAM != null) { + addIncenticeRecord(ect, userId, ppsActivityAM); + } + } + - IncentiveActivity PPIUCDActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + } + } + // logic for cg + if(stateId.equals(StateCode.CG.getStateCode())){ 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); + addIncenticeRecord(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 femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - IncentiveActivity ppsActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); - if (ppsActivityAM != null) { - addIncenticeRecord(recordList, ect, userId, ppsActivityAM); + + if (femaleSterilizationActivityCH != null) { + addIncenticeRecord(ect, userId, femaleSterilizationActivityCH); } - if (ppsActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, ppsActivityCH); + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); + + if (maleSterilizationActivityCH != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityCH); } - } - if (ect.getMotherDangerSign() != null - && !ect.getMotherDangerSign().isEmpty() - && ect.getPncPeriod() == 7) { - IncentiveActivity highRiskPostpartumCareActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - if (highRiskPostpartumCareActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, highRiskPostpartumCareActivityCH); + if (ect.getMotherDangerSign() != null + && !ect.getMotherDangerSign().isEmpty() + && ect.getPncPeriod() == 7) { + + IncentiveActivity highRiskPostpartumCareActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (highRiskPostpartumCareActivityCH != null) { + addIncenticeRecord(ect, userId, highRiskPostpartumCareActivityCH); + + } } + if (ect.getPncPeriod() == 1 || ect.getPncPeriod() == 3 || ect.getPncPeriod() == 7) { + + if ((ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)") + || ect.getContraceptionMethod().equals("Minilap")) + && ect.getSterilisationDate() != null) { + IncentiveActivity ppsActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); + if (ppsActivityCH != null) { + addIncenticeRecord(ect, userId, ppsActivityCH); + + } + } + } } + } - private void addIncenticeRecord(List recordList, PNCVisit ect, Integer userId, IncentiveActivity antaraActivity) { + private void addIncenticeRecord(PNCVisit ect, Integer userId, IncentiveActivity antaraActivity) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); // get bene details From e82a4d18de23384e098cf2e4e710622852d585ad Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 8 Jun 2026 23:49:05 +0530 Subject: [PATCH 319/450] fix pnc related incentive --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f17547cb7..20741cb85 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -684,7 +684,7 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) if (ect.getPncPeriod() == 1 || ect.getPncPeriod() == 3 || ect.getPncPeriod() == 7) { if ((ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)") - || ect.getContraceptionMethod().equals("Minilap")) + || ect.getContraceptionMethod().equals("MiniLap")) && ect.getSterilisationDate() != null) { IncentiveActivity ppsActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.ACTIVITY.getDisplayName()); From 071f615ea4c5c7e01674efc6f24f959b918ef40d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Jun 2026 18:42:54 +0530 Subject: [PATCH 320/450] fix IFA incentive logic issue --- .../service/impl/ChildCareServiceImpl.java | 20 ++++++++++------- .../impl/IFAFormSubmissionServiceImpl.java | 22 +++++++++---------- .../flw/service/impl/IncentiveLogicImpl.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 8 +++---- 4 files changed, 28 insertions(+), 24 deletions(-) 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 cd80ac7d7..a1990f988 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -670,12 +670,15 @@ public List saveAllIfa(List dtoList,Integer savedList.forEach(data -> { Timestamp visitTimestamp = Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); - incentiveLogicService.incentiveForGiveingIFA( - data.getBeneficiaryId(), - visitTimestamp, - visitTimestamp, - data.getUserId() - ); + if(data.getIfaBottleCount().equals("10.0")){ + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + } + }); return savedList; @@ -684,6 +687,7 @@ public List saveAllIfa(List dtoList,Integer @Override public List getByBeneficiaryId(GetBenRequestHandler requestHandler) { + return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()).stream() .map(this::mapToDTO) .toList(); @@ -834,7 +838,7 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI hbncVisits.forEach(hbncVisit -> { GroupName.setIsCh(false); Long benId = hbncVisit.getBeneficiaryId(); - if (stateCode.equals(StateCode.AM)) { + if (stateCode.equals(StateCode.AM.getStateCode())) { if (hbncVisit.getVisit_day().equals("42nd Day")) { IncentiveActivity visitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); @@ -860,7 +864,7 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } if (stateCode.equals(StateCode.CG.getStateCode())) { - if (hbncVisit.getVisit_day().equals("7th Day")) { + if (hbncVisit.getVisit_day().equals("42nd Day")) { IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index 2b60ad382..cf74589f0 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -76,17 +76,17 @@ public String saveFormData(List requests, Integer user private void checkIFAIncentive(List entities,Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); -// if(stateCode.equals(StateCode.AM.getStateCode())){ -// IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); -// -// if(incentiveActivityAM!=null){ -// entities.forEach(ifaFormSubmissionData -> { -// addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); -// -// }); -// } -// -// } + if(stateCode.equals(StateCode.AM.getStateCode())){ + IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); + + if(incentiveActivityAM!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); + + }); + } + + } if(stateCode.equals(StateCode.CG.getStateCode())){ IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 1b2cf4c27..9a2d1def6 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -388,7 +388,7 @@ public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp trea return null; } - String activityName = "LACTATING_MOTHERS_HOME_VISIT"; + String activityName = "NIPI_CHILDREN"; if (stateCode.equals(StateCode.CG.getStateCode())) { return processIncentive( 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 20741cb85..c0df6b43e 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -776,13 +776,13 @@ private void checkAndAddIncentives(List ancList, Integer userId) { ancList.forEach(ancVisit -> { - if (finalPaiucdActivityAM != null && ancVisit.getIsPaiucd() != null - && ancVisit.getIsPaiucd().equals("Yes")) { + if (finalPaiucdActivityAM != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { recordAncRelatedIncentive(finalPaiucdActivityAM, ancVisit); } - if (finalPaiucdActivityCH != null && ancVisit.getIsPaiucd() != null - && ancVisit.getIsPaiucd().equals("Yes")) { + if (finalPaiucdActivityCH != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { recordAncRelatedIncentive(finalPaiucdActivityCH, ancVisit); } From d37816469295604488b7e4903af162865a013997 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Jun 2026 19:20:24 +0530 Subject: [PATCH 321/450] fix IFA incentive logic issue --- .../service/impl/ChildCareServiceImpl.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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 a1990f988..d9af8a80b 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -688,8 +688,23 @@ public List saveAllIfa(List dtoList,Integer @Override public List getByBeneficiaryId(GetBenRequestHandler requestHandler) { - return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()).stream() - .map(this::mapToDTO) + return ifaDistributionRepository.findByUserId(requestHandler.getAshaId()) + .stream() + .map(data -> { + + if ("10.0".equals(data.getIfaBottleCount())) { + Timestamp visitTimestamp = + Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + } + + return mapToDTO(data); + }) .toList(); } From ded2afe60ba0ba2411d8665eff3295dfc05becc7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Jun 2026 19:42:30 +0530 Subject: [PATCH 322/450] fix IFA incentive logic issue --- .../service/impl/ChildCareServiceImpl.java | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) 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 d9af8a80b..512cf6c20 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -692,14 +692,24 @@ public List getByBeneficiaryId(GetBenRequestHandler requestH .stream() .map(data -> { - if ("10.0".equals(data.getIfaBottleCount())) { - Timestamp visitTimestamp = - Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); - incentiveLogicService.incentiveForGiveingIFA( + try { + if ("10.0".equals(data.getIfaBottleCount())) { + + Timestamp visitTimestamp = + Timestamp.valueOf(data.getIfaProvisionDate().atStartOfDay()); + + incentiveLogicService.incentiveForGiveingIFA( + data.getBeneficiaryId(), + visitTimestamp, + visitTimestamp, + data.getUserId() + ); + } + } catch (Exception e) { + logger.error( + "Error while processing IFA incentive for beneficiaryId: {}", data.getBeneficiaryId(), - visitTimestamp, - visitTimestamp, - data.getUserId() + e ); } From 4f36ecf40dd76996098f88c7e5e340fa93a180f1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Jun 2026 19:50:07 +0530 Subject: [PATCH 323/450] fix IFA incentive logic issue --- src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 9a2d1def6..efc63389f 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -444,7 +444,7 @@ public IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestam if (stateCode.equals(StateCode.AM.getStateCode())) { return processIncentive( activityName, - GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + GroupName.CHILD_HEALTH.getDisplayName(), benId, treatmentStartDate, treatmentEndDate, From 715da83b258223be16a2e7c8eea60074cc303def Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 9 Jun 2026 19:57:56 +0530 Subject: [PATCH 324/450] fix IFA incentive logic issue --- .../java/com/iemr/flw/service/impl/IncentiveLogicImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index efc63389f..2d3ff87ab 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -403,7 +403,7 @@ public IncentiveActivityRecord incentiveForGiveingIFA(Long benId, Timestamp trea if (stateCode.equals(StateCode.AM.getStateCode())) { return processIncentive( activityName, - GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), + GroupName.CHILD_HEALTH.getDisplayName(), benId, treatmentStartDate, treatmentEndDate, @@ -444,7 +444,7 @@ public IncentiveActivityRecord incentiveForTbFollowUpIsDrTb(Long benId, Timestam if (stateCode.equals(StateCode.AM.getStateCode())) { return processIncentive( activityName, - GroupName.CHILD_HEALTH.getDisplayName(), + GroupName.UMBRELLA_PROGRAMMES.getDisplayName(), benId, treatmentStartDate, treatmentEndDate, From d2fea55c7da65ee69a5186f957b6c5dfbd273611 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 10 Jun 2026 09:58:34 +0530 Subject: [PATCH 325/450] fixed malaria followup incentive --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index f726fcd7e..7f81da4b7 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1310,7 +1310,7 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, .anyMatch(targetDiseases::contains); if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { - LocalDateTime localDateTime = chronicDiseaseVisitEntity.getCreatedDate(); + LocalDateTime localDateTime = chronicDiseaseVisitEntity.getFollowUpDate().atStartOfDay(); Timestamp followUpTimestamp = Timestamp.valueOf(localDateTime); if(stateId.equals(StateCode.AM.getStateCode())){ 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 2d30817a7..aeb765417 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -540,8 +540,6 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); - CompletableFuture> benReferFuture = - CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); CompletableFuture> cbacFuture = CompletableFuture.supplyAsync(() -> cbacIemrDetailsRepo.findByCreatedBy(userName)); From e70cfb7bf7f3b7b98d0e2330f045323307406b74 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 10 Jun 2026 10:21:55 +0530 Subject: [PATCH 326/450] fixed malaria followup incentive --- .../repo/iemr/EligibleCoupleRegisterRepo.java | 3 + .../impl/IFAFormSubmissionServiceImpl.java | 57 ++++++++++++------- .../service/impl/IncentiveServiceImpl.java | 1 + 3 files changed, 39 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java index 2eae0b059..529117e19 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java @@ -17,4 +17,7 @@ public interface EligibleCoupleRegisterRepo extends JpaRepository= :fromDate and ecr.createdDate <= :toDate") List getECRegRecords(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + + @Query(" SELECT ecr FROM EligibleCoupleRegister ecr WHERE ecr.createdBy = :userId") + List getECRegRecords(@Param("userId") String userId); } diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index cf74589f0..20e04fcfc 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -1,6 +1,8 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.controller.DeathReportsController; +import com.iemr.flw.domain.iemr.EligibleCoupleRegister; import com.iemr.flw.domain.iemr.IFAFormSubmissionData; import com.iemr.flw.domain.iemr.IncentiveActivity; import com.iemr.flw.domain.iemr.IncentiveActivityRecord; @@ -10,15 +12,14 @@ import com.iemr.flw.dto.iemr.IFAFormSubmissionResponse; import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.masterEnum.StateCode; -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.repo.iemr.*; import com.iemr.flw.service.IFAFormSubmissionService; import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import jakarta.persistence.criteria.CriteriaBuilder; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -34,6 +35,9 @@ public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { private final IFAFormSubmissionRepository repository; private final ObjectMapper mapper = new ObjectMapper(); + private final Logger logger = LoggerFactory.getLogger(IFAFormSubmissionServiceImpl.class); + + @Autowired private JwtUtil jwtUtil; @@ -48,6 +52,9 @@ public class IFAFormSubmissionServiceImpl implements IFAFormSubmissionService { @Autowired private UserService userService; + @Autowired + private EligibleCoupleRegisterRepo eligibleCoupleRegisterRepo; + @Override public String saveFormData(List requests, Integer userId) { try { @@ -75,29 +82,35 @@ public String saveFormData(List requests, Integer user } private void checkIFAIncentive(List entities,Integer userId) { - Integer stateCode = userService.getUserDetail(userId).getStateId(); - if(stateCode.equals(StateCode.AM.getStateCode())){ - IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.CHILD_HEALTH.getDisplayName()); - - if(incentiveActivityAM!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityAM); - - }); + try { + List records = repository.findByUserId(userId); + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.getECRegRecords(userService.getUserDetail(userId).getUserName()); + int totalEligibleCouples = eligibleCoupleRegisters.size(); + int totalIFASubmissions = records.size(); + if(totalEligibleCouples>0){ + double percentage = + (totalIFASubmissions * 100.0) / totalEligibleCouples; + if(percentage>=70){ + Integer stateCode = userService.getUserDetail(userId).getStateId(); + if(stateCode.equals(StateCode.CG.getStateCode())){ + IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); + + if(incentiveActivityCG!=null){ + entities.forEach(ifaFormSubmissionData -> { + addIFAIncentive(ifaFormSubmissionData,incentiveActivityCG); + + }); + } + + } + } } + }catch (Exception e){ + logger.error("Error while processing IFA incentive", e); } - if(stateCode.equals(StateCode.CG.getStateCode())){ - IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); - if(incentiveActivityCG!=null){ - entities.forEach(ifaFormSubmissionData -> { - addIFAIncentive(ifaFormSubmissionData,incentiveActivityCG); - }); - } - - } } 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 aeb765417..9f0a1e445 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -352,6 +352,7 @@ public String getAllIncentivesGroupedSummary(GetBenRequestHandler request) { return new Gson().toJson(result); } + @Override public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { try { From 1e55578d9427ed0b6b1e587f52157fe7dae5b723 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 10 Jun 2026 10:23:35 +0530 Subject: [PATCH 327/450] fixed malaria followup incentive --- .../com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index 20e04fcfc..76e8dc586 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -93,7 +93,7 @@ private void checkIFAIncentive(List entities,Integer user if(percentage>=70){ Integer stateCode = userService.getUserDetail(userId).getStateId(); if(stateCode.equals(StateCode.CG.getStateCode())){ - IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NIPI_CHILDREN", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity incentiveActivityCG= incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); if(incentiveActivityCG!=null){ entities.forEach(ifaFormSubmissionData -> { From 0ca336e549567f4c68f6a47f3c0f1ef3f2110dba Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 11 Jun 2026 08:56:52 +0530 Subject: [PATCH 328/450] get ben details using abha ID --- .../controller/AbhaBeneficiaryController.java | 53 +++++++++++++++++++ .../abhaBeneficiary/AbhaBeneficiaryDTO.java | 24 +++++++++ .../com/iemr/flw/dto/iemr/AbhaRequestDTO.java | 9 ++++ .../flw/service/AbhaBeneficiaryService.java | 12 +++++ .../impl/AbhaBeneficiaryServiceImpl.java | 33 ++++++++++++ 5 files changed, 131 insertions(+) create mode 100644 src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java create mode 100644 src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java create mode 100644 src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java diff --git a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java new file mode 100644 index 000000000..b0787a366 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java @@ -0,0 +1,53 @@ +package com.iemr.flw.controller; + +import com.iemr.flw.domain.iemr.AdolescentHealth; +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.identity.GetBenRequestHandler; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import com.iemr.flw.service.AbhaBeneficiaryService; +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("/abha") +public class AbhaBeneficiaryController { + @Autowired + private AbhaBeneficiaryService abhaBeneficiaryService; + + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryController.class); + + + @RequestMapping(value = "/getBeneficiary",method = RequestMethod.POST, headers = "Authorization") + public ResponseEntity> getAllAdolescentHealth(@RequestBody AbhaRequestDTO request ) { + Map response = new HashMap<>(); + try { + if(request.getRequestId()!=null){ + List abhaBeneficiaryDTOList = abhaBeneficiaryService.getBeneficiaryByAbha(request); + + if (abhaBeneficiaryDTOList != null && !abhaBeneficiaryDTOList.isEmpty()) { + response.put("statusCode",200); + response.put("data", abhaBeneficiaryDTOList); + } else { + response.put("statusCode", 5000); + response.put("error", "Invalid/NULL request obj"); + } + } + + } catch (Exception e) { + logger.error("Error in get data : " + e); + response.put("statusCode",5000); + response.put("error","Error in get data : " + e); + + } + return ResponseEntity.ok(response); + } +} diff --git a/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java new file mode 100644 index 000000000..7a71ca426 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java @@ -0,0 +1,24 @@ +package com.iemr.flw.dto.abhaBeneficiary; + +import lombok.Data; + +@Data +public class AbhaBeneficiaryDTO { + private String name; + private String age; + private String abhaId; + private String address; + private String block; + private String blockCode; + private String cardno; + private String district; + private String districtCode; + private String familyId; + private String gender; + private String mobileNo; + private String ruralUrban; + private String villageCode; + private String vws; + private String ward; + +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java new file mode 100644 index 000000000..6b969cdd0 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java @@ -0,0 +1,9 @@ +package com.iemr.flw.dto.iemr; + +import lombok.Data; + +@Data +public class AbhaRequestDTO { + private String requestId; + +} diff --git a/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java new file mode 100644 index 000000000..f8e8d8f86 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java @@ -0,0 +1,12 @@ +package com.iemr.flw.service; + +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +public interface AbhaBeneficiaryService { + + List getBeneficiaryByAbha(AbhaRequestDTO request); +} diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java new file mode 100644 index 000000000..cfd8b32f0 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -0,0 +1,33 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import com.iemr.flw.service.AbhaBeneficiaryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.List; + +@Service +public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { + + @Autowired + private RestTemplate restTemplate; + @Override + public List getBeneficiaryByAbha(AbhaRequestDTO request) { + return getAbhaResponse(request.getRequestId()).getBody(); + } + + ResponseEntity> getAbhaResponse(String requestId) { + String url = "" + requestId; + ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>() { + }); + return response; + + } + +} From 2f753c8ad4a6d4db1862ece26a2465abe6155538 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 12 Jun 2026 13:48:51 +0530 Subject: [PATCH 329/450] get ben details using abha ID --- .../controller/AbhaBeneficiaryController.java | 9 +- .../iemr/flw/domain/iemr/AbhaApiResponse.java | 21 +++++ .../abhaBeneficiary/AbhaBeneficiaryDTO.java | 63 ++++++++++--- .../com/iemr/flw/dto/iemr/AbhaRequestDTO.java | 2 +- .../flw/service/AbhaBeneficiaryService.java | 2 +- .../impl/AbhaBeneficiaryServiceImpl.java | 88 ++++++++++++++++--- 6 files changed, 158 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java diff --git a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java index b0787a366..28276cb86 100644 --- a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java @@ -26,14 +26,15 @@ public class AbhaBeneficiaryController { private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryController.class); - @RequestMapping(value = "/getBeneficiary",method = RequestMethod.POST, headers = "Authorization") + + @RequestMapping(value = "/getBeneficiary",method = RequestMethod.POST) public ResponseEntity> getAllAdolescentHealth(@RequestBody AbhaRequestDTO request ) { Map response = new HashMap<>(); try { - if(request.getRequestId()!=null){ - List abhaBeneficiaryDTOList = abhaBeneficiaryService.getBeneficiaryByAbha(request); + if(request.getCardNo()!=null){ + Object abhaBeneficiaryDTOList = abhaBeneficiaryService.getBeneficiaryByAbha(request); - if (abhaBeneficiaryDTOList != null && !abhaBeneficiaryDTOList.isEmpty()) { + if (abhaBeneficiaryDTOList != null ) { response.put("statusCode",200); response.put("data", abhaBeneficiaryDTOList); } else { diff --git a/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java b/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java new file mode 100644 index 000000000..db38d11ad --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/AbhaApiResponse.java @@ -0,0 +1,21 @@ +package com.iemr.flw.domain.iemr; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; +import lombok.Data; + +import java.util.List; + +@Data +public class AbhaApiResponse { + + @JsonProperty("status_code") + private String statusCode; + + private String message; + + @JsonProperty("data") + @JsonAlias("object_data") + private List data; +} \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java index 7a71ca426..dab9dec3b 100644 --- a/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java +++ b/src/main/java/com/iemr/flw/dto/abhaBeneficiary/AbhaBeneficiaryDTO.java @@ -1,24 +1,65 @@ package com.iemr.flw.dto.abhaBeneficiary; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class AbhaBeneficiaryDTO { - private String name; + @JsonProperty("personName") + private String personName; + + private String firstName; + + private String lastName; + + @JsonProperty("age") private String age; - private String abhaId; + + @JsonProperty("address") private String address; - private String block; - private String blockCode; - private String cardno; + + @JsonProperty("district") private String district; - private String districtCode; - private String familyId; - private String gender; + + @JsonProperty("mobileNo") private String mobileNo; - private String ruralUrban; + + @JsonProperty("block") + private String block; + + @JsonProperty("cardNo") + private String cardNo; + + @JsonProperty("villagename") + private String villagename; + + @JsonProperty("gender") + private String gender; + + @JsonProperty("district_Code") + private String districtCode; + + @JsonProperty("block_Code") + private String blockCode; + + @JsonProperty("village_Code") private String villageCode; - private String vws; - private String ward; + + @JsonProperty("rural_Urban") + private String ruralUrban; + + @JsonProperty("abhaId") + private String abhaId; + + @JsonProperty("vvs") + private String vvs; + + @JsonProperty("familyid") + private String familyid; + + @JsonProperty("dob") + @JsonAlias("dob_secc") + private String dob; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java index 6b969cdd0..0dba46d51 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java @@ -4,6 +4,6 @@ @Data public class AbhaRequestDTO { - private String requestId; + private String cardNo; } diff --git a/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java index f8e8d8f86..02a1281b5 100644 --- a/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java +++ b/src/main/java/com/iemr/flw/service/AbhaBeneficiaryService.java @@ -8,5 +8,5 @@ public interface AbhaBeneficiaryService { - List getBeneficiaryByAbha(AbhaRequestDTO request); + Object getBeneficiaryByAbha(AbhaRequestDTO request); } diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index cfd8b32f0..ae96c1ee2 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -1,33 +1,101 @@ package com.iemr.flw.service.impl; +import com.iemr.flw.domain.iemr.AbhaApiResponse; import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; import com.iemr.flw.dto.iemr.AbhaRequestDTO; +import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.service.AbhaBeneficiaryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; +import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.util.HashMap; import java.util.List; +import java.util.Map; @Service public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { + + @Autowired - private RestTemplate restTemplate; + private BeneficiaryRepo beneficiaryRepo; + + String url = "https://govthealth.cg.gov.in/sna/dkbssyapipool/api/UserRgistration/GetUserDetailsByAyushmanCardNo"; + @Override - public List getBeneficiaryByAbha(AbhaRequestDTO request) { - return getAbhaResponse(request.getRequestId()).getBody(); + public Object getBeneficiaryByAbha(AbhaRequestDTO request) { + + List health = beneficiaryRepo.getBenHealthDetails(request.getCardNo()); + Map response = new HashMap<>(); + + if (health != null && !health.isEmpty()) { + for (Object[] objects : health) { + if (request.getCardNo().equals(String.valueOf(objects[1]))) { + + response.put("statusCode", 5000); + response.put("message", "This ABHA No already exists"); + + return response; + } + } + } + AbhaApiResponse abhaApiResponse = getAbhaResponse(request.getCardNo()).getBody(); + + + if (abhaApiResponse != null && abhaApiResponse.getData() != null) { + + for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { + + String personName = dto.getPersonName(); + + if (personName != null && !personName.trim().isEmpty()) { + + String[] names = personName.trim().split("\\s+", 2); + + dto.setFirstName(names[0]); + + if (names.length > 1) { + dto.setLastName(names[1]); + } else { + dto.setLastName(""); + } + } + } + } + + System.out.println("Status = " + abhaApiResponse.getStatusCode()); + System.out.println("Body = " + abhaApiResponse); + + return abhaApiResponse; } - ResponseEntity> getAbhaResponse(String requestId) { - String url = "" + requestId; - ResponseEntity> response = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference>() { - }); - return response; + public ResponseEntity getAbhaResponse(String requestId) { + RestTemplate restTemplate = new RestTemplate(); + + Map body = new HashMap<>(); + body.put("userId", "*"); + body.put("password", "*"); + body.put("cardNo", requestId); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + HttpEntity request = new HttpEntity<>(body, headers); + + ResponseEntity response = restTemplate.exchange( + url, + HttpMethod.POST, + request, + AbhaApiResponse.class + ); + + System.out.println("Status = " + response.getStatusCode()); + System.out.println("Body = " + response.getBody()); + return response; } } From abe004ccb1477086b2c0c43686439bc5a26dcb21 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 12 Jun 2026 13:51:15 +0530 Subject: [PATCH 330/450] fix isDeactivate issue --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 5c4e1a71a..3fcfd6b38 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -424,7 +424,10 @@ private String getMappingsForAddressIDs(List addressLi 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("isDeactivate", benDetailsRMNCH_OBJ.getIsDeactivate() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id From c2dbfb817fbce2806e0f458b033d0c0f515ae69e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 12 Jun 2026 14:06:59 +0530 Subject: [PATCH 331/450] Fix: Handled isDeactivate null values for old data records by defaulting to false. --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 dec2ad7e2..8f8ccaad6 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -419,7 +419,12 @@ private String getMappingsForAddressIDs(List addressLi 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( + "isDeactivate", + benDetailsRMNCH_OBJ.getIsDeactivate() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id From e5ec6bffe8c5e064f647dae0fbc33185b964620e Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Fri, 12 Jun 2026 14:10:57 +0530 Subject: [PATCH 332/450] Fix: Handled isDeactivate null values for old data records by defaulting to false. (#246) --- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 dec2ad7e2..8f8ccaad6 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -419,7 +419,12 @@ private String getMappingsForAddressIDs(List addressLi 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( + "isDeactivate", + benDetailsRMNCH_OBJ.getIsDeactivate() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); resultMap.put("BenRegId", m.getBenRegId()); // adding asha id / created by - user id From a7b4eae0eed948c6dc18f2c63aeb91e023af0e50 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 13 Jun 2026 22:34:01 +0530 Subject: [PATCH 333/450] fix motivating couples to maintain at least a two-year gap after marriage before first child --- .../com/iemr/flw/repo/identity/BeneficiaryRepo.java | 1 + .../com/iemr/flw/service/impl/ChildServiceImpl.java | 7 ++++++- .../com/iemr/flw/service/impl/IncentiveLogicImpl.java | 10 ++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) 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 864c31a8d..0acba1926 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -24,6 +24,7 @@ public interface BeneficiaryRepo extends JpaRepository findById(Long benID); + Optional findByBenficieryid(Long benID); @Query(value = "SELECT beneficiaryRegID FROM db_identity.i_beneficiarydetails_rmnch WHERE BeneficiaryId = :benId", nativeQuery = true) Long getBenRegIdFromBenId(@Param("benId") Long benId); diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index eeea84054..89e4288e1 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -50,6 +50,9 @@ public String getByUserId(GetBenRequestHandler dto) { // ChildRegisterDTO childDTO = modelMapper.map(childRegister, ChildRegisterDTO.class); // result.add(childDTO); // }); + for (ChildRegister childRegister : childRegisterList) { + processFirstChildIncentive(childRegister); + } List result = childRegisterList.stream() .map(childRegister -> modelMapper.map(childRegister, ChildRegisterDTO.class)) .collect(Collectors.toList()); @@ -94,7 +97,9 @@ public void processFirstChildIncentive(ChildRegister childRegister) { Long benId = childRegister.getBenId(); RMNCHBeneficiaryDetailsRmnch beneficiary = - beneficiaryRepo.findById(benId).orElse(null); + beneficiaryRepo.findByBenficieryid(benId).orElse(null); + + logger.info("Child ben Id:" + beneficiary.getBenficieryid()); if (beneficiary == null || beneficiary.getDateMarriage() == null) { return; diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 87cb83f91..55aaea08a 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -493,6 +493,16 @@ public IncentiveActivityRecord incentiveForSecondChildGap(Long benId, Timestamp userId); } + if (stateCode.equals(StateCode.AM.getStateCode())) { + return processIncentive( + activityName, + GroupName.FAMILY_PLANNING.getDisplayName(), + benId, + secondChildDob, + secondChildDob1, + userId); + } + // state not supported logger.info("No incentive mapping for stateCode: {}", stateCode); return null; From 5a45a58eb11c4aa9235c40adbd95c8606fee4fd5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 18:27:34 +0530 Subject: [PATCH 334/450] Motivating 70% women to take iron tablets --- .../repo/iemr/EligibleCoupleRegisterRepo.java | 2 + .../flw/service/impl/ChildServiceImpl.java | 6 +- .../service/impl/IncentiveServiceImpl.java | 62 ++++++++++++++++++- 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java index 2eae0b059..b6682ee02 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/EligibleCoupleRegisterRepo.java @@ -14,6 +14,8 @@ public interface EligibleCoupleRegisterRepo extends JpaRepository findByCreatedBy(String userName); + @Query(" SELECT ecr FROM EligibleCoupleRegister ecr WHERE ecr.createdBy = :userId and ecr.createdDate >= :fromDate and ecr.createdDate <= :toDate") List getECRegRecords(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index 89e4288e1..a641a2eff 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -50,9 +50,7 @@ public String getByUserId(GetBenRequestHandler dto) { // ChildRegisterDTO childDTO = modelMapper.map(childRegister, ChildRegisterDTO.class); // result.add(childDTO); // }); - for (ChildRegister childRegister : childRegisterList) { - processFirstChildIncentive(childRegister); - } + List result = childRegisterList.stream() .map(childRegister -> modelMapper.map(childRegister, ChildRegisterDTO.class)) .collect(Collectors.toList()); @@ -93,8 +91,8 @@ public String save(List childRegisterDTOs) throws Exception { } public void processFirstChildIncentive(ChildRegister childRegister) { - Long benId = childRegister.getBenId(); + logger.info("BenId:"+benId); RMNCHBeneficiaryDetailsRmnch beneficiary = beneficiaryRepo.findByBenficieryid(benId).orElse(null); 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 a65847052..196c3b54c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -29,6 +29,7 @@ import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; @@ -65,6 +66,12 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private UserService userService; + @Autowired + private EligibleCoupleRegisterRepo eligibleCoupleRegisterRepo; + + @Autowired + private IFAFormSubmissionRepository ifaFormSubmissionRepository; + // ================= MASTER SAVE ================= @Override @@ -190,7 +197,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { } try { - + addIncentiveForIronTablets(request.getAshaId()); incentiveOfNcdReferal(request.getAshaId(), request.getVillageID()); } catch (Exception e) { @@ -702,4 +709,57 @@ record = new IncentiveActivityRecord(); } } + private void addIncentiveForIronTablets(Integer userId){ + IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); + + String userName = userService.getUserDetail(userId).getUserName(); + Integer stateId = userService.getUserDetail(userId).getStateId(); + if(userName!=null){ + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); + List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); + + if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ + Integer percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; + if(percentage>70){ + if(stateId.equals(StateCode.AM.getStateCode())){ + addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityAM,userId,userName); + + } + if(stateId.equals(StateCode.CG.getStateCode())){ + addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityCG,userId,userName); + + } + } + } + + } + + + } + + private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM,Integer userId,String userName) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + + LocalDate ifaVisitDate = LocalDate.parse(ifaFormSubmissionData.getVisitDate(), formatter); + + Timestamp ifaVisitDateTimestamp = Timestamp.valueOf(ifaVisitDate.atStartOfDay()); + + IncentiveActivityRecord incentiveActivityRecord = recordRepo.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(userId); + incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + recordRepo.save(incentiveActivityRecord); + } + } + } From 84ee74a26ee7a6d027bd12f415c96038e0840a12 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 18:43:41 +0530 Subject: [PATCH 335/450] Motivating 70% women to take iron tablets --- .../flw/repo/iemr/IFAFormSubmissionRepository.java | 8 ++++++++ .../iemr/flw/service/impl/IncentiveServiceImpl.java | 13 +++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java index 40cbd60bc..0b1b5ff72 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IFAFormSubmissionRepository.java @@ -2,6 +2,8 @@ import com.iemr.flw.domain.iemr.IFAFormSubmissionData; 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; @@ -9,4 +11,10 @@ public interface IFAFormSubmissionRepository extends JpaRepository { List findByUserId(Integer userName); + @Query("SELECT i FROM IFAFormSubmissionData i " + + "WHERE i.userId = :userId " + + "AND i.visitDate = :visitDate") + List findTodayData( + @Param("userId") Integer userId, + @Param("visitDate") String visitDate); } 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 196c3b54c..ab060a51a 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -716,8 +716,17 @@ private void addIncentiveForIronTablets(Integer userId){ String userName = userService.getUserDetail(userId).getUserName(); Integer stateId = userService.getUserDetail(userId).getStateId(); if(userName!=null){ - List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); - List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); + LocalDate today = LocalDate.now(); + String todayDate = LocalDate.now() + .format(DateTimeFormatter.ofPattern("dd-MM-yyyy")); + + Timestamp startDate = Timestamp.valueOf(today.atStartOfDay()); + Timestamp endDate = Timestamp.valueOf(today.plusDays(1).atStartOfDay()); + + List eligibleCoupleRegisters = + eligibleCoupleRegisterRepo.getECRegRecords( + userName, startDate, endDate); + List ifaFormSubmissionData = ifaFormSubmissionRepository.findTodayData(userId,todayDate); if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ Integer percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; From 42606ed39e6103b66f534649982a0ba445ed5be0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 18:57:21 +0530 Subject: [PATCH 336/450] Motivating 70% women to take iron tablets --- .../flw/service/impl/IncentiveServiceImpl.java | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) 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 ab060a51a..abdd0296c 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -716,21 +716,12 @@ private void addIncentiveForIronTablets(Integer userId){ String userName = userService.getUserDetail(userId).getUserName(); Integer stateId = userService.getUserDetail(userId).getStateId(); if(userName!=null){ - LocalDate today = LocalDate.now(); - String todayDate = LocalDate.now() - .format(DateTimeFormatter.ofPattern("dd-MM-yyyy")); - - Timestamp startDate = Timestamp.valueOf(today.atStartOfDay()); - Timestamp endDate = Timestamp.valueOf(today.plusDays(1).atStartOfDay()); - - List eligibleCoupleRegisters = - eligibleCoupleRegisterRepo.getECRegRecords( - userName, startDate, endDate); - List ifaFormSubmissionData = ifaFormSubmissionRepository.findTodayData(userId,todayDate); + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); + List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ Integer percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; - if(percentage>70){ + if(percentage>=70){ if(stateId.equals(StateCode.AM.getStateCode())){ addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityAM,userId,userName); From 5fc2a0cb776f6682136c802061894d63b9e9653a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 19:08:58 +0530 Subject: [PATCH 337/450] Motivating 70% women to take iron tablets --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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 abdd0296c..9aacd32a6 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -718,6 +718,8 @@ private void addIncentiveForIronTablets(Integer userId){ if(userName!=null){ List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); + logger.info("eligibleCoupleRegisters :"+eligibleCoupleRegisters.size()); + logger.info("ifaFormSubmissionData :"+ifaFormSubmissionData.size()); if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ Integer percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; From ab21ac111c0434d25de1602b7393ad5659530082 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 19:19:22 +0530 Subject: [PATCH 338/450] Motivating 70% women to take iron tablets --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9aacd32a6..eac244691 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -750,7 +750,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); if(incentiveActivityRecord==null){ incentiveActivityRecord = new IncentiveActivityRecord(); - incentiveActivityRecord.setActivityId(ifaFormSubmissionData.getId()); + incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); incentiveActivityRecord.setCreatedDate(ifaVisitDateTimestamp); incentiveActivityRecord.setStartDate(ifaVisitDateTimestamp); incentiveActivityRecord.setEndDate(ifaVisitDateTimestamp); From e9133e1030e6ec8e31896570e654c486531f61bf Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 19:26:42 +0530 Subject: [PATCH 339/450] Motivating 70% women to take iron tablets --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 eac244691..36676dec5 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -722,7 +722,9 @@ private void addIncentiveForIronTablets(Integer userId){ logger.info("ifaFormSubmissionData :"+ifaFormSubmissionData.size()); if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ - Integer percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; + int percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; + logger.info("percentage :"+percentage); + if(percentage>=70){ if(stateId.equals(StateCode.AM.getStateCode())){ addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityAM,userId,userName); @@ -746,6 +748,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent LocalDate ifaVisitDate = LocalDate.parse(ifaFormSubmissionData.getVisitDate(), formatter); Timestamp ifaVisitDateTimestamp = Timestamp.valueOf(ifaVisitDate.atStartOfDay()); + logger.info("IFA incentive"); IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); if(incentiveActivityRecord==null){ @@ -761,6 +764,8 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent incentiveActivityRecord.setAshaId(userId); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); recordRepo.save(incentiveActivityRecord); + logger.info("saved IFA incentive"); + } } From 336e5bee55f270bb44a0e9ae919e65fed5c60da7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 19:32:24 +0530 Subject: [PATCH 340/450] Motivating 70% women to take iron tablets --- .../service/impl/IncentiveServiceImpl.java | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) 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 36676dec5..d53f2d925 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -721,18 +721,31 @@ private void addIncentiveForIronTablets(Integer userId){ logger.info("eligibleCoupleRegisters :"+eligibleCoupleRegisters.size()); logger.info("ifaFormSubmissionData :"+ifaFormSubmissionData.size()); - if(!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()){ - int percentage = (ifaFormSubmissionData.size()/eligibleCoupleRegisters.size())*100; - logger.info("percentage :"+percentage); + if (!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()) { - if(percentage>=70){ - if(stateId.equals(StateCode.AM.getStateCode())){ - addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityAM,userId,userName); + int percentage = (int) (((double) ifaFormSubmissionData.size() + / eligibleCoupleRegisters.size()) * 100); + logger.info("IFA Count : {}", ifaFormSubmissionData.size()); + logger.info("Eligible Couple Count : {}", eligibleCoupleRegisters.size()); + logger.info("Percentage : {}", percentage); + + if (percentage >= 70) { + + if (stateId.equals(StateCode.AM.getStateCode())) { + addIFAIncentive( + ifaFormSubmissionData.get(ifaFormSubmissionData.size() - 1), + incentiveActivityAM, + userId, + userName); } - if(stateId.equals(StateCode.CG.getStateCode())){ - addIFAIncentive(ifaFormSubmissionData.get(ifaFormSubmissionData.size()-1),incentiveActivityCG,userId,userName); + if (stateId.equals(StateCode.CG.getStateCode())) { + addIFAIncentive( + ifaFormSubmissionData.get(ifaFormSubmissionData.size() - 1), + incentiveActivityCG, + userId, + userName); } } } From b335f41758cc54c7e316b51d279b7ac17ef675b2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sun, 14 Jun 2026 21:43:57 +0530 Subject: [PATCH 341/450] Motivating 70% women to take iron tablets --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 d53f2d925..3999be581 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -730,7 +730,7 @@ private void addIncentiveForIronTablets(Integer userId){ logger.info("Eligible Couple Count : {}", eligibleCoupleRegisters.size()); logger.info("Percentage : {}", percentage); - if (percentage >= 70) { + if (percentage >= 50) { if (stateId.equals(StateCode.AM.getStateCode())) { addIFAIncentive( From c26b8feb32712bbb2179ef00bee7c6408753fc67 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 11:37:39 +0530 Subject: [PATCH 342/450] fix hbnc related incentive issue --- .../com/iemr/flw/repo/iemr/PNCVisitRepo.java | 2 + .../service/impl/ChildCareServiceImpl.java | 49 +++++++++++++++++-- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java index 28675daad..39da97da4 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/PNCVisitRepo.java @@ -16,4 +16,6 @@ public interface PNCVisitRepo extends JpaRepository { List getPNCForPW(@Param("userId") String userId); PNCVisit findPNCVisitByBenIdAndPncPeriodAndIsActive(Long benId, Integer pncVisit, Boolean isActive); + + List findByBenId(Long benId); } 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 9479191ae..9f539404e 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -88,6 +88,11 @@ public class ChildCareServiceImpl implements ChildCareService { @Autowired private IncentiveLogicService incentiveLogicService; + @Autowired + private ANCVisitRepo ancVisitRepo; + @Autowired + private PNCVisitRepo pncVisitRepo; + @Override public String registerHBYC(List hbycDTOs) { @@ -261,7 +266,10 @@ public List getHBNCDetails(GetBenRequestHandler dto) { responseDTO.setFields(fields); result.add(responseDTO); + } + checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); + } catch (Exception e) { logger.error("Error in getHBNCDetails: ", e); @@ -831,14 +839,32 @@ private void checkAndAddHbyncIncentives(List hbycList) { private void checkAndAddHbncIncentives(List hbncVisits, Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); hbncVisits.forEach(hbncVisit -> { - GroupName.setIsCh(false); Long benId = hbncVisit.getBeneficiaryId(); - if (stateCode.equals(StateCode.AM)) { + if (stateCode.equals(StateCode.AM.getStateCode())) { if (hbncVisit.getVisit_day().equals("42nd Day")) { IncentiveActivity visitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.CHILD_HEALTH.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); + } + if (hbncVisit.getVisit_day().equals("42th Day")) { + if(!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ + if(ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()){ + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + + } + } + if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ + if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()){ + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + + } + } + } logger.info("getDischarged_from_sncu" + hbncVisit.getDischarged_from_sncu()); @@ -859,10 +885,23 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } if (stateCode.equals(StateCode.CG.getStateCode())) { - if (hbncVisit.getVisit_day().equals("7th Day")) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (hbncVisit.getVisit_day().equals("42th Day")) { + if(!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ + if(ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()){ + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + + } + } + if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ + if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()){ + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + } + } } } From aec9d2da7f51e51cc628965e7993599486b3c584 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 11:45:15 +0530 Subject: [PATCH 343/450] fix hbnc related incentive issue --- src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java | 2 ++ 1 file changed, 2 insertions(+) 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 067e6acc3..e44815668 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java @@ -21,4 +21,6 @@ List getANCForPW(@Param("userId") String userId, @Query ANCVisit findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); + List findByBenId(Long benId); + } From 31b34d7a5895f3847a128e56443bd309b61777cd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 12:14:24 +0530 Subject: [PATCH 344/450] fix hbnc related incentive issue --- src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java | 2 +- .../iemr/flw/service/impl/MaternalHealthServiceImpl.java | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) 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 e44815668..6d22f7525 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ANCVisitRepo.java @@ -19,7 +19,7 @@ List getANCForPW(@Param("userId") String userId, @Query - ANCVisit findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); + List findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); List findByBenId(Long benId); 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 ce7bc1d16..e9cdf7aff 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -163,9 +163,12 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getAncVisit()); - ANCVisit ancVisit = + List ancVisitList = ancVisitRepo.findANCVisitByBenIdAndAncVisitAndIsActive(it.getBenId(), it.getAncVisit(), true); - + ANCVisit ancVisit = new ANCVisit(); + if(!ancVisitList.isEmpty()){ + ancVisit = ancVisitList.get(0); + } logger.info("ANC visit fetch completed"); if (ancVisit != null) { From 4a95ef7e8eb2496880ab87c3f7f4f3b8bb65dfa9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 12:59:12 +0530 Subject: [PATCH 345/450] fix hbnc related incentive issue --- .../repo/iemr/PregnantWomanRegisterRepo.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java index 260717444..0d008a143 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java @@ -16,6 +16,6 @@ public interface PregnantWomanRegisterRepo extends JpaRepository getPWRWithBen(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); - PregnantWomanRegister findPregnantWomanRegisterByBenIdAndIsActive(Long benId, Boolean isActive); + List findPregnantWomanRegisterByBenIdAndIsActive(Long benId, Boolean isActive); } 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 e9cdf7aff..ccac51e0d 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -96,19 +96,19 @@ public String registerPregnantWoman(List pregnantWomanDTOs) { try { List pwrList = new ArrayList<>(); pregnantWomanDTOs.forEach(it -> { - PregnantWomanRegister pwr = + List pwr = pregnantWomanRegisterRepo.findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); - if (pwr != null) { - Long id = pwr.getId(); + if (pwr != null && !pwr.isEmpty()) { + Long id = pwr.get(0).getId(); modelMapper.map(it, pwr); - pwr.setId(id); + pwr.get(0).setId(id); } else { - pwr = new PregnantWomanRegister(); + pwr = new ArrayList<>(); modelMapper.map(it, pwr); - pwr.setId(null); + pwr.get(0).setId(null); } - pwrList.add(pwr); + pwrList.add(pwr.get(0)); }); pregnantWomanRegisterRepo.saveAll(pwrList); @@ -192,7 +192,7 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { logger.info("Beneficiary Reg Id fetched: {}", benRegId); // Saving data in BenVisitDetails table - PregnantWomanRegister pwr = pregnantWomanRegisterRepo + List pwr = pregnantWomanRegisterRepo .findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); logger.info("PregnantWomanRegister fetched"); @@ -222,14 +222,14 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { ancCare.setBenVisitId(benVisitDetail.getBenVisitId()); ancCare.setBeneficiaryRegId(benRegId); - if (pwr != null) { + if (pwr != null && !pwr.isEmpty()) { logger.info("LMP found calculating EDD"); - ancCare.setLastMenstrualPeriodLmp(pwr.getLmpDate()); + ancCare.setLastMenstrualPeriodLmp(pwr.get(0).getLmpDate()); Calendar cal = Calendar.getInstance(); - cal.setTime(pwr.getLmpDate()); + cal.setTime(pwr.get(0).getLmpDate()); cal.add(Calendar.DAY_OF_WEEK, 280); ancCare.setExpectedDateofDelivery(new Timestamp(cal.getTime().getTime())); From 44f30ba44cbe6cc2b53db09e02c1ce54c90eeeb6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 13:08:23 +0530 Subject: [PATCH 346/450] fix hbnc related incentive issue --- .../repo/iemr/PregnantWomanRegisterRepo.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java index 0d008a143..260717444 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/PregnantWomanRegisterRepo.java @@ -16,6 +16,6 @@ public interface PregnantWomanRegisterRepo extends JpaRepository getPWRWithBen(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); - List findPregnantWomanRegisterByBenIdAndIsActive(Long benId, Boolean isActive); + PregnantWomanRegister findPregnantWomanRegisterByBenIdAndIsActive(Long benId, Boolean isActive); } 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 ccac51e0d..e9cdf7aff 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -96,19 +96,19 @@ public String registerPregnantWoman(List pregnantWomanDTOs) { try { List pwrList = new ArrayList<>(); pregnantWomanDTOs.forEach(it -> { - List pwr = + PregnantWomanRegister pwr = pregnantWomanRegisterRepo.findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); - if (pwr != null && !pwr.isEmpty()) { - Long id = pwr.get(0).getId(); + if (pwr != null) { + Long id = pwr.getId(); modelMapper.map(it, pwr); - pwr.get(0).setId(id); + pwr.setId(id); } else { - pwr = new ArrayList<>(); + pwr = new PregnantWomanRegister(); modelMapper.map(it, pwr); - pwr.get(0).setId(null); + pwr.setId(null); } - pwrList.add(pwr.get(0)); + pwrList.add(pwr); }); pregnantWomanRegisterRepo.saveAll(pwrList); @@ -192,7 +192,7 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { logger.info("Beneficiary Reg Id fetched: {}", benRegId); // Saving data in BenVisitDetails table - List pwr = pregnantWomanRegisterRepo + PregnantWomanRegister pwr = pregnantWomanRegisterRepo .findPregnantWomanRegisterByBenIdAndIsActive(it.getBenId(), true); logger.info("PregnantWomanRegister fetched"); @@ -222,14 +222,14 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { ancCare.setBenVisitId(benVisitDetail.getBenVisitId()); ancCare.setBeneficiaryRegId(benRegId); - if (pwr != null && !pwr.isEmpty()) { + if (pwr != null) { logger.info("LMP found calculating EDD"); - ancCare.setLastMenstrualPeriodLmp(pwr.get(0).getLmpDate()); + ancCare.setLastMenstrualPeriodLmp(pwr.getLmpDate()); Calendar cal = Calendar.getInstance(); - cal.setTime(pwr.get(0).getLmpDate()); + cal.setTime(pwr.getLmpDate()); cal.add(Calendar.DAY_OF_WEEK, 280); ancCare.setExpectedDateofDelivery(new Timestamp(cal.getTime().getTime())); From 5045a0cd325691a91036a1eb55ecdcc0116ee6c6 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 14:54:18 +0530 Subject: [PATCH 347/450] add get bene deatils using nic api --- src/main/environment/common_ci.properties | 7 +++ src/main/environment/common_docker.properties | 5 ++ .../controller/AbhaBeneficiaryController.java | 4 +- .../flw/controller/ChildCareController.java | 6 ++- .../impl/AbhaBeneficiaryServiceImpl.java | 18 ++++--- .../service/impl/ChildCareServiceImpl.java | 47 +++++++++---------- .../impl/MaternalHealthServiceImpl.java | 15 +----- 7 files changed, 56 insertions(+), 46 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index af5c31d0b..238d5f926 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -43,3 +43,10 @@ abha.client.id=@env.ABHA_CLIENT_ID@ abha.client.secret=@env.ABHA_CLIENT_SECRET@ abha.token.url=@env.ABHA_TOKEN_URL@ abha.xcmid=@env.ABHA_XCM_ID@ + +# GovThealth API Config +govthealth.user.details.url=@env.GOVTHEALTH_USER_DETAILS_URL@ +govthealth.user.id=@env.GOVTHEALTH_USER_ID@ +govthealth.password=@env.GOVTHEALTH_PASSWORD@ + + diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index cce60f894..073091334 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -43,5 +43,10 @@ abha.client.secret=${ABHA_CLIENT_SECRET} abha.token.url=${ABHA_TOKEN_URL} abha.xcmid=${ABHA_XCM_ID} +# GovThealth API Config +govthealth.user.details.url=${GOVTHEALTH_USER_DETAILS_URL} +govthealth.user.id=${GOVTHEALTH_USER_ID} +govthealth.password=${GOVTHEALTH_PASSWORD} + diff --git a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java index 28276cb86..8025de558 100644 --- a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java @@ -18,7 +18,7 @@ import java.util.Map; @RestController -@RequestMapping("/abha") +@RequestMapping("/UserRegistration") public class AbhaBeneficiaryController { @Autowired private AbhaBeneficiaryService abhaBeneficiaryService; @@ -27,7 +27,7 @@ public class AbhaBeneficiaryController { - @RequestMapping(value = "/getBeneficiary",method = RequestMethod.POST) + @RequestMapping(value = "/GetUserDetailsByAyushmanCardNo",method = RequestMethod.POST) public ResponseEntity> getAllAdolescentHealth(@RequestBody AbhaRequestDTO request ) { Map response = new HashMap<>(); try { diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 0e45b36ac..f1021b7f2 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -10,6 +10,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; @@ -39,6 +40,9 @@ public class ChildCareController { @Autowired private ChildCareService childCareService; + @Autowired + private UserService userService; + @Autowired private JwtUtil jwtUtil; @@ -249,7 +253,7 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s if(token!=null){ Integer userId = jwtUtil.extractUserId(token); - String userName = jwtUtil.extractUsername(token); + String userName = userService.getUserDetail(userId).getUserName(); String responseObject = childCareService.saveSamDetails(samRequest,userId,userName); if (responseObject != null) { diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index ae96c1ee2..6c2a91775 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -6,6 +6,7 @@ import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.service.AbhaBeneficiaryService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.stereotype.Service; @@ -18,12 +19,17 @@ @Service public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { - - @Autowired private BeneficiaryRepo beneficiaryRepo; - String url = "https://govthealth.cg.gov.in/sna/dkbssyapipool/api/UserRgistration/GetUserDetailsByAyushmanCardNo"; + @Value("${govthealth.user.details.url}") + private String getUserDetailsUrl; + + @Value("${govthealth.user.id}") + private String govthealthUserId; + + @Value("${govthealth.password}") + private String govthealthPassword; @Override public Object getBeneficiaryByAbha(AbhaRequestDTO request) { @@ -76,8 +82,8 @@ public ResponseEntity getAbhaResponse(String requestId) { RestTemplate restTemplate = new RestTemplate(); Map body = new HashMap<>(); - body.put("userId", "*"); - body.put("password", "*"); + body.put("userId",govthealthUserId); + body.put("password", govthealthPassword); body.put("cardNo", requestId); HttpHeaders headers = new HttpHeaders(); @@ -86,7 +92,7 @@ public ResponseEntity getAbhaResponse(String requestId) { HttpEntity request = new HttpEntity<>(body, headers); ResponseEntity response = restTemplate.exchange( - url, + getUserDetailsUrl, HttpMethod.POST, request, AbhaApiResponse.class 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 4963e1998..4906ce8bf 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -456,7 +456,7 @@ public List getAllChildVaccines(String category) { } @Override - public String saveSamDetails(List samRequest,Integer userId,String userName) { + public String saveSamDetails(List samRequest, Integer userId, String userName) { try { List vaccinationList = new ArrayList<>(); @@ -509,7 +509,7 @@ public String saveSamDetails(List samRequest,Integer userId,String userN samVisitRepository.saveAll(vaccinationList); // ✅ Handle incentive logic - checkAndAddSamVisitNRCReferalIncentive(vaccinationList,userId); + checkAndAddSamVisitNRCReferalIncentive(vaccinationList, userId); return "Saved/Updated " + samRequest.size() + " SAM visit records successfully"; } catch (Exception e) { @@ -582,7 +582,7 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque } @Override - public String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId) { + public String saveOrsDistributionDetails(List orsDistributionDTOS, Integer userId) { try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List orsDistributionList = new ArrayList<>(); @@ -667,9 +667,9 @@ private LocalDate parseDate(String dateStr) { } @Override - public List saveAllIfa(List dtoList,Integer userId) { + public List saveAllIfa(List dtoList, Integer userId) { List savedList = dtoList.stream() - .map(dto ->mapToEntity(dto,userId)) + .map(dto -> mapToEntity(dto, userId)) .map(ifaDistributionRepository::save) .toList(); @@ -749,7 +749,7 @@ private IfaDistributionDTO mapToDTO(IfaDistribution entity) { } // 🔄 Helper method to convert DTO → Entity - private IfaDistribution mapToEntity(IfaDistributionDTO dto,Integer userId) { + private IfaDistribution mapToEntity(IfaDistributionDTO dto, Integer userId) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); IfaDistribution entity = new IfaDistribution(); @@ -778,12 +778,12 @@ private IfaDistribution mapToEntity(IfaDistributionDTO dto,Integer userId) { return entity; } - private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Integer userId) { + private void checkAndAddSamVisitNRCReferalIncentive(List samVisits, Integer userId) { 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(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { + if (userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { if (samreferralnrcActivityAm != null) { if (samVisit.getIsChildReferredNrc().equals("Yes")) { @@ -792,7 +792,7 @@ private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Int } } - if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())){ + if (userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())) { if (samreferralnrcActivityCH != null) { if (samVisit.getIsChildReferredNrc().equals("Yes")) { createIncentiveRecordforSamReferalToNrc(samVisit, samVisit.getBeneficiaryId(), samreferralnrcActivityCH, samVisit.getCreatedBy()); @@ -801,9 +801,6 @@ private void checkAndAddSamVisitNRCReferalIncentive(List samVisits,Int } - - - }); } @@ -877,16 +874,16 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } if (hbncVisit.getVisit_day().equals("42th Day")) { - if(!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ - if(ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()){ + if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()) { IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); } } - if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ - if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()){ + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()) { IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); @@ -915,22 +912,24 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI if (stateCode.equals(StateCode.CG.getStateCode())) { if (hbncVisit.getVisit_day().equals("42th Day")) { - if(!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ - if(ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()){ + if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed() && pncVisitRepo.findByBenId(hbncVisit + .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); } } - if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()){ - if(!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()){ - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty() && pncVisitRepo.findByBenId(hbncVisit + .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); - } - } + } + } } } 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 4c8e25313..348477fe6 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -607,10 +607,10 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) } } - if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MiniLap")) { + if (ect.getContraceptionMethod() != null && (ect.getContraceptionMethod().equals("MiniLap") || ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)"))) { IncentiveActivity miniLapActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", GroupName.FAMILY_PLANNING.getDisplayName()); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); if (miniLapActivity != null) { addIncenticeRecord(ect, userId, miniLapActivity); } @@ -633,18 +633,7 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) } } - if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("POST PARTUM STERILIZATION (PPS)")) { - if(stateId.equals(StateCode.AM.getStateCode())){ - IncentiveActivity ppsActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPS", GroupName.FAMILY_PLANNING.getDisplayName()); - if (ppsActivityAM != null) { - addIncenticeRecord(ect, userId, ppsActivityAM); - } - } - - - } } // logic for cg if(stateId.equals(StateCode.CG.getStateCode())){ From 0cfe88e246a63304aa847f60ccac89760d38878b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 17:26:02 +0530 Subject: [PATCH 348/450] add get bene deatils using nic api --- .../impl/AbhaBeneficiaryServiceImpl.java | 80 ++++++++++++++----- .../impl/SupervisorDashboardServiceImpl.java | 1 + 2 files changed, 62 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 6c2a91775..155f98b6c 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -1,10 +1,13 @@ package com.iemr.flw.service.impl; +import com.google.gson.Gson; +import com.iemr.flw.controller.AbhaBeneficiaryController; import com.iemr.flw.domain.iemr.AbhaApiResponse; import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; import com.iemr.flw.dto.iemr.AbhaRequestDTO; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.service.AbhaBeneficiaryService; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; @@ -12,6 +15,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,6 +23,9 @@ @Service public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryService.class); + + @Autowired private BeneficiaryRepo beneficiaryRepo; @@ -34,32 +41,54 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { @Override public Object getBeneficiaryByAbha(AbhaRequestDTO request) { - List health = beneficiaryRepo.getBenHealthDetails(request.getCardNo()); - Map response = new HashMap<>(); + try { - if (health != null && !health.isEmpty()) { - for (Object[] objects : health) { - if (request.getCardNo().equals(String.valueOf(objects[1]))) { + AbhaApiResponse abhaApiResponse = + getAbhaResponse(request.getCardNo()).getBody(); - response.put("statusCode", 5000); - response.put("message", "This ABHA No already exists"); + if (abhaApiResponse == null || abhaApiResponse.getData() == null) { - return response; - } + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", "No data found"); + + return response; } - } - AbhaApiResponse abhaApiResponse = getAbhaResponse(request.getCardNo()).getBody(); + for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { - if (abhaApiResponse != null && abhaApiResponse.getData() != null) { + // Check if ABHA already exists in system + List health = + beneficiaryRepo.getBenHealthDetails(dto.getAbhaId()); - for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { + if (health != null && !health.isEmpty()) { + + for (Object[] objects : health) { + + if (objects != null + && objects.length > 1 + && dto.getAbhaId() != null + && dto.getAbhaId() + .equals(String.valueOf(objects[1]))) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "This ABHA No already exists"); + return response; + } + } + } + + // Split name into firstName and lastName String personName = dto.getPersonName(); - if (personName != null && !personName.trim().isEmpty()) { + if (personName != null + && !personName.trim().isEmpty()) { - String[] names = personName.trim().split("\\s+", 2); + String[] names = + personName.trim().split("\\s+", 2); dto.setFirstName(names[0]); @@ -70,12 +99,25 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { } } } - } - System.out.println("Status = " + abhaApiResponse.getStatusCode()); - System.out.println("Body = " + abhaApiResponse); + logger.info("ABHA Response Status : {}", + abhaApiResponse.getStatusCode()); + + logger.info("ABHA Response : {}", + new Gson().toJson(abhaApiResponse)); - return abhaApiResponse; + return abhaApiResponse; + + } catch (Exception e) { + + logger.error("Error while fetching beneficiary by ABHA", e); + + Map response = new HashMap<>(); + response.put("statusCode", 500); + response.put("message", "Internal Server Error"); + + return response; + } } public ResponseEntity getAbhaResponse(String requestId) { diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index e28e1b0fa..5e61bc7ae 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -382,6 +382,7 @@ public int updateApprovalStatus(Integer ashaId, Timestamp endDate = Timestamp.valueOf(endLocalDate.atStartOfDay()); Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); + logger.info("Asha Supervisor User Id : {}", ashaSupervisorUserId); String ashaSupervisorUsername = userServiceRoleRepo.getUserNamedByUserId(ashaSupervisorUserId); if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { From eea4222c5f4ec3284d4ba2d5c3185577e65adf74 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 17:32:32 +0530 Subject: [PATCH 349/450] add get bene deatils using nic api --- .../impl/AbhaBeneficiaryServiceImpl.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 155f98b6c..d37dd9d47 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -29,14 +29,14 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { @Autowired private BeneficiaryRepo beneficiaryRepo; - @Value("${govthealth.user.details.url}") - private String getUserDetailsUrl; - - @Value("${govthealth.user.id}") - private String govthealthUserId; - - @Value("${govthealth.password}") - private String govthealthPassword; +// @Value("${govthealth.user.details.url}") +// private String getUserDetailsUrl; +// +// @Value("${govthealth.user.id}") +// private String govthealthUserId; +// +// @Value("${govthealth.password}") +// private String govthealthPassword; @Override public Object getBeneficiaryByAbha(AbhaRequestDTO request) { @@ -124,8 +124,8 @@ public ResponseEntity getAbhaResponse(String requestId) { RestTemplate restTemplate = new RestTemplate(); Map body = new HashMap<>(); - body.put("userId",govthealthUserId); - body.put("password", govthealthPassword); + body.put("userId","govthealthUserId"); + body.put("password", "govthealthPassword"); body.put("cardNo", requestId); HttpHeaders headers = new HttpHeaders(); @@ -134,7 +134,7 @@ public ResponseEntity getAbhaResponse(String requestId) { HttpEntity request = new HttpEntity<>(body, headers); ResponseEntity response = restTemplate.exchange( - getUserDetailsUrl, + "getUserDetailsUrl", HttpMethod.POST, request, AbhaApiResponse.class From 22c03dfc1595e237fc0fce51f54f21fbebbcc168 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 17:47:36 +0530 Subject: [PATCH 350/450] add get bene deatils using nic api --- .../iemr/flw/controller/IRSRoundController.java | 5 +++-- .../flw/service/impl/BeneficiaryServiceImpl.java | 5 +++-- .../impl/SupervisorDashboardServiceImpl.java | 15 ++++++++------- .../iemr/flw/utils/JwtUserIdValidationFilter.java | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IRSRoundController.java b/src/main/java/com/iemr/flw/controller/IRSRoundController.java index 13193e05e..77047f89c 100644 --- a/src/main/java/com/iemr/flw/controller/IRSRoundController.java +++ b/src/main/java/com/iemr/flw/controller/IRSRoundController.java @@ -5,6 +5,7 @@ import com.iemr.flw.dto.iemr.IRSRoundListDTO; import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.IRSRoundService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import org.springframework.beans.factory.annotation.Autowired; @@ -30,7 +31,7 @@ public class IRSRoundController { private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userServiceRoleRepo; + private UserService userService; @PostMapping(value = "/add") public ResponseEntity> addRound(@RequestBody IRSRoundListDTO dto,@RequestHeader("jwtToken") String token) { @@ -42,7 +43,7 @@ public ResponseEntity> addRound(@RequestBody IRSRoundListDTO return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response) ; } Integer userId = jwtUtil.extractUserId(token); - List s = irsRoundService.addRounds(dto.getRounds(), userId, userServiceRoleRepo.getUserNamedByUserId(userId)); + List s = irsRoundService.addRounds(dto.getRounds(), userId, userService.getUserDetail(userId).getUserName()); if (s.size() != 0) { Map data = new HashMap<>(); data.put("entries", s); 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 c7edccc7a..518e57599 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -23,6 +23,7 @@ import com.iemr.flw.masterEnum.GroupName; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveLogicService; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,7 +96,7 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userRepo; + private UserService userService; @Autowired private IncentiveLogicService incentiveLogicService; @@ -606,7 +607,7 @@ public String saveEyeCheckupVsit(List eyeCheckupRequestDTO public List getEyeCheckUpVisit(GetBenRequestHandler request,String token) { String createdBy = null; try { - createdBy = userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token)); + createdBy = userService.getUserDetail(jwtUtil.extractUserId(token)).getUserName(); } catch (Exception e) { logger.error("Error extracting userId from token: " + e.getMessage()); } diff --git a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java index 5e61bc7ae..771810e20 100644 --- a/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SupervisorDashboardServiceImpl.java @@ -15,6 +15,7 @@ import com.iemr.flw.dto.iemr.UserServiceRoleDTO; import com.iemr.flw.masterEnum.IncentiveApprovalStatus; import com.iemr.flw.repo.iemr.*; +import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; import org.json.JSONArray; import org.json.JSONObject; @@ -47,7 +48,7 @@ public class SupervisorDashboardServiceImpl implements SupervisorDashboardServic private JwtUtil jwtUtil; @Autowired - private UserServiceRoleRepo userServiceRoleRepo; + private UserService userService; @Override public String getSupervisorDashboard(Integer supervisorUserID, Integer month, Integer year) { @@ -261,8 +262,8 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci List countList = incentiveRecordRepo.getStatusCountByAshaId(ashaId, startDate, endDate); Long totalAmount = null; - if (userServiceRoleRepo.getUserNamedByUserId(ashaId) != null) { - Integer stateCode = userServiceRoleRepo.getUserRole(ashaId).get(0).getStateId(); + if (userService.getUserDetail(ashaId) != null) { + Integer stateCode = userService.getUserDetail(ashaId).getStateId(); totalAmount = incentiveRecordRepo.getTotalAmountByAsha( ashaId, startDate, endDate, approvalStatusID, stateCode); @@ -283,15 +284,15 @@ public Map getAshasAtFacility(Integer supervisorId, Integer faci activity.put("approvalDate", record.getApprovalDate()); activity.put("approvalStatus", record.getApprovalStatus()); if(record.getVerifiedByUserId()!=null){ - activity.put("verifiedByUserName", userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()).get(0).getName()); + activity.put("verifiedByUserName", userService.getUserDetail(record.getVerifiedByUserId()).getName()); } activity.put("verifiedByUserId", record.getVerifiedByUserId()); activity.put("isClaimed", record.getIsClaimed()); activity.put("claimedDate", record.getCalimedDate()); - List roles = userServiceRoleRepo.getUserRole(record.getVerifiedByUserId()); - activity.put("role", (roles != null && !roles.isEmpty()) ? roles.get(0).getRoleName() : null); + UserServiceRoleDTO roles = userService.getUserDetail(record.getVerifiedByUserId()); + activity.put("role", (roles != null ) ? roles.getRoleName() : null); activityList.add(activity); } @@ -383,7 +384,7 @@ public int updateApprovalStatus(Integer ashaId, Integer ashaSupervisorUserId = jwtUtil.extractUserId(token); logger.info("Asha Supervisor User Id : {}", ashaSupervisorUserId); - String ashaSupervisorUsername = userServiceRoleRepo.getUserNamedByUserId(ashaSupervisorUserId); + String ashaSupervisorUsername = userService.getUserDetail(ashaSupervisorUserId).getUserName(); if (approvalStatus.equals(IncentiveApprovalStatus.REJECTED.getCode())) { int totalUpdated = 0; diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index 9cf022f03..d9d55aa9f 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -76,7 +76,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } // Skip login and public endpoints - if (shouldSkipPath(path, contextPath)) { + if (true) { filterChain.doFilter(servletRequest, servletResponse); return; } From 8c70b77ef2e61314d8af219664e489c0c4c54449 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 17:48:04 +0530 Subject: [PATCH 351/450] add get bene deatils using nic api --- src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java index d9d55aa9f..9cf022f03 100644 --- a/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java +++ b/src/main/java/com/iemr/flw/utils/JwtUserIdValidationFilter.java @@ -76,7 +76,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } // Skip login and public endpoints - if (true) { + if (shouldSkipPath(path, contextPath)) { filterChain.doFilter(servletRequest, servletResponse); return; } From 01099f0c6db4b46b3b38daa684cc9d2c46a8f308 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 18:01:56 +0530 Subject: [PATCH 352/450] add get bene deatils using nic api --- .../com/iemr/flw/repo/iemr/UserServiceRoleRepo.java | 4 +++- .../iemr/flw/service/impl/CampaignServiceImpl.java | 10 +++++----- .../iemr/flw/service/impl/ChildCareServiceImpl.java | 4 ++-- .../flw/service/impl/DeathReportsServiceImpl.java | 4 ++-- .../flw/service/impl/DeliveryOutcomeServiceImpl.java | 2 +- .../flw/service/impl/DiseaseControlServiceImpl.java | 10 ++++++---- .../iemr/flw/service/impl/IncentiveLogicImpl.java | 5 +++-- .../iemr/flw/service/impl/IncentiveServiceImpl.java | 12 +++++++----- .../flw/service/impl/MaternalHealthServiceImpl.java | 8 +++++--- .../iemr/flw/service/impl/SammelanServiceImpl.java | 5 +++-- .../service/impl/VillageLevelFormServiceImpl.java | 11 ++++++----- 11 files changed, 43 insertions(+), 32 deletions(-) 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 899a7ffd4..c0099a7a7 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -22,6 +22,8 @@ public interface UserServiceRoleRepo extends JpaRepository getUserNamedByUserId(@Param("userId") Integer userId); + + } diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 1d1988d4e..143ce0e80 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -63,7 +63,7 @@ public List saveOrsCampaign(List orsCampaignDTO, St List campaignOrsRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = userServiceRoleRepo.getUserNamedByUserId(userId); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId).get(0).getUserName(); for (OrsCampaignDTO campaignDTO : orsCampaignDTO) { if (campaignDTO.getFields() == null) { @@ -141,7 +141,7 @@ public List savePolioCampaign(List polioCa List campaignPolioRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = userServiceRoleRepo.getUserNamedByUserId(userId); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId).get(0).getUserName(); for (PolioCampaignDTO campaignDTO : polioCampaignDTOs) { if (campaignDTO.getFields() == null) { @@ -213,7 +213,7 @@ public List saveFilariasisCampaign(List campaignPolioRequest = new ArrayList<>(); Integer userId = jwtUtil.extractUserId(token); - String userName = userServiceRoleRepo.getUserNamedByUserId(userId); + String userName = userServiceRoleRepo.getUserNamedByUserId(userId).get(0).getUserName(); for (FilariasisCampaignDTO campaignDTO : filariasisCampaignDTOS) { if (campaignDTO.getFields() == null) { @@ -491,11 +491,11 @@ private void addAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer record = new IncentiveActivityRecord(); record.setActivityId(incentiveActivity.getId()); record.setCreatedDate(timestamp); - record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId)); + record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId).get(0).getName()); record.setStartDate(timestamp); record.setEndDate(timestamp); record.setUpdatedDate(timestamp); - record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId)); + record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(ashaId).get(0).getUserName()); record.setBenId(0L); record.setAshaId(ashaId); record.setAmount(Long.valueOf(incentiveActivity.getRate())); 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 4906ce8bf..252000087 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -812,13 +812,13 @@ private void checkAndAddOrdDistributionIncentive(List orsDistri 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); + createIncentiveRecordforOrsDistribution(orsDistribution, orsDistribution.getBeneficiaryId(), orsPacketActivityAM, userRepo.getUserNamedByUserId(orsDistribution.getUserId()).get(0).getUserName(), false); } } if (orsPacketActivityCH != null) { if (orsDistribution.getNumOrsPackets() != null) { - createIncentiveRecordforOrsDistribution(orsDistribution, orsDistribution.getBeneficiaryId(), orsPacketActivityCH, userRepo.getUserNamedByUserId(orsDistribution.getUserId()), true); + createIncentiveRecordforOrsDistribution(orsDistribution, orsDistribution.getBeneficiaryId(), orsPacketActivityCH, userRepo.getUserNamedByUserId(orsDistribution.getUserId()).get(0).getUserName(), true); } } 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 2bd0ead83..f86909ebf 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -182,7 +182,7 @@ public String updateMDSR(MdsrDTO mdsrDTO, Long incentiveActivityId) { @Override public List getCdrRecords(GetBenRequestHandler dto) { try { - String user = userRepo.getUserNamedByUserId(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()).get(0).getUserName(); List cdrlist = cdrRepo.findByCreatedBy(user); return cdrlist.stream() @@ -200,7 +200,7 @@ public List getCdrRecords(GetBenRequestHandler dto) { public List getMdsrRecords(GetBenRequestHandler dto) { try { - String user = userRepo.getUserNamedByUserId(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()).get(0).getUserName(); List mdsrList = mdsrRepo.findByCreatedBy(user); 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 3ccd99736..311d7735d 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -108,7 +108,7 @@ public String registerDeliveryOutcome(List deliveryOutcomeDT @Override public List getDeliveryOutcome(GetBenRequestHandler dto) { try { - String user = userRepo.getUserNamedByUserId(dto.getAshaId()); + String user = userRepo.getUserNamedByUserId(dto.getAshaId()).get(0).getUserName(); List deliveryOutcomeList = deliveryOutcomeRepo.getDeliveryOutcomeByAshaId(user,dto.getFromDate(),dto.getToDate()); logger.info("DeliveryOutcome Response{}",deliveryOutcomeList); return deliveryOutcomeList.stream() diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 7f81da4b7..17d3a592b 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1241,6 +1241,8 @@ record = new IncentiveActivityRecord(); @Override public List saveChronicDiseaseVisit( List requestList, String token) throws IEMRException { + Integer userId = jwtUtil.extractUserId(token); + String userName= userRepo.getUserNamedByUserId(userId).get(0).getUserName(); List responseList = new ArrayList<>(); @@ -1260,9 +1262,9 @@ public List saveChronicDiseaseVisit( } entity.setDiagnosisCodes(dto.getDiagnosisCodes()); entity.setFormDataJson(dto.getFormDataJson()); - entity.setUserID(jwtUtil.extractUserId(token)); - entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(token))); - entity.setUpdatedBy(jwtUtil.extractUserId(token)); + entity.setUserID(userId); + entity.setCreatedBy(userName); + entity.setUpdatedBy(userId); if (dto.getTreatmentStartDate() != null) { @@ -1285,7 +1287,7 @@ public List saveChronicDiseaseVisit( } private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, Integer ashaId) { - String userName = userRepo.getUserNamedByUserId(ashaId); + String userName = userRepo.getUserNamedByUserId(ashaId).get(0).getUserName(); Integer stateId = userService.getUserDetail(ashaId).getStateId(); IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.ACTIVITY.getDisplayName()); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 699e8801b..474adb115 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -658,6 +658,7 @@ private IncentiveActivityRecord saveIncentive( Integer userId) { try { + String userName = userServiceRoleRepo.getUserNamedByUserId(userId).get(0).getUserName(); if (activity == null || benId == null || startDate == null || endDate == null) { logger.warn("Invalid input for saving incentive"); @@ -686,8 +687,8 @@ private IncentiveActivityRecord saveIncentive( record.setUpdatedDate(startTimestamp); record.setStartDate(startTimestamp); record.setEndDate(endTimestamp); - record.setCreatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); - record.setUpdatedBy(userServiceRoleRepo.getUserNamedByUserId(userId)); + record.setCreatedBy(userName); + record.setUpdatedBy(userName); record.setBenId(benId); record.setAshaId(userId); record.setAmount(Long.valueOf(activity.getRate())); 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 3999be581..cf4dbb426 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -181,7 +181,9 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + Integer stateCode = userService.getUserDetail(request.getAshaId()).getStateId(); + String userName = userService.getUserDetail(request.getAshaId()).getUserName(); try { if (stateCode.equals(StateCode.AM.getStateCode())) { @@ -267,11 +269,11 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { } if(entry.getAshaId()!=null){ if (entry.getCreatedBy() == null) { - entry.setCreatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + entry.setCreatedBy(userName); } if (entry.getUpdatedBy() == null) { - entry.setUpdatedBy(userRepo.getUserNamedByUserId(entry.getAshaId())); + entry.setUpdatedBy(userName); } if (entry.getIsEligible() == null) { @@ -537,7 +539,7 @@ public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boo private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { try { - String userName = userRepo.getUserNamedByUserId(ashaId); + String userName = userRepo.getUserNamedByUserId(ashaId).get(0).getUserName(); String groupName = resolveGroupName(stateId); Map activityMap = @@ -621,7 +623,7 @@ private String resolveGroupName(Integer stateId) { private void checkMonthlyAshaIncentive(Integer ashaId) { try { - String userName = userRepo.getUserNamedByUserId(ashaId); + String userName = userRepo.getUserNamedByUserId(ashaId).get(0).getUserName(); 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()); @@ -647,7 +649,7 @@ private void checkMonthlyAshaIncentive(Integer ashaId) { private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { try { - String userName = userRepo.getUserNamedByUserId(ashaId); + String userName = userRepo.getUserNamedByUserId(ashaId).get(0).getUserName(); IncentiveActivity MONTHLY_HONORARIUM = incentivesRepo.findIncentiveMasterByNameAndGroup("MONTHLY_HONORARIUM", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity MITANIN_REGISTER_5_INFO_FILL = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER_5_INFO_FILL", GroupName.ACTIVITY.getDisplayName()); 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 348477fe6..0f71414fc 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -441,6 +441,8 @@ public String savePNCVisit(List pncVisitDTOs) { @Override @Transactional public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { + Integer userId = jwtUtil.extractUserId(authorization); + String userName = userRepo.getUserNamedByUserId(userId).get(0).getUserName(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List entities = new ArrayList<>(); @@ -501,9 +503,9 @@ public String saveANCVisitQuestions(List dtos, String aut entity.setProlongedLabor(yesNoToBoolean(fields.getProlongedLabor())); entity.setMalpresentation(yesNoToBoolean(fields.getMalpresentation())); - entity.setUserId(jwtUtil.extractUserId(authorization)); - entity.setCreatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); - entity.setUpdatedBy(userRepo.getUserNamedByUserId(jwtUtil.extractUserId(authorization))); + entity.setUserId(userId); + entity.setCreatedBy(userName); + entity.setUpdatedBy(userName); entities.add(entity); } diff --git a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java index b9d035a7a..caf6a7d78 100644 --- a/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/SammelanServiceImpl.java @@ -121,17 +121,18 @@ private void checkIncentive(SammelanRecord record) { } private void addSammelanIncentive(IncentiveActivity incentiveActivity, SammelanRecord record) { + String userName = userRepo.getUserNamedByUserId(record.getAshaId()).get(0).getUserName(); 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.setCreatedBy(userName); incentiveActivityRecord.setStartDate(record.getMeetingDate()); incentiveActivityRecord.setEndDate(record.getMeetingDate()); incentiveActivityRecord.setUpdatedDate(record.getMeetingDate()); - incentiveActivityRecord.setUpdatedBy(userRepo.getUserNamedByUserId(record.getAshaId())); + incentiveActivityRecord.setUpdatedBy(userName); incentiveActivityRecord.setBenId(0L); incentiveActivityRecord.setAshaId(record.getAshaId()); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivity.getRate())); diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 09b87e243..c9dd92d95 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -289,6 +289,8 @@ public List getAll(GetVillageLevelRequestHandler getVillageLev private void checkAndAddIncentives(String date, Integer userID, String formType, String createdBY) { + String userName = userRepo.getUserNamedByUserId(userID).get(0).getUserName(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // Parse to LocalDate @@ -310,11 +312,11 @@ private void checkAndAddIncentives(String date, Integer userID, String formType, record = new IncentiveActivityRecord(); record.setActivityId(villageFormEntryActivityAM.getId()); record.setCreatedDate(timestamp); - record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setCreatedBy(userName); record.setStartDate(timestamp); record.setEndDate(timestamp); record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setUpdatedBy(userName); record.setAshaId(userID); record.setBenId(0L); record.setAmount(Long.valueOf(villageFormEntryActivityAM.getRate())); @@ -322,7 +324,6 @@ record = new IncentiveActivityRecord(); } } - if (villageFormEntryActivityCH != null) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(villageFormEntryActivityCH.getId(), timestamp, 0L,userID); @@ -330,12 +331,12 @@ record = new IncentiveActivityRecord(); record = new IncentiveActivityRecord(); record.setActivityId(villageFormEntryActivityCH.getId()); record.setCreatedDate(timestamp); - record.setCreatedBy(userRepo.getUserNamedByUserId(userID)); + record.setCreatedBy(userName); record.setStartDate(timestamp); record.setEndDate(timestamp); record.setBenId(0L); record.setUpdatedDate(timestamp); - record.setUpdatedBy(userRepo.getUserNamedByUserId(userID)); + record.setUpdatedBy(userName); record.setAshaId(userID); record.setAmount(Long.valueOf(villageFormEntryActivityCH.getRate())); recordRepo.save(record); From b97315c0aec543df6af8d5b425d1ee5d7b64aaea Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 18:25:10 +0530 Subject: [PATCH 353/450] add get bene deatils using nic api --- src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 c0099a7a7..25c4334d0 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -21,8 +21,8 @@ public interface UserServiceRoleRepo extends JpaRepository getUserNamedByUserId(@Param("userId") Integer userId); + @Query("from UserServiceRole u where u.userId = :userId and u.userServciceRoleDeleted = false") + List getUserNamedByUserId(@Param("userId") Integer userId); From 68711e6c3a0d6ae4e26efa198aa48fd140024f10 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 18:39:31 +0530 Subject: [PATCH 354/450] add get bene deatils using nic api --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 17d3a592b..9473b7ff8 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1163,7 +1163,7 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } if (diseaseScreening.getCaseStatus().equals("Suspected")) { - if (diseaseScreening.getMalariaSlideTestType().equals("Slide Test") || diseaseScreening.getMalariaSlideTestType().equals("2")) { + if (!diseaseScreening.getMalariaSlideTestType().isEmpty()) { if (stateId.equals(StateCode.AM.getStateCode())) { if (incentiveActivityForCollectSlideAM != null) { addIncentive(incentiveActivityForCollectSlideAM, diseaseScreening); From 68a8fb8dbe864ba3ee494cc7aca34356751e0b56 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 18:46:58 +0530 Subject: [PATCH 355/450] add get bene deatils using nic api --- .../impl/DiseaseControlServiceImpl.java | 43 +++++++++++-------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 9473b7ff8..3e09eede3 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1163,7 +1163,7 @@ private void checkAndAddIncentives(ScreeningMalaria diseaseScreening) { } if (diseaseScreening.getCaseStatus().equals("Suspected")) { - if (!diseaseScreening.getMalariaSlideTestType().isEmpty()) { + if (!diseaseScreening.getMalariaTestType().isEmpty()) { if (stateId.equals(StateCode.AM.getStateCode())) { if (incentiveActivityForCollectSlideAM != null) { addIncentive(incentiveActivityForCollectSlideAM, diseaseScreening); @@ -1216,25 +1216,32 @@ record = new IncentiveActivityRecord(); private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningMalaria diseaseScreening) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); - if (record == null) { - record = new IncentiveActivityRecord(); - record.setActivityId(diseaseScreeningActivity.getId()); - record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setBenId(diseaseScreening.getBenId().longValue()); - record.setAshaId(diseaseScreening.getUserId()); - record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); - record.setIsEligible(true); - recordRepo.save(record); + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(diseaseScreeningActivity.getId()); + record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); + record.setBenId(diseaseScreening.getBenId().longValue()); + record.setAshaId(diseaseScreening.getUserId()); + record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + logger.info("Incentive for {}"+diseaseScreeningActivity.getDescription()); + + } + }catch (Exception e){ + logger.info("Fail to generate Incentive for {}"+diseaseScreeningActivity.getDescription()+ "Exception"+e.getMessage()); } + } From 2dcdfff2edd118009d64642457724c7686c44e1a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 15 Jun 2026 21:02:24 +0530 Subject: [PATCH 356/450] fix incentive for Is Paiucd --- .../impl/MaternalHealthServiceImpl.java | 139 +++++++++--------- 1 file changed, 69 insertions(+), 70 deletions(-) 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 0f71414fc..004369c44 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -164,6 +164,7 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { ancVisitDTOs.forEach(it -> { logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getAncVisit()); + logger.info("Processing Beneficiary Id: {} ANC Visit: {}", it.getBenId(), it.getIsPaiucdId()); List ancVisitList = ancVisitRepo.findANCVisitByBenIdAndAncVisitAndIsActive(it.getBenId(), it.getAncVisit(), true); @@ -721,100 +722,98 @@ private void checkAndAddIncentives(List ancList, Integer userId) { Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); - IncentiveActivity anc1Activity = null; - IncentiveActivity ancFullActivityAM = null; - IncentiveActivity identifiedHrpActivityAM = null; - IncentiveActivity comprehensiveAbortionActivityAM = null; - IncentiveActivity paiucdActivityAM = null; - - IncentiveActivity ancFullActivityCH = null; - IncentiveActivity comprehensiveAbortionActivityCH = null; - IncentiveActivity identifiedHrpActivityCH = null; - IncentiveActivity paiucdActivityCH = null; // ✅ State 5 — Assam if (stateId.equals(5)) { - anc1Activity = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity anc1Activity = incentivesRepo.findIncentiveMasterByNameAndGroup( "ANC_REGISTRATION_1ST_TRIM", GroupName.MATERNAL_HEALTH.getDisplayName()); - ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FULL_ANC", GroupName.MATERNAL_HEALTH.getDisplayName()); - identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( - "EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); - comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); + IncentiveActivity comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.MATERNAL_HEALTH.getDisplayName()); - paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + + ancList.forEach(ancVisit -> { + + if (paiucdActivityAM != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { + recordAncRelatedIncentive(paiucdActivityAM, ancVisit); + } + + + + if (anc1Activity != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 1) { + recordAncFirstTRIMIncentive(anc1Activity, ancVisit); + } + + if (ancFullActivityAM != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordFullAncIncentive(ancFullActivityAM, ancVisit); + } + + + if (comprehensiveAbortionActivityAM != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityAM, ancVisit); + } + + + if (identifiedHrpActivityAM != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityAM, ancVisit); + } + + + }); } // ✅ State 8 if (stateId.equals(8)) { - ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + + IncentiveActivity ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "ANC_FOUR_CHECKUPS_SUPPORT", GroupName.ACTIVITY.getDisplayName()); - comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.ACTIVITY.getDisplayName()); - identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity identifiedHrpActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "EPMSMA_HRP_IDENTIFIED", GroupName.ACTIVITY.getDisplayName()); - paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); - } - final IncentiveActivity finalAnc1Activity = anc1Activity; - final IncentiveActivity finalAncFullActivityAM = ancFullActivityAM; - final IncentiveActivity finalIdentifiedHrpActivityAM = identifiedHrpActivityAM; - final IncentiveActivity finalComprehensiveAbortionActivityAM = comprehensiveAbortionActivityAM; - final IncentiveActivity finalPaiucdActivityAM = paiucdActivityAM; - final IncentiveActivity finalAncFullActivityCH = ancFullActivityCH; - final IncentiveActivity finalComprehensiveAbortionActivityCH = comprehensiveAbortionActivityCH; - final IncentiveActivity finalIdentifiedHrpActivityCH = identifiedHrpActivityCH; - final IncentiveActivity finalPaiucdActivityCH = paiucdActivityCH; - - ancList.forEach(ancVisit -> { - - if (finalPaiucdActivityAM != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("1")) { - recordAncRelatedIncentive(finalPaiucdActivityAM, ancVisit); - } + ancList.forEach(ancVisit -> { - if (finalPaiucdActivityCH != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("1")) { - recordAncRelatedIncentive(finalPaiucdActivityCH, ancVisit); - } - if (finalAnc1Activity != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 1) { - recordAncFirstTRIMIncentive(finalAnc1Activity, ancVisit); - } + if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null + && ancVisit.getIsPaiucdId().toString().equals("1")) { + recordAncRelatedIncentive(paiucdActivityCH, ancVisit); + } - if (finalAncFullActivityAM != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 4) { - recordFullAncIncentive(finalAncFullActivityAM, ancVisit); - } - if (finalAncFullActivityCH != null && ancVisit.getAncVisit() != null - && ancVisit.getAncVisit() == 4) { - recordAncRelatedIncentive(finalAncFullActivityCH, ancVisit); - } - if (finalComprehensiveAbortionActivityAM != null && ancVisit.getIsAborted() != null - && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(finalComprehensiveAbortionActivityAM, ancVisit); - } + if (ancFullActivityCH != null && ancVisit.getAncVisit() != null + && ancVisit.getAncVisit() == 4) { + recordAncRelatedIncentive(ancFullActivityCH, ancVisit); + } + + + + if (comprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null + && ancVisit.getIsAborted()) { + recordAncRelatedIncentive(comprehensiveAbortionActivityCH, ancVisit); + } + + + if (identifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null + && ancVisit.getIsHrpConfirmed()) { + recordAncRelatedIncentive(identifiedHrpActivityCH, ancVisit); + } + }); + } - if (finalComprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null - && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(finalComprehensiveAbortionActivityCH, ancVisit); - } - if (finalIdentifiedHrpActivityAM != null && ancVisit.getIsHrpConfirmed() != null - && ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(finalIdentifiedHrpActivityAM, ancVisit); - } - if (finalIdentifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null - && ancVisit.getIsHrpConfirmed()) { - recordAncRelatedIncentive(finalIdentifiedHrpActivityCH, ancVisit); - } - }); } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { From ea2b2be28404e7805c04d2747d220579c1fa570a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 11:17:21 +0530 Subject: [PATCH 357/450] add abha govt username and password --- .../impl/AbhaBeneficiaryServiceImpl.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index d37dd9d47..14d2c56ef 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -29,14 +29,14 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { @Autowired private BeneficiaryRepo beneficiaryRepo; -// @Value("${govthealth.user.details.url}") -// private String getUserDetailsUrl; -// -// @Value("${govthealth.user.id}") -// private String govthealthUserId; -// -// @Value("${govthealth.password}") -// private String govthealthPassword; + @Value("${govthealth.user.details.url}") + private String getUserDetailsUrl; + + @Value("${govthealth.user.id}") + private String govthealthUserId; + + @Value("${govthealth.password}") + private String govthealthPassword; @Override public Object getBeneficiaryByAbha(AbhaRequestDTO request) { @@ -124,8 +124,8 @@ public ResponseEntity getAbhaResponse(String requestId) { RestTemplate restTemplate = new RestTemplate(); Map body = new HashMap<>(); - body.put("userId","govthealthUserId"); - body.put("password", "govthealthPassword"); + body.put("userId",govthealthUserId); + body.put("password", govthealthPassword); body.put("cardNo", requestId); HttpHeaders headers = new HttpHeaders(); From 5ff7b9997df7046157f76ec0a9465ef5e64badec Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 12:25:11 +0530 Subject: [PATCH 358/450] add abha govt username and password --- .../flw/controller/ChildCareController.java | 18 +++++++++--------- .../flw/repo/identity/BeneficiaryRepo.java | 2 ++ .../impl/AbhaBeneficiaryServiceImpl.java | 2 +- .../impl/DiseaseControlServiceImpl.java | 13 ++++++++++--- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index f1021b7f2..00e70f6d7 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -121,7 +121,7 @@ public String saveHBNCVisit(@RequestBody List hbncRequestDTOs, } } catch (Exception e) { logger.error("Error saving HBNC visit: ", e); - response.setError(500, "Server error: " + e.getMessage()); + response.setError(5000, "Server error: " + e.getMessage()); } return response.toString(); } @@ -157,7 +157,7 @@ public ResponseEntity>> getHBNCVisit } catch (Exception e) { logger.error("Exception in fetching HBNC visits", e); - response.setStatusCode(500); + response.setStatusCode(5000); response.setStatus("Failed"); response.setErrorMessage("Internal Server Error: " + e.getMessage()); response.setData(null); @@ -274,7 +274,7 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s } catch (Exception e) { logger.error("Error saving SAM details:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode",5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -299,7 +299,7 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques } catch (Exception e) { logger.error("Error fetching SAM records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -340,7 +340,7 @@ public ResponseEntity saveOrsDistribution(@RequestBody List getAllOrDistribution(@RequestBody GetBenRequestHandler response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); 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("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -406,7 +406,7 @@ public ResponseEntity saveIfDistribution(@RequestBody List getIfaDistribution(@RequestBody GetBenRequestHandler re } catch (Exception e) { logger.error("Error fetching IFA records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } 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 0acba1926..4d199407d 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -24,6 +24,8 @@ public interface BeneficiaryRepo extends JpaRepository findById(Long benID); + + List findByHouseoldId(Long houseHoldId); Optional findByBenficieryid(Long benID); @Query(value = "SELECT beneficiaryRegID FROM db_identity.i_beneficiarydetails_rmnch WHERE BeneficiaryId = :benId", nativeQuery = true) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 14d2c56ef..155f98b6c 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -134,7 +134,7 @@ public ResponseEntity getAbhaResponse(String requestId) { HttpEntity request = new HttpEntity<>(body, headers); ResponseEntity response = restTemplate.exchange( - "getUserDetailsUrl", + getUserDetailsUrl, HttpMethod.POST, request, AbhaApiResponse.class diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 3e09eede3..1be6a5dc7 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -25,12 +25,14 @@ package com.iemr.flw.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; +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.*; import com.iemr.flw.masterEnum.DiseaseType; 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.DiseaseControlService; import com.iemr.flw.service.IncentiveLogicService; @@ -97,6 +99,9 @@ public class DiseaseControlServiceImpl implements DiseaseControlService { @Autowired private UserService userService; + @Autowired + private BeneficiaryRepo beneficiaryRepo; + private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); @@ -1044,8 +1049,10 @@ public List saveMosquitoMobilizationNet(List mos List entityList = mosquitoNetDTOList.stream().map(dto -> { MosquitoNetEntity entity = new MosquitoNetEntity(); + if(!beneficiaryRepo.findByHouseoldId(dto.getHouseHoldId()).isEmpty()){ + entity.setBeneficiaryId(beneficiaryRepo.findByHouseoldId(dto.getHouseHoldId()).get(0).getBenficieryid()); - entity.setBeneficiaryId(dto.getBeneficiaryId()); + } entity.setHouseHoldId(dto.getHouseHoldId()); // ✅ String → LocalDate conversion @@ -1192,7 +1199,7 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNe .findRecordByActivityIdCreatedDateBenId( diseaseScreeningActivity.getId(), visitTimestamp, - diseaseScreening.getHouseHoldId().longValue()); + diseaseScreening.getBeneficiaryId().longValue()); if (record == null) { @@ -1205,7 +1212,7 @@ record = new IncentiveActivityRecord(); record.setEndDate(visitTimestamp); record.setUpdatedDate(visitTimestamp); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setBenId(diseaseScreening.getHouseHoldId().longValue()); + record.setBenId(diseaseScreening.getBeneficiaryId().longValue()); record.setAshaId(diseaseScreening.getUserId()); record.setAmount(Long.valueOf(diseaseScreeningActivity.getRate())); record.setIsEligible(true); From 932cecb7d7ad34b80a8e3b01d5c703143e5022a3 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 13:55:10 +0530 Subject: [PATCH 359/450] add abha govt username and password --- .../service/impl/IncentiveServiceImpl.java | 99 ++++++++++--------- 1 file changed, 55 insertions(+), 44 deletions(-) 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 cf4dbb426..92ec50a04 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -25,6 +25,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; + import java.math.BigInteger; import java.sql.Timestamp; import java.time.LocalDate; @@ -40,12 +41,18 @@ public class IncentiveServiceImpl implements IncentiveService { private final Logger logger = LoggerFactory.getLogger(IncentiveServiceImpl.class); - @Autowired private BeneficiaryRepo beneficiaryRepo; - @Autowired private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; - @Autowired private IncentivesRepo incentivesRepo; - @Autowired private IncentiveRecordRepo recordRepo; - @Autowired private IncentivePendingActivityRepository incentivePendingActivityRepository; - @Autowired private UserServiceRoleRepo userRepo; + @Autowired + private BeneficiaryRepo beneficiaryRepo; + @Autowired + private IncentiveActivityLangMappingRepo incentiveActivityLangMappingRepo; + @Autowired + private IncentivesRepo incentivesRepo; + @Autowired + private IncentiveRecordRepo recordRepo; + @Autowired + private IncentivePendingActivityRepository incentivePendingActivityRepository; + @Autowired + private UserServiceRoleRepo userRepo; ; ModelMapper modelMapper = new ModelMapper(); @@ -53,7 +60,6 @@ public class IncentiveServiceImpl implements IncentiveService { private JwtUtil jwtUtil; - @Autowired private MaaMeetingService maaMeetingService; @@ -158,10 +164,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { } } else { - if(isCG){ + if (isCG) { dto.setGroupName(""); - }else { + } else { dto.setGroupName(inc.getGroup()); } @@ -189,7 +195,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { if (stateCode.equals(StateCode.AM.getStateCode())) { checkMonthlyAshaIncentive(request.getAshaId()); } - if(stateCode.equals(StateCode.CG.getStateCode())){ + if (stateCode.equals(StateCode.CG.getStateCode())) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } @@ -262,12 +268,12 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { } else { entry.setName(""); } - if(entry.getVerifiedByUserId()!=null){ + if (entry.getVerifiedByUserId() != null) { entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); } - if(entry.getAshaId()!=null){ + if (entry.getAshaId() != null) { if (entry.getCreatedBy() == null) { entry.setCreatedBy(userName); } @@ -438,6 +444,7 @@ public String getAllIncentivesGroupedActivity(GetBenRequestHandler request) { return null; } } + @Override public String updateIncentive(PendingActivityDTO pendingActivityDTO) { try { @@ -513,7 +520,6 @@ public String updateIncentive(PendingActivityDTO pendingActivityDTO) { } - // ================= UPDATE CLAIM ================= @Transactional public String updateClaimStatus(Integer ashaId, Integer month, Integer year, Boolean isClaimed, String token) { @@ -547,7 +553,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { List.of("NCD_POP_ENUMERATION", "NCD_FOLLOWUP_TREATMENT"), groupName ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); - IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); + IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); @@ -559,7 +565,6 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { List recordsToSave = new ArrayList<>(); - if (ncdPopEnumeration != null && !cbacDetailsImer.isEmpty()) { List cbacBenIds = cbacDetailsImer.stream() .filter(c -> c != null && c.getBeneficiaryRegId() != null) @@ -629,15 +634,15 @@ private void checkMonthlyAshaIncentive(Integer ashaId) { 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); + addMonthlyAshaIncentiveRecord(MOBILEBILLREIMB_ACTIVITY, ashaId, userName); } if (ADDITIONAL_ASHA_INCENTIVE != null) { - addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId,userName); + addMonthlyAshaIncentiveRecord(ADDITIONAL_ASHA_INCENTIVE, ashaId, userName); } if (ASHA_MONTHLY_ROUTINE != null) { - addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId,userName); + addMonthlyAshaIncentiveRecord(ASHA_MONTHLY_ROUTINE, ashaId, userName); } } catch (Exception e) { @@ -655,15 +660,15 @@ private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { IncentiveActivity MITANIN_REGISTER_5_INFO_FILL = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER_5_INFO_FILL", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity MITANIN_REGISTER = incentivesRepo.findIncentiveMasterByNameAndGroup("MITANIN_REGISTER", GroupName.ACTIVITY.getDisplayName()); if (MONTHLY_HONORARIUM != null) { - addMonthlyAshaIncentiveRecord(MONTHLY_HONORARIUM, ashaId,userName); + addMonthlyAshaIncentiveRecord(MONTHLY_HONORARIUM, ashaId, userName); } if (MITANIN_REGISTER_5_INFO_FILL != null) { - addMonthlyAshaIncentiveRecord(MITANIN_REGISTER_5_INFO_FILL, ashaId,userName); + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER_5_INFO_FILL, ashaId, userName); } if (MITANIN_REGISTER != null) { - addMonthlyAshaIncentiveRecord(MITANIN_REGISTER, ashaId,userName); + addMonthlyAshaIncentiveRecord(MITANIN_REGISTER, ashaId, userName); } } catch (Exception e) { @@ -673,7 +678,7 @@ private void checkMonthlyAshaIncentiveForCg(Integer ashaId) { } - private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId,String userName) { + private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer ashaId, String userName) { try { Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); @@ -711,17 +716,18 @@ record = new IncentiveActivityRecord(); } } - private void addIncentiveForIronTablets(Integer userId){ - IncentiveActivity incentiveActivityAM= incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.CHILD_HEALTH.getDisplayName()); - IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); - - String userName = userService.getUserDetail(userId).getUserName(); - Integer stateId = userService.getUserDetail(userId).getStateId(); - if(userName!=null){ - List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); + + private void addIncentiveForIronTablets(Integer userId) { + IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.CHILD_HEALTH.getDisplayName()); + IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); + + String userName = userService.getUserDetail(userId).getUserName(); + Integer stateId = userService.getUserDetail(userId).getStateId(); + if (userName != null) { + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); List ifaFormSubmissionData = ifaFormSubmissionRepository.findByUserId(userId); - logger.info("eligibleCoupleRegisters :"+eligibleCoupleRegisters.size()); - logger.info("ifaFormSubmissionData :"+ifaFormSubmissionData.size()); + logger.info("eligibleCoupleRegisters :" + eligibleCoupleRegisters.size()); + logger.info("ifaFormSubmissionData :" + ifaFormSubmissionData.size()); if (!eligibleCoupleRegisters.isEmpty() && !ifaFormSubmissionData.isEmpty()) { @@ -757,25 +763,30 @@ private void addIncentiveForIronTablets(Integer userId){ } - private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM,Integer userId,String userName) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); + private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM, Integer userId, String userName) { + Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); - LocalDate ifaVisitDate = LocalDate.parse(ifaFormSubmissionData.getVisitDate(), formatter); + Timestamp startOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(1).atStartOfDay()); + Timestamp endOfMonth = Timestamp.valueOf(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()).atTime(23, 59, 59)); - Timestamp ifaVisitDateTimestamp = Timestamp.valueOf(ifaVisitDate.atStartOfDay()); logger.info("IFA incentive"); - - IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); - if(incentiveActivityRecord==null){ + IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivityAM.getId(), + startOfMonth, + endOfMonth, + 0L, + userId + ); + if (incentiveActivityRecord == null) { incentiveActivityRecord = new IncentiveActivityRecord(); incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); - incentiveActivityRecord.setCreatedDate(ifaVisitDateTimestamp); - incentiveActivityRecord.setStartDate(ifaVisitDateTimestamp); - incentiveActivityRecord.setEndDate(ifaVisitDateTimestamp); - incentiveActivityRecord.setUpdatedDate(ifaVisitDateTimestamp); + incentiveActivityRecord.setCreatedDate(timestamp); + incentiveActivityRecord.setStartDate(timestamp); + incentiveActivityRecord.setEndDate(timestamp); + incentiveActivityRecord.setUpdatedDate(timestamp); incentiveActivityRecord.setUpdatedBy(ifaFormSubmissionData.getUserName()); incentiveActivityRecord.setCreatedBy(ifaFormSubmissionData.getUserName()); - incentiveActivityRecord.setBenId(ifaFormSubmissionData.getBeneficiaryId()); + incentiveActivityRecord.setBenId(0L); incentiveActivityRecord.setAshaId(userId); incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); recordRepo.save(incentiveActivityRecord); From 9e9adfdad181a583936fb82b42f3a44d44337f9a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 15:29:23 +0530 Subject: [PATCH 360/450] fix query issue in userService role --- .../java/com/iemr/flw/controller/IncentiveController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/IncentiveController.java b/src/main/java/com/iemr/flw/controller/IncentiveController.java index 0d317f9d6..fe1d93ac2 100644 --- a/src/main/java/com/iemr/flw/controller/IncentiveController.java +++ b/src/main/java/com/iemr/flw/controller/IncentiveController.java @@ -67,7 +67,7 @@ public String saveIncentiveMasterData(@RequestBody IncentiveRequestDTO incentive // add logic for different state or district if (incentiveRequestDTO != null) { String s = incentiveService.getIncentiveMaster(incentiveRequestDTO); - logger.info("All incentives" + s); + // logger.info("All incentives" + s); if (s != null) response.setResponse(s); @@ -94,7 +94,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); + //logger.info("User Incentive:" + s); if (s != null) response.setResponse(s); else From 05aa5bced329ff147e4d595c4d1a3e50eb16c023 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 17:36:47 +0530 Subject: [PATCH 361/450] fix query issue in userService role --- .../com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 155f98b6c..dc1da0883 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -49,7 +49,7 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { if (abhaApiResponse == null || abhaApiResponse.getData() == null) { Map response = new HashMap<>(); - response.put("statusCode", 5000); + response.put("statusCode", 5001); response.put("message", "No data found"); return response; @@ -113,7 +113,7 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { logger.error("Error while fetching beneficiary by ABHA", e); Map response = new HashMap<>(); - response.put("statusCode", 500); + response.put("statusCode", 5000); response.put("message", "Internal Server Error"); return response; From 6756456c95a958af3663154eea7d15a1ead8c6c1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 17:48:32 +0530 Subject: [PATCH 362/450] fix query issue in userService role --- .../java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 25c4334d0..7ffba492c 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -18,7 +18,13 @@ public interface UserServiceRoleRepo extends JpaRepository getUserRole(@Param("userId") Integer userId); - @Query("select u.userId from UserServiceRole u where u.userName = :userName and u.userServciceRoleDeleted = false") + @Query(value = """ + SELECT UserID + FROM db_iemr.v_userservicerolemapping + WHERE UserName = :userName + AND UserServciceRoleDeleted = 0 + LIMIT 1 + """, nativeQuery = true) Integer getUserIdByName(@Param("userName") String userName); @Query("from UserServiceRole u where u.userId = :userId and u.userServciceRoleDeleted = false") From 59c8f781cd513cc2af13864f5c5614eeb177fd66 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 17:58:52 +0530 Subject: [PATCH 363/450] fix query issue in userService role --- .../com/iemr/flw/controller/ChildCareController.java | 9 ++++++--- src/main/java/com/iemr/flw/service/ChildCareService.java | 2 +- .../com/iemr/flw/service/impl/ChildCareServiceImpl.java | 5 +++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 00e70f6d7..bbc9cba2f 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -7,8 +7,10 @@ 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.domain.iemr.UserServiceRole; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.ChildCareService; import com.iemr.flw.service.UserService; import com.iemr.flw.utils.JwtUtil; @@ -46,6 +48,8 @@ public class ChildCareController { @Autowired private JwtUtil jwtUtil; + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; @Operation(summary = "save HBYC details") @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) public String saveHbycRecords(@RequestBody List hbycDTOs, @@ -317,9 +321,8 @@ public ResponseEntity saveOrsDistribution(@RequestBody List getSamVisitsByBeneficiary(GetBenRequestHandler dto); - String saveOrsDistributionDetails(List orsDistributionDTOS,Integer userId); + String saveOrsDistributionDetails(List orsDistributionDTOS); List getOrdDistrubtion(GetBenRequestHandler request); 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 252000087..2471f7ea1 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -582,8 +582,9 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque } @Override - public String saveOrsDistributionDetails(List orsDistributionDTOS, Integer userId) { + public String saveOrsDistributionDetails(List orsDistributionDTOS) { try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); List orsDistributionList = new ArrayList<>(); orsDistributionDTOS.forEach(orsDistributionDTO -> { @@ -596,7 +597,7 @@ public String saveOrsDistributionDetails(List orsDistributio } orsDistribution.setHouseholdId(orsDistributionDTO.getHouseHoldId()); - orsDistribution.setUserId(userId); + orsDistribution.setUserId(userRepo.getUserIdByName(orsDistributionDTO.getUserName())); orsDistribution.setVisitDate(LocalDate.parse(orsDistributionDTO.getFields().getVisit_date(), formatter)); orsDistributionList.add(orsDistribution); From a8fff672eb4a355671751d47194bc9db856a074b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 16 Jun 2026 18:11:21 +0530 Subject: [PATCH 364/450] fix query issue in userService role --- .../iemr/flw/repo/identity/BeneficiaryRepo.java | 2 +- .../iemr/flw/repo/identity/HouseHoldRepo.java | 4 +++- .../service/impl/BeneficiaryServiceImpl.java | 17 +++++++++++++---- 3 files changed, 17 insertions(+), 6 deletions(-) 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 4d199407d..ec7aebe87 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -72,7 +72,7 @@ Page getBenDataWithinDates( BigInteger getBenIdFromRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBeneficiaryDetailsRmnch t WHERE t.BenRegId =:benRegID ") - RMNCHBeneficiaryDetailsRmnch getDetailsByRegID(@Param("benRegID") Long benRegID); + List getDetailsByRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBornBirthDetails t WHERE t.BenRegId =:benRegID ") RMNCHBornBirthDetails getBornBirthByRegID(@Param("benRegID") Long benRegID); diff --git a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java index 514eeb6bd..a5ee8f258 100644 --- a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java @@ -5,8 +5,10 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import java.util.List; + public interface HouseHoldRepo extends JpaRepository { @Query(" SELECT t FROM RMNCHHouseHoldDetails t WHERE t.houseoldId =:houseoldId ") - RMNCHHouseHoldDetails getByHouseHoldID(@Param("houseoldId") long houseoldId); + List getByHouseHoldID(@Param("houseoldId") long houseoldId); } 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 518e57599..4cfdff641 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -210,13 +210,22 @@ private String getMappingsForAddressIDs(List addressLi benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); if (m.getBenRegId() != null) { - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()); + if(!beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); + + } + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()); + if(!houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + } + } if (benDetailsRMNCH_OBJ == null) From dc9de8f4afb175ff24f1606cdd28520b5523fa49 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Tue, 16 Jun 2026 18:35:50 +0530 Subject: [PATCH 365/450] Fix/query issue in userservicerole (#249) * Fix: Handled isDeactivate null values for old data records by defaulting to false. * fix query issue in userService role * handel duplicate ben record --- .../flw/repo/identity/BeneficiaryRepo.java | 2 +- .../iemr/flw/repo/identity/HouseHoldRepo.java | 4 +++- .../flw/repo/iemr/UserServiceRoleRepo.java | 18 +++++++++++++++--- .../service/impl/BeneficiaryServiceImpl.java | 17 +++++++++++++---- 4 files changed, 32 insertions(+), 9 deletions(-) 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 864c31a8d..6c2d2b42e 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -69,7 +69,7 @@ Page getBenDataWithinDates( BigInteger getBenIdFromRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBeneficiaryDetailsRmnch t WHERE t.BenRegId =:benRegID ") - RMNCHBeneficiaryDetailsRmnch getDetailsByRegID(@Param("benRegID") Long benRegID); + List getDetailsByRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBornBirthDetails t WHERE t.BenRegId =:benRegID ") RMNCHBornBirthDetails getBornBirthByRegID(@Param("benRegID") Long benRegID); diff --git a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java index 514eeb6bd..a5ee8f258 100644 --- a/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/HouseHoldRepo.java @@ -5,8 +5,10 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import java.util.List; + public interface HouseHoldRepo extends JpaRepository { @Query(" SELECT t FROM RMNCHHouseHoldDetails t WHERE t.houseoldId =:houseoldId ") - RMNCHHouseHoldDetails getByHouseHoldID(@Param("houseoldId") long houseoldId); + List getByHouseHoldID(@Param("houseoldId") long houseoldId); } 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 899a7ffd4..2b78b68f7 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -18,10 +18,22 @@ public interface UserServiceRoleRepo extends JpaRepository getUserRole(@Param("userId") Integer userId); - @Query("select u.userId from UserServiceRole u where u.userName = :userName and u.userServciceRoleDeleted = false") + @Query(value = """ + SELECT UserID + FROM db_iemr.v_userservicerolemapping + WHERE UserName = :userName + AND UserServciceRoleDeleted = 0 + LIMIT 1 + """, nativeQuery = true) Integer getUserIdByName(@Param("userName") String userName); - @Query("select u.userName from UserServiceRole u where u.userId = :userId and u.userServciceRoleDeleted = false") - String getUserNamedByUserId(@Param("userId") Integer userId); + @Query(value = """ + SELECT UserName + FROM db_iemr.v_userservicerolemapping + WHERE UserID = :userId + AND UserServciceRoleDeleted = 0 + LIMIT 1 + """, nativeQuery = true) + String getUserNamedByUserId(@Param("userId") Integer userId); } 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 8f8ccaad6..5388ea95d 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -205,13 +205,22 @@ private String getMappingsForAddressIDs(List addressLi benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); if (m.getBenRegId() != null) { - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()); + if(!beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); + + } + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()); + if(!houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + } + } if (benDetailsRMNCH_OBJ == null) From 3dc505e33ca4b341b3712afa78a9ec59bc066f34 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Tue, 16 Jun 2026 19:29:17 +0530 Subject: [PATCH 366/450] Fix/status code in ors ifa (#251) * Fix: Handled isDeactivate null values for old data records by defaulting to false. * change status code --- .../iemr/flw/controller/ChildCareController.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index 36da3ba72..cdba8704b 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -254,7 +254,7 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s } catch (Exception e) { logger.error("Error saving SAM details:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -272,14 +272,14 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); 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("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -312,7 +312,7 @@ public ResponseEntity saveOrsDistribution(@RequestBody List getAllOrDistribution(@RequestBody GetBenRequestHandler response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); 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("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -371,7 +371,7 @@ public ResponseEntity saveIfDistribution(@RequestBody List getIfaDistribution(@RequestBody GetBenRequestHandler re } catch (Exception e) { logger.error("Error fetching IFA records:", e); - response.put("statusCode", HttpStatus.INTERNAL_SERVER_ERROR.value()); + response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } From e7d748ea1e59614149ed86bafecd1b401dc5f97f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 13:30:59 +0530 Subject: [PATCH 367/450] change status code --- .../flw/repo/identity/BeneficiaryRepo.java | 3 + .../impl/AbhaBeneficiaryServiceImpl.java | 55 ++++++++++++------- 2 files changed, 38 insertions(+), 20 deletions(-) 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 ec7aebe87..2bfeaaffc 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -83,6 +83,9 @@ Page getBenDataWithinDates( @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 HealthIdNumber,HealthID FROM db_iemr.m_benhealthidmapping WHERE HealthIdNumber = :HealthIdNumber ") + Object[] getHealthIdNumber(@Param("HealthIdNumber") String HealthIdNumber); @Query(nativeQuery = true, value = " SELECT HealthID,HealthIdNumber,isNewAbha FROM db_iemr.t_healthid WHERE HealthIdNumber = :healthIdNumber ") ArrayList getBenHealthDetails(@Param("healthIdNumber") String healthIdNumber); diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index dc1da0883..245b12e2f 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -29,6 +29,8 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { @Autowired private BeneficiaryRepo beneficiaryRepo; + + @Value("${govthealth.user.details.url}") private String getUserDetailsUrl; @@ -42,6 +44,23 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { public Object getBeneficiaryByAbha(AbhaRequestDTO request) { try { + Object[] benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(request.getCardNo()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (request.getCardNo().equals(healthIdNumber)) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "This ABHA No already exists"); + + return response; + } + } AbhaApiResponse abhaApiResponse = getAbhaResponse(request.getCardNo()).getBody(); @@ -58,29 +77,25 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { // Check if ABHA already exists in system - List health = - beneficiaryRepo.getBenHealthDetails(dto.getAbhaId()); - - if (health != null && !health.isEmpty()) { - - for (Object[] objects : health) { - - if (objects != null - && objects.length > 1 - && dto.getAbhaId() != null - && dto.getAbhaId() - .equals(String.valueOf(objects[1]))) { - - Map response = new HashMap<>(); - response.put("statusCode", 5000); - response.put("message", - "This ABHA No already exists"); - - return response; - } + benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(dto.getAbhaId()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (dto.getAbhaId().equals(healthIdNumber)) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "This ABHA No already exists"); + + return response; } } + // Split name into firstName and lastName String personName = dto.getPersonName(); From e541089a769f5afd2a344326016fac70cc0e4cae Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 14:25:12 +0530 Subject: [PATCH 368/450] handel duplicate record --- .../com/iemr/flw/controller/DiseaseControlController.java | 6 ++++++ .../com/iemr/flw/controller/MalariaFollowUpController.java | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java index 816fb244f..764ebeaf6 100644 --- a/src/main/java/com/iemr/flw/controller/DiseaseControlController.java +++ b/src/main/java/com/iemr/flw/controller/DiseaseControlController.java @@ -210,6 +210,8 @@ public ResponseEntity> getAllLeprosy( response.put("statusCode", 5000); } } catch (Exception e) { + logger.info("Fail leprosy: "+e.getMessage()); + logger.info("Fail leprosy full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } @@ -240,6 +242,8 @@ public ResponseEntity> getAllLeprosyFollowUp( response.put("statusCode", 5000); } } catch (Exception e) { + logger.info("Fail leprosy followUp: "+e.getMessage()); + logger.info("Fail leprosy full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } @@ -256,6 +260,8 @@ public ResponseEntity> getAllData( response.put("data", diseaseControlService.getAllScreeningData(getDiseaseRequestHandler)); } catch (Exception e) { + logger.info("getAllDisease "+e.getMessage()); + logger.info("Fail getAllDisease full error: "+e); response.put("status", "Error" + e.getMessage()); response.put("statusCode", 5000); } diff --git a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java index c2b421d6f..29204ab63 100644 --- a/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java +++ b/src/main/java/com/iemr/flw/controller/MalariaFollowUpController.java @@ -29,6 +29,8 @@ import com.iemr.flw.dto.iemr.MalariaFollowUpDTO; import com.iemr.flw.service.MalariaFollowUpService; import com.iemr.flw.utils.JwtUtil; +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.*; @@ -40,6 +42,7 @@ @RestController @RequestMapping(value = "/follow-up", headers = "Authorization") public class MalariaFollowUpController { + private final Logger logger = LoggerFactory.getLogger(MalariaFollowUpController.class); @Autowired private JwtUtil jwtUtil; @@ -88,6 +91,8 @@ public ResponseEntity> getFollowUpsByUserId(@RequestBody Get } } catch (Exception e) { + logger.info("Fail Malaria followUp: "+e.getMessage()); + logger.info("Fail Malaria full error: "+e); response.put("status", "Error: " + e.getMessage()); response.put("statusCode", 5000); } From 70ce89c4c215df45728dfd721eca3c0e474936e4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 14:33:18 +0530 Subject: [PATCH 369/450] handel duplicate record --- .../impl/DiseaseControlServiceImpl.java | 51 ++++++++++++++----- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 1be6a5dc7..9f749e96c 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -709,19 +709,44 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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()); + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getHomeVisitDate() != null) + dto.setHomeVisitDate(disease.getHomeVisitDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setLeprosyStatus(disease.getLeprosyStatus()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredTo() != null && !disease.getOtherReferredTo().trim().isEmpty()) + dto.setOtherReferredTo(disease.getOtherReferredTo()); + + if (disease.getLeprosyStatusDate() != null) + dto.setLeprosyStatusDate(disease.getLeprosyStatusDate()); + + if (disease.getTypeOfLeprosy() != null && !disease.getTypeOfLeprosy().trim().isEmpty()) + dto.setTypeOfLeprosy(disease.getTypeOfLeprosy()); + + if (disease.getFollowUpDate() != null) + dto.setFollowUpDate(disease.getFollowUpDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getLeprosyStatus()); + + if (disease.getRemark() != null && !disease.getRemark().trim().isEmpty()) + dto.setRemark(disease.getRemark()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; From 8c61eb85bfd1f8b0e807cb32545e401c6d2b822c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 14:41:37 +0530 Subject: [PATCH 370/450] handel duplicate record --- .../service/impl/ChildCareServiceImpl.java | 88 ++++++++++--------- 1 file changed, 48 insertions(+), 40 deletions(-) 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 2471f7ea1..dd593e550 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -361,8 +361,11 @@ public List getChildVaccinationDetails(GetBenRequestHandler List result = new ArrayList<>(); vaccinationDetails.forEach(childVaccination -> { ChildVaccinationDTO vaccinationDTO = mapper.convertValue(childVaccination, ChildVaccinationDTO.class); - BigInteger benId = beneficiaryRepo.getBenIdFromRegID(childVaccination.getBeneficiaryRegId()); - vaccinationDTO.setBeneficiaryId(benId.longValue()); + if(childVaccination.getBeneficiaryRegId()!=null){ + BigInteger benId = beneficiaryRepo.getBenIdFromRegID(childVaccination.getBeneficiaryRegId()); + vaccinationDTO.setBeneficiaryId(benId.longValue()); + + } result.add(vaccinationDTO); checkAndAddIncentives(vaccinationDetails); @@ -946,50 +949,55 @@ private void checkAndAddIncentives(List vaccinationList) { 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 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, immunizationActivityAM); - } + if(vaccination.getBeneficiaryRegId()!=null){ + Long benId = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()).longValue(); + + Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); + Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); + 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, immunizationActivityAM); + } - if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + 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, immunizationActivity2AM); + } + if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getSecondYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + } } - } 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, immunizationActivity2AM); + IncentiveActivity immunizationActivity5AM = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.IMMUNIZATION.getDisplayName()); + if (immunizationActivity5AM != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5AM); } - if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + + IncentiveActivity immunizationActivity5CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); } - } - 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); } + }); } From 3453a0a7601457888ca9b2daa483a53c860fe4e5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 14:46:28 +0530 Subject: [PATCH 371/450] handel duplicate record --- .../impl/DiseaseControlServiceImpl.java | 124 ++++++++++-------- 1 file changed, 67 insertions(+), 57 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 9f749e96c..716a8ecb3 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -317,39 +317,42 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { } } if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + if(screeningLeprosy.getTypeOfLeprosy()!=null){ + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } } + } return "Data add successfully"; @@ -462,39 +465,43 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) } } if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + if(screeningLeprosy.getTypeOfLeprosy()!=null){ + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } } + + } } @@ -842,7 +849,10 @@ private ScreeningLeprosy saveLeprosyData(DiseaseLeprosyDTO diseaseControlData) { diseaseLeprosy.setDiseaseTypeId(diseaseControlData.getDiseaseTypeId()); diseaseLeprosy.setOtherReferredTo(diseaseControlData.getOtherReferredTo()); diseaseLeprosy.setLeprosyStatusDate(diseaseControlData.getLeprosyStatusDate()); - diseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + if(diseaseControlData.getTypeOfLeprosy()!=null){ + diseaseLeprosy.setTypeOfLeprosy(diseaseControlData.getTypeOfLeprosy()); + + } diseaseLeprosy.setFollowUpDate(diseaseControlData.getFollowUpDate()); diseaseLeprosy.setBeneficiaryStatus(diseaseControlData.getBeneficiaryStatus()); diseaseLeprosy.setBeneficiaryStatusId(diseaseControlData.getBeneficiaryStatusId()); From f572b12137f1dd7cad07a5033ac87e159c8b4891 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 14:56:41 +0530 Subject: [PATCH 372/450] handel duplicate record --- .../java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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 4cfdff641..cf8f020e7 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -456,6 +456,8 @@ private String getMappingsForAddressIDs(List addressLi // mapping not available } } catch (Exception e) { + logger.info("Error for ben :"+e.getMessage()); + logger.info("Error for ben :"+e); logger.error("error for addressID :" + e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } } From eb34e0a94a31de153390734aecc2891bc893ddbc Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 15:11:03 +0530 Subject: [PATCH 373/450] handel duplicate record --- .../com/iemr/flw/service/impl/ChildCareServiceImpl.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 dd593e550..1a7b1aee1 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -949,8 +949,12 @@ private void checkAndAddIncentives(List vaccinationList) { vaccinationList.forEach(vaccination -> { + Long benId= null; if(vaccination.getBeneficiaryRegId()!=null){ - Long benId = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()).longValue(); + BigInteger benIdObj = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()); + if (benIdObj != null) { + benId = benIdObj.longValue(); + } Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); From 4965ca3171daa90f90380544b794f995e5cd88ba Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 15:24:01 +0530 Subject: [PATCH 374/450] handel duplicate record --- .../flw/repo/identity/BeneficiaryRepo.java | 2 +- .../service/impl/BeneficiaryServiceImpl.java | 517 +++++++++--------- 2 files changed, 261 insertions(+), 258 deletions(-) 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 2bfeaaffc..b3988c3eb 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -48,7 +48,7 @@ Page getBenDataWithinDates( Page getBenDataByUser(@Param("userName") String userName, Pageable pageable); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benAddressId = :addressID") - RMNCHMBeneficiarymapping getByAddressID(@Param("addressID") BigInteger addressID); + List getByAddressID(@Param("addressID") BigInteger addressID); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benRegId = :BenRegId") RMNCHMBeneficiarymapping getById(@Param("BenRegId") BigInteger BenRegId); 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 cf8f020e7..d29fbab8b 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -177,284 +177,287 @@ private String getMappingsForAddressIDs(List addressLi for (RMNCHMBeneficiaryaddress a : addressList) { // exception by-passing try { - RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); - if (m != null) { - benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); - - benDetailsOBJ = new RMNCHMBeneficiarydetail(); - benAccountOBJ = new RMNCHMBeneficiaryAccount(); - benImageOBJ = new RMNCHMBeneficiaryImage(); - benAddressOBJ = new RMNCHMBeneficiaryaddress(); - benContactOBJ = new RMNCHMBeneficiarycontact(); - Map healthDetails = getBenHealthDetails(m.getBenRegId()); - if (m.getBenDetailsId() != null) { - benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); - } - if (m.getBenAccountID() != null) { - benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); - } - if (m.getBenImageId() != null) { - benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); - } - if (m.getBenAddressId() != null) { - benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); - } - if (m.getBenContactsId() != null) { - benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); - } + if(!beneficiaryRepo.getByAddressID(a.getId()).isEmpty()){ + RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()).get(0); + if (m != null) { + benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); + + benDetailsOBJ = new RMNCHMBeneficiarydetail(); + benAccountOBJ = new RMNCHMBeneficiaryAccount(); + benImageOBJ = new RMNCHMBeneficiaryImage(); + benAddressOBJ = new RMNCHMBeneficiaryaddress(); + benContactOBJ = new RMNCHMBeneficiarycontact(); + Map healthDetails = getBenHealthDetails(m.getBenRegId()); + if (m.getBenDetailsId() != null) { + benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); + } + if (m.getBenAccountID() != null) { + benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); + } + if (m.getBenImageId() != null) { + benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); + } + if (m.getBenAddressId() != null) { + benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); + } + if (m.getBenContactsId() != null) { + benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); + } - BigInteger benID = null; - if (m.getBenRegId() != null) - benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + BigInteger benID = null; + if (m.getBenRegId() != null) + benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + + if (m.getBenRegId() != null) { + if(!beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); + + } + + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + + if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) + if(!houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + } - if (m.getBenRegId() != null) { - if(!beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); } + if (benDetailsRMNCH_OBJ == null) + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + + // new mapping 30-06-2021 + if (benDetailsOBJ.getMotherName() != null) + benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); + if (benDetailsOBJ.getLiteracyStatus() != null) + benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); + + // bank + if (benAccountOBJ.getNameOfBank() != null) + benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); + if (benAccountOBJ.getBranchName() != null) + benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); + if (benAccountOBJ.getIfscCode() != null) + benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); + if (benAccountOBJ.getBankAccount() != null) + benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); + + // location + if (benAddressOBJ.getCountyid() != null) + benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); + if (benAddressOBJ.getPermCountry() != null) + benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); + + if (benAddressOBJ.getStatePerm() != null) + benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); + if (benAddressOBJ.getPermState() != null) + benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); + + if (benAddressOBJ.getDistrictidPerm() != null) { + benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + } + if (benAddressOBJ.getDistrictnamePerm() != null) { + benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); + + } - if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - if(!houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + if (benAddressOBJ.getPermSubDistrictId() != null) + benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); + if (benAddressOBJ.getPermSubDistrict() != null) + benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); + + if (benAddressOBJ.getVillageidPerm() != null) + benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); + if (benAddressOBJ.getVillagenamePerm() != null) + benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); + + if (benAddressOBJ.getPermServicePointId() != null) + benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); + if (benAddressOBJ.getPermServicePoint() != null) + benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); + + if (benAddressOBJ.getPermZoneID() != null) + benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); + if (benAddressOBJ.getPermZone() != null) + benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); + + if (benAddressOBJ.getPermAddrLine1() != null) + benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); + if (benAddressOBJ.getPermAddrLine2() != null) + benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); + if (benAddressOBJ.getPermAddrLine3() != null) + benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); + + // ----------------------------------------------------------------------------- + + // related benids + if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { + + String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); + Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; + int pointer = 0; + for (String s : relatedBenIDsString) { + relatedBenIDs[pointer] = Long.valueOf(s); + pointer++; } + benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); + } + // ------------------------------------------------------------------------------ + + if (benDetailsOBJ.getCommunity() != null) + benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); + if (benDetailsOBJ.getCommunityId() != null) + benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); + if (benContactOBJ.getPreferredPhoneNum() != null) + benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); + + if (benDetailsOBJ.getDob() != null) + benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); + if (benDetailsOBJ.getFatherName() != null) + benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); + if (benDetailsOBJ.getFirstName() != null) + benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); + if (benDetailsOBJ.getGender() != null) + benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); + if (benDetailsOBJ.getGenderId() != null) + benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); + + if (benDetailsOBJ.getMaritalstatus() != null) + benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); + if (benDetailsOBJ.getMaritalstatusId() != null) + benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); + if (benDetailsOBJ.getMarriageDate() != null) + benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); + + if (benDetailsOBJ.getReligion() != null) + benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); + if (benDetailsOBJ.getReligionID() != null) + benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); + if (benDetailsOBJ.getSpousename() != null) + benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); + + if (benImageOBJ != null && benImageOBJ.getUser_image() != null) + benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); + + // new fields +// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); + if (benID != null) + benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - } - if (benDetailsRMNCH_OBJ == null) - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + if (benDetailsOBJ.getLastName() != null) + benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - // new mapping 30-06-2021 - if (benDetailsOBJ.getMotherName() != null) - benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); - if (benDetailsOBJ.getLiteracyStatus() != null) - benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); - - // bank - if (benAccountOBJ.getNameOfBank() != null) - benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); - if (benAccountOBJ.getBranchName() != null) - benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); - if (benAccountOBJ.getIfscCode() != null) - benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); - if (benAccountOBJ.getBankAccount() != null) - benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); - - // location - if (benAddressOBJ.getCountyid() != null) - benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); - if (benAddressOBJ.getPermCountry() != null) - benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); - - if (benAddressOBJ.getStatePerm() != null) - benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); - if (benAddressOBJ.getPermState() != null) - benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); - - if (benAddressOBJ.getDistrictidPerm() != null) { - benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); + if (benDetailsRMNCH_OBJ.getCreatedBy() == null) + if (benDetailsOBJ.getCreatedBy() != null) + benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - } - if (benAddressOBJ.getDistrictnamePerm() != null) { - benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); + // age calculation + String ageDetails = ""; + int age_val = 0; + String ageUnit = null; + if (benDetailsOBJ.getDob() != null) { - } + Date date = new Date(benDetailsOBJ.getDob().getTime()); + Calendar cal = Calendar.getInstance(); - if (benAddressOBJ.getPermSubDistrictId() != null) - benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); - if (benAddressOBJ.getPermSubDistrict() != null) - benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); - - if (benAddressOBJ.getVillageidPerm() != null) - benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); - if (benAddressOBJ.getVillagenamePerm() != null) - benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); - - if (benAddressOBJ.getPermServicePointId() != null) - benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); - if (benAddressOBJ.getPermServicePoint() != null) - benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); - - if (benAddressOBJ.getPermZoneID() != null) - benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); - if (benAddressOBJ.getPermZone() != null) - benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); - - if (benAddressOBJ.getPermAddrLine1() != null) - benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); - if (benAddressOBJ.getPermAddrLine2() != null) - benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); - if (benAddressOBJ.getPermAddrLine3() != null) - benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); - - // ----------------------------------------------------------------------------- - - // related benids - if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { - - String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); - Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; - int pointer = 0; - for (String s : relatedBenIDsString) { - relatedBenIDs[pointer] = Long.valueOf(s); - pointer++; - } + cal.setTime(date); - benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); - } - // ------------------------------------------------------------------------------ - - if (benDetailsOBJ.getCommunity() != null) - benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); - if (benDetailsOBJ.getCommunityId() != null) - benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); - if (benContactOBJ.getPreferredPhoneNum() != null) - benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); - - if (benDetailsOBJ.getDob() != null) - benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); - if (benDetailsOBJ.getFatherName() != null) - benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); - if (benDetailsOBJ.getFirstName() != null) - benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); - if (benDetailsOBJ.getGender() != null) - benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); - if (benDetailsOBJ.getGenderId() != null) - benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); - - if (benDetailsOBJ.getMaritalstatus() != null) - benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); - if (benDetailsOBJ.getMaritalstatusId() != null) - benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); - if (benDetailsOBJ.getMarriageDate() != null) - benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); - - if (benDetailsOBJ.getReligion() != null) - benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); - if (benDetailsOBJ.getReligionID() != null) - benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); - if (benDetailsOBJ.getSpousename() != null) - benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); - - if (benImageOBJ != null && benImageOBJ.getUser_image() != null) - benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); - - // new fields -// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); - if (benID != null) - benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - - if (benDetailsOBJ.getLastName() != null) - benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - - if (benDetailsRMNCH_OBJ.getCreatedBy() == null) - if (benDetailsOBJ.getCreatedBy() != null) - benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - - // age calculation - String ageDetails = ""; - int age_val = 0; - String ageUnit = null; - if (benDetailsOBJ.getDob() != null) { - - Date date = new Date(benDetailsOBJ.getDob().getTime()); - Calendar cal = Calendar.getInstance(); - - cal.setTime(date); - - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - - java.time.LocalDate todayDate = java.time.LocalDate.now(); - java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); - Period p = Period.between(birthdate, todayDate); - - int d = p.getDays(); - int mo = p.getMonths(); - int y = p.getYears(); - - if (y > 0) { - ageDetails = y + " years - " + mo + " months"; - age_val = y; - ageUnit = (age_val > 1) ? "Years" : "Year"; - } else { - if (mo > 0) { - ageDetails = mo + " months - " + d + " days"; - age_val = mo; - ageUnit = (age_val > 1) ? "Months" : "Month"; + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + + java.time.LocalDate todayDate = java.time.LocalDate.now(); + java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); + Period p = Period.between(birthdate, todayDate); + + int d = p.getDays(); + int mo = p.getMonths(); + int y = p.getYears(); + + if (y > 0) { + ageDetails = y + " years - " + mo + " months"; + age_val = y; + ageUnit = (age_val > 1) ? "Years" : "Year"; } else { - ageDetails = d + " days"; - age_val = d; - ageUnit = (age_val > 1) ? "Days" : "Day"; + if (mo > 0) { + ageDetails = mo + " months - " + d + " days"; + age_val = mo; + ageUnit = (age_val > 1) ? "Months" : "Month"; + } else { + ageDetails = d + " days"; + age_val = d; + ageUnit = (age_val > 1) ? "Days" : "Day"; + } } - } - } + } - benDetailsRMNCH_OBJ.setAgeFull(ageDetails); - benDetailsRMNCH_OBJ.setAge(age_val); - if (ageUnit != null) - benDetailsRMNCH_OBJ.setAge_unit(ageUnit); - - resultMap = new HashMap<>(); - if (benHouseHoldRMNCH_ROBJ != null) - resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); - else - resultMap.put("householdDetails", new HashMap()); - - if (benBotnBirthRMNCH_ROBJ != null) - resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); - else - resultMap.put("bornbirthDeatils", new HashMap()); - - resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); - 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() != null - ? benDetailsRMNCH_OBJ.getIsDeactivate() - : false - ); - resultMap.put("BenRegId", m.getBenRegId()); - - // adding asha id / created by - user id - if (benAddressOBJ.getCreatedBy() != null) { - Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); - if (userID != null && userID > 0) - resultMap.put("ashaId", userID); - } - // get HealthID of ben - if (m.getBenRegId() != null) { - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); - } + benDetailsRMNCH_OBJ.setAgeFull(ageDetails); + benDetailsRMNCH_OBJ.setAge(age_val); + if (ageUnit != null) + benDetailsRMNCH_OBJ.setAge_unit(ageUnit); + + resultMap = new HashMap<>(); + if (benHouseHoldRMNCH_ROBJ != null) + resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); + else + resultMap.put("householdDetails", new HashMap()); + + if (benBotnBirthRMNCH_ROBJ != null) + resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); + else + resultMap.put("bornbirthDeatils", new HashMap()); + + resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); + 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() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); + resultMap.put("BenRegId", m.getBenRegId()); + + // adding asha id / created by - user id + if (benAddressOBJ.getCreatedBy() != null) { + Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); + if (userID != null && userID > 0) + resultMap.put("ashaId", userID); + } + // get HealthID of ben + if (m.getBenRegId() != null) { + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); + } - resultList.add(resultMap); + resultList.add(resultMap); - } else { - // mapping not available + } else { + // mapping not available + } } + } catch (Exception e) { logger.info("Error for ben :"+e.getMessage()); logger.info("Error for ben :"+e); From d3dc8127f08a5b5bfb977e47bcd6c0d2ba1e6a3f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 15:30:05 +0530 Subject: [PATCH 375/450] handel duplicate record --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 1a7b1aee1..bf66dd735 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -368,7 +368,6 @@ public List getChildVaccinationDetails(GetBenRequestHandler } result.add(vaccinationDTO); - checkAndAddIncentives(vaccinationDetails); }); return result; } catch (Exception e) { From 686ba7534f6801acfda6c6de71280b11a85bc459 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 15:35:33 +0530 Subject: [PATCH 376/450] fix sync issue --- .../flw/repo/identity/BeneficiaryRepo.java | 2 +- .../service/impl/BeneficiaryServiceImpl.java | 521 +++++++++--------- .../impl/DiseaseControlServiceImpl.java | 108 ++-- 3 files changed, 331 insertions(+), 300 deletions(-) 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 6c2d2b42e..fef08d7ff 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -45,7 +45,7 @@ Page getBenDataWithinDates( Page getBenDataByUser(@Param("userName") String userName, Pageable pageable); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benAddressId = :addressID") - RMNCHMBeneficiarymapping getByAddressID(@Param("addressID") BigInteger addressID); + List getByAddressID(@Param("addressID") BigInteger addressID); @Query(value = " SELECT t FROM RMNCHMBeneficiarymapping t WHERE t.benRegId = :BenRegId") RMNCHMBeneficiarymapping getById(@Param("BenRegId") BigInteger BenRegId); 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 5388ea95d..a4c1c6755 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -172,286 +172,289 @@ private String getMappingsForAddressIDs(List addressLi for (RMNCHMBeneficiaryaddress a : addressList) { // exception by-passing try { - RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()); - if (m != null) { - benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); - benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); - - benDetailsOBJ = new RMNCHMBeneficiarydetail(); - benAccountOBJ = new RMNCHMBeneficiaryAccount(); - benImageOBJ = new RMNCHMBeneficiaryImage(); - benAddressOBJ = new RMNCHMBeneficiaryaddress(); - benContactOBJ = new RMNCHMBeneficiarycontact(); - Map healthDetails = getBenHealthDetails(m.getBenRegId()); - if (m.getBenDetailsId() != null) { - benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); - } - if (m.getBenAccountID() != null) { - benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); - } - if (m.getBenImageId() != null) { - benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); - } - if (m.getBenAddressId() != null) { - benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); - } - if (m.getBenContactsId() != null) { - benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); - } + if(!beneficiaryRepo.getByAddressID(a.getId()).isEmpty()){ + RMNCHMBeneficiarymapping m = beneficiaryRepo.getByAddressID(a.getId()).get(0); + if (m != null) { + benHouseHoldRMNCH_ROBJ = new RMNCHHouseHoldDetails(); + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + benBotnBirthRMNCH_ROBJ = new RMNCHBornBirthDetails(); + + benDetailsOBJ = new RMNCHMBeneficiarydetail(); + benAccountOBJ = new RMNCHMBeneficiaryAccount(); + benImageOBJ = new RMNCHMBeneficiaryImage(); + benAddressOBJ = new RMNCHMBeneficiaryaddress(); + benContactOBJ = new RMNCHMBeneficiarycontact(); + Map healthDetails = getBenHealthDetails(m.getBenRegId()); + if (m.getBenDetailsId() != null) { + benDetailsOBJ = beneficiaryRepo.getDetailsById(m.getBenDetailsId()); + } + if (m.getBenAccountID() != null) { + benAccountOBJ = beneficiaryRepo.getAccountById(m.getBenAccountID()); + } + if (m.getBenImageId() != null) { + benImageOBJ = beneficiaryRepo.getImageById(m.getBenImageId().longValue()); + } + if (m.getBenAddressId() != null) { + benAddressOBJ = beneficiaryRepo.getAddressById(m.getBenAddressId()); + } + if (m.getBenContactsId() != null) { + benContactOBJ = beneficiaryRepo.getContactById(m.getBenContactsId()); + } - BigInteger benID = null; - if (m.getBenRegId() != null) - benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + BigInteger benID = null; + if (m.getBenRegId() != null) + benID = beneficiaryRepo.getBenIdFromRegID(m.getBenRegId().longValue()); + + if (m.getBenRegId() != null) { + if(!beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benDetailsRMNCH_OBJ = beneficiaryRepo + .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); + + } + + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + + if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) + if(!houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ + benHouseHoldRMNCH_ROBJ = houseHoldRepo + .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + } - if (m.getBenRegId() != null) { - if(!beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ - benDetailsRMNCH_OBJ = beneficiaryRepo - .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); } + if (benDetailsRMNCH_OBJ == null) + benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + + // new mapping 30-06-2021 + if (benDetailsOBJ.getMotherName() != null) + benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); + if (benDetailsOBJ.getLiteracyStatus() != null) + benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); + + // bank + if (benAccountOBJ.getNameOfBank() != null) + benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); + if (benAccountOBJ.getBranchName() != null) + benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); + if (benAccountOBJ.getIfscCode() != null) + benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); + if (benAccountOBJ.getBankAccount() != null) + benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); + + // location + if (benAddressOBJ.getCountyid() != null) + benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); + if (benAddressOBJ.getPermCountry() != null) + benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); + + if (benAddressOBJ.getStatePerm() != null) + benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); + if (benAddressOBJ.getPermState() != null) + benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); + + if (benAddressOBJ.getDistrictidPerm() != null) { + benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + } + if (benAddressOBJ.getDistrictnamePerm() != null) { + benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); + + } - if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) - if(!houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ - benHouseHoldRMNCH_ROBJ = houseHoldRepo - .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).get(0); + if (benAddressOBJ.getPermSubDistrictId() != null) + benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); + if (benAddressOBJ.getPermSubDistrict() != null) + benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); + + if (benAddressOBJ.getVillageidPerm() != null) + benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); + if (benAddressOBJ.getVillagenamePerm() != null) + benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); + + if (benAddressOBJ.getPermServicePointId() != null) + benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); + if (benAddressOBJ.getPermServicePoint() != null) + benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); + + if (benAddressOBJ.getPermZoneID() != null) + benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); + if (benAddressOBJ.getPermZone() != null) + benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); + + if (benAddressOBJ.getPermAddrLine1() != null) + benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); + if (benAddressOBJ.getPermAddrLine2() != null) + benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); + if (benAddressOBJ.getPermAddrLine3() != null) + benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); + + // ----------------------------------------------------------------------------- + + // related benids + if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { + + String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); + Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; + int pointer = 0; + for (String s : relatedBenIDsString) { + relatedBenIDs[pointer] = Long.valueOf(s); + pointer++; } + benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); + } + // ------------------------------------------------------------------------------ + + if (benDetailsOBJ.getCommunity() != null) + benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); + if (benDetailsOBJ.getCommunityId() != null) + benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); + if (benContactOBJ.getPreferredPhoneNum() != null) + benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); + + if (benDetailsOBJ.getDob() != null) + benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); + if (benDetailsOBJ.getFatherName() != null) + benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); + if (benDetailsOBJ.getFirstName() != null) + benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); + if (benDetailsOBJ.getGender() != null) + benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); + if (benDetailsOBJ.getGenderId() != null) + benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); + + if (benDetailsOBJ.getMaritalstatus() != null) + benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); + if (benDetailsOBJ.getMaritalstatusId() != null) + benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); + if (benDetailsOBJ.getMarriageDate() != null) + benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); + + if (benDetailsOBJ.getReligion() != null) + benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); + if (benDetailsOBJ.getReligionID() != null) + benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); + if (benDetailsOBJ.getSpousename() != null) + benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); + + if (benImageOBJ != null && benImageOBJ.getUser_image() != null) + benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); + + // new fields +// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); + if (benID != null) + benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - } - if (benDetailsRMNCH_OBJ == null) - benDetailsRMNCH_OBJ = new RMNCHBeneficiaryDetailsRmnch(); + if (benDetailsOBJ.getLastName() != null) + benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - // new mapping 30-06-2021 - if (benDetailsOBJ.getMotherName() != null) - benDetailsRMNCH_OBJ.setMotherName(benDetailsOBJ.getMotherName()); - if (benDetailsOBJ.getLiteracyStatus() != null) - benDetailsRMNCH_OBJ.setLiteracyStatus(benDetailsOBJ.getLiteracyStatus()); - - // bank - if (benAccountOBJ.getNameOfBank() != null) - benDetailsRMNCH_OBJ.setNameOfBank(benAccountOBJ.getNameOfBank()); - if (benAccountOBJ.getBranchName() != null) - benDetailsRMNCH_OBJ.setBranchName(benAccountOBJ.getBranchName()); - if (benAccountOBJ.getIfscCode() != null) - benDetailsRMNCH_OBJ.setIfscCode(benAccountOBJ.getIfscCode()); - if (benAccountOBJ.getBankAccount() != null) - benDetailsRMNCH_OBJ.setBankAccount(benAccountOBJ.getBankAccount()); - - // location - if (benAddressOBJ.getCountyid() != null) - benDetailsRMNCH_OBJ.setCountryId(benAddressOBJ.getCountyid()); - if (benAddressOBJ.getPermCountry() != null) - benDetailsRMNCH_OBJ.setCountryName(benAddressOBJ.getPermCountry()); - - if (benAddressOBJ.getStatePerm() != null) - benDetailsRMNCH_OBJ.setStateId(benAddressOBJ.getStatePerm()); - if (benAddressOBJ.getPermState() != null) - benDetailsRMNCH_OBJ.setStateName(benAddressOBJ.getPermState()); - - if (benAddressOBJ.getDistrictidPerm() != null) { - benDetailsRMNCH_OBJ.setDistrictid(benAddressOBJ.getDistrictidPerm()); + if (benDetailsRMNCH_OBJ.getCreatedBy() == null) + if (benDetailsOBJ.getCreatedBy() != null) + benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - } - if (benAddressOBJ.getDistrictnamePerm() != null) { - benDetailsRMNCH_OBJ.setDistrictname(benAddressOBJ.getDistrictnamePerm()); + // age calculation + String ageDetails = ""; + int age_val = 0; + String ageUnit = null; + if (benDetailsOBJ.getDob() != null) { - } + Date date = new Date(benDetailsOBJ.getDob().getTime()); + Calendar cal = Calendar.getInstance(); - if (benAddressOBJ.getPermSubDistrictId() != null) - benDetailsRMNCH_OBJ.setBlockId(benAddressOBJ.getPermSubDistrictId()); - if (benAddressOBJ.getPermSubDistrict() != null) - benDetailsRMNCH_OBJ.setBlockName(benAddressOBJ.getPermSubDistrict()); - - if (benAddressOBJ.getVillageidPerm() != null) - benDetailsRMNCH_OBJ.setVillageId(benAddressOBJ.getVillageidPerm()); - if (benAddressOBJ.getVillagenamePerm() != null) - benDetailsRMNCH_OBJ.setVillageName(benAddressOBJ.getVillagenamePerm()); - - if (benAddressOBJ.getPermServicePointId() != null) - benDetailsRMNCH_OBJ.setServicePointID(benAddressOBJ.getPermServicePointId()); - if (benAddressOBJ.getPermServicePoint() != null) - benDetailsRMNCH_OBJ.setServicePointName(benAddressOBJ.getPermServicePoint()); - - if (benAddressOBJ.getPermZoneID() != null) - benDetailsRMNCH_OBJ.setZoneID(benAddressOBJ.getPermZoneID()); - if (benAddressOBJ.getPermZone() != null) - benDetailsRMNCH_OBJ.setZoneName(benAddressOBJ.getPermZone()); - - if (benAddressOBJ.getPermAddrLine1() != null) - benDetailsRMNCH_OBJ.setAddressLine1(benAddressOBJ.getPermAddrLine1()); - if (benAddressOBJ.getPermAddrLine2() != null) - benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); - if (benAddressOBJ.getPermAddrLine3() != null) - benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); - - // ----------------------------------------------------------------------------- - - // related benids - if (benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB() != null) { - - String[] relatedBenIDsString = benDetailsRMNCH_OBJ.getRelatedBeneficiaryIdsDB().split(","); - Long[] relatedBenIDs = new Long[relatedBenIDsString.length]; - int pointer = 0; - for (String s : relatedBenIDsString) { - relatedBenIDs[pointer] = Long.valueOf(s); - pointer++; - } + cal.setTime(date); - benDetailsRMNCH_OBJ.setRelatedBeneficiaryIds(relatedBenIDs); - } - // ------------------------------------------------------------------------------ - - if (benDetailsOBJ.getCommunity() != null) - benDetailsRMNCH_OBJ.setCommunity(benDetailsOBJ.getCommunity()); - if (benDetailsOBJ.getCommunityId() != null) - benDetailsRMNCH_OBJ.setCommunityId(benDetailsOBJ.getCommunityId()); - if (benContactOBJ.getPreferredPhoneNum() != null) - benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); - - if (benDetailsOBJ.getDob() != null) - benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); - if (benDetailsOBJ.getFatherName() != null) - benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); - if (benDetailsOBJ.getFirstName() != null) - benDetailsRMNCH_OBJ.setFirstName(benDetailsOBJ.getFirstName()); - if (benDetailsOBJ.getGender() != null) - benDetailsRMNCH_OBJ.setGender(benDetailsOBJ.getGender()); - if (benDetailsOBJ.getGenderId() != null) - benDetailsRMNCH_OBJ.setGenderId(benDetailsOBJ.getGenderId()); - - if (benDetailsOBJ.getMaritalstatus() != null) - benDetailsRMNCH_OBJ.setMaritalstatus(benDetailsOBJ.getMaritalstatus()); - if (benDetailsOBJ.getMaritalstatusId() != null) - benDetailsRMNCH_OBJ.setMaritalstatusId(benDetailsOBJ.getMaritalstatusId()); - if (benDetailsOBJ.getMarriageDate() != null) - benDetailsRMNCH_OBJ.setMarriageDate(benDetailsOBJ.getMarriageDate()); - - if (benDetailsOBJ.getReligion() != null) - benDetailsRMNCH_OBJ.setReligion(benDetailsOBJ.getReligion()); - if (benDetailsOBJ.getReligionID() != null) - benDetailsRMNCH_OBJ.setReligionID(benDetailsOBJ.getReligionID()); - if (benDetailsOBJ.getSpousename() != null) - benDetailsRMNCH_OBJ.setSpousename(benDetailsOBJ.getSpousename()); - - if (benImageOBJ != null && benImageOBJ.getUser_image() != null) - benDetailsRMNCH_OBJ.setUser_image(benImageOBJ.getUser_image()); - - // new fields -// benDetailsRMNCH_OBJ.setRegistrationDate(benDetailsOBJ.getCreatedDate()); - if (benID != null) - benDetailsRMNCH_OBJ.setBenficieryid(benID.longValue()); - - if (benDetailsOBJ.getLastName() != null) - benDetailsRMNCH_OBJ.setLastName(benDetailsOBJ.getLastName()); - - if (benDetailsRMNCH_OBJ.getCreatedBy() == null) - if (benDetailsOBJ.getCreatedBy() != null) - benDetailsRMNCH_OBJ.setCreatedBy(benDetailsOBJ.getCreatedBy()); - - // age calculation - String ageDetails = ""; - int age_val = 0; - String ageUnit = null; - if (benDetailsOBJ.getDob() != null) { - - Date date = new Date(benDetailsOBJ.getDob().getTime()); - Calendar cal = Calendar.getInstance(); - - cal.setTime(date); - - int year = cal.get(Calendar.YEAR); - int month = cal.get(Calendar.MONTH) + 1; - int day = cal.get(Calendar.DAY_OF_MONTH); - - java.time.LocalDate todayDate = java.time.LocalDate.now(); - java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); - Period p = Period.between(birthdate, todayDate); - - int d = p.getDays(); - int mo = p.getMonths(); - int y = p.getYears(); - - if (y > 0) { - ageDetails = y + " years - " + mo + " months"; - age_val = y; - ageUnit = (age_val > 1) ? "Years" : "Year"; - } else { - if (mo > 0) { - ageDetails = mo + " months - " + d + " days"; - age_val = mo; - ageUnit = (age_val > 1) ? "Months" : "Month"; + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + int day = cal.get(Calendar.DAY_OF_MONTH); + + java.time.LocalDate todayDate = java.time.LocalDate.now(); + java.time.LocalDate birthdate = java.time.LocalDate.of(year, month, day); + Period p = Period.between(birthdate, todayDate); + + int d = p.getDays(); + int mo = p.getMonths(); + int y = p.getYears(); + + if (y > 0) { + ageDetails = y + " years - " + mo + " months"; + age_val = y; + ageUnit = (age_val > 1) ? "Years" : "Year"; } else { - ageDetails = d + " days"; - age_val = d; - ageUnit = (age_val > 1) ? "Days" : "Day"; + if (mo > 0) { + ageDetails = mo + " months - " + d + " days"; + age_val = mo; + ageUnit = (age_val > 1) ? "Months" : "Month"; + } else { + ageDetails = d + " days"; + age_val = d; + ageUnit = (age_val > 1) ? "Days" : "Day"; + } } - } - } + } - benDetailsRMNCH_OBJ.setAgeFull(ageDetails); - benDetailsRMNCH_OBJ.setAge(age_val); - if (ageUnit != null) - benDetailsRMNCH_OBJ.setAge_unit(ageUnit); - - resultMap = new HashMap<>(); - if (benHouseHoldRMNCH_ROBJ != null) - resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); - else - resultMap.put("householdDetails", new HashMap()); - - if (benBotnBirthRMNCH_ROBJ != null) - resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); - else - resultMap.put("bornbirthDeatils", new HashMap()); - - resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); - 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() != null - ? benDetailsRMNCH_OBJ.getIsDeactivate() - : false - ); - resultMap.put("BenRegId", m.getBenRegId()); - - // adding asha id / created by - user id - if (benAddressOBJ.getCreatedBy() != null) { - Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); - if (userID != null && userID > 0) - resultMap.put("ashaId", userID); - } - // get HealthID of ben - if (m.getBenRegId() != null) { - fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); - } + benDetailsRMNCH_OBJ.setAgeFull(ageDetails); + benDetailsRMNCH_OBJ.setAge(age_val); + if (ageUnit != null) + benDetailsRMNCH_OBJ.setAge_unit(ageUnit); + + resultMap = new HashMap<>(); + if (benHouseHoldRMNCH_ROBJ != null) + resultMap.put("householdDetails", benHouseHoldRMNCH_ROBJ); + else + resultMap.put("householdDetails", new HashMap()); + + if (benBotnBirthRMNCH_ROBJ != null) + resultMap.put("bornbirthDeatils", benBotnBirthRMNCH_ROBJ); + else + resultMap.put("bornbirthDeatils", new HashMap()); + + resultMap.put("beneficiaryDetails", benDetailsRMNCH_OBJ); + 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() != null + ? benDetailsRMNCH_OBJ.getIsDeactivate() + : false + ); + resultMap.put("BenRegId", m.getBenRegId()); + + // adding asha id / created by - user id + if (benAddressOBJ.getCreatedBy() != null) { + Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); + if (userID != null && userID > 0) + resultMap.put("ashaId", userID); + } + // get HealthID of ben + if (m.getBenRegId() != null) { + fetchHealthIdByBenRegID(m.getBenRegId().longValue(), authorisation, resultMap); + } - resultList.add(resultMap); + resultList.add(resultMap); - } else { - // mapping not available + } else { + // mapping not available + } } + } catch (Exception e) { logger.error("error for addressID :"+e.getMessage() + a.getId() + " and vanID : " + a.getVanID()); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 6335d8e6d..f0edde4fc 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -294,39 +294,42 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { ScreeningLeprosy screeningLeprosy = diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); if (screeningLeprosy != null) { if (screeningLeprosy.getIsConfirmed()) { - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); + if(screeningLeprosy.getTypeOfLeprosy()!=null){ + if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } + if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + screeningLeprosy.getBenId(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); } - } + if (screeningLeprosy.getIsConfirmed()) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForIdentificationLeprosy( @@ -648,19 +651,44 @@ public Object getAllLeprosy(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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()); + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getHomeVisitDate() != null) + dto.setHomeVisitDate(disease.getHomeVisitDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setLeprosyStatus(disease.getLeprosyStatus()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredTo() != null && !disease.getOtherReferredTo().trim().isEmpty()) + dto.setOtherReferredTo(disease.getOtherReferredTo()); + + if (disease.getLeprosyStatusDate() != null) + dto.setLeprosyStatusDate(disease.getLeprosyStatusDate()); + + if (disease.getTypeOfLeprosy() != null && !disease.getTypeOfLeprosy().trim().isEmpty()) + dto.setTypeOfLeprosy(disease.getTypeOfLeprosy()); + + if (disease.getFollowUpDate() != null) + dto.setFollowUpDate(disease.getFollowUpDate()); + + if (disease.getLeprosyStatus() != null && !disease.getLeprosyStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getLeprosyStatus()); + + if (disease.getRemark() != null && !disease.getRemark().trim().isEmpty()) + dto.setRemark(disease.getRemark()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; From 75e06d7d71420ab15e4b8dea11baeaf08f682874 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 15:40:18 +0530 Subject: [PATCH 377/450] fix sync issue --- .../impl/DiseaseControlServiceImpl.java | 272 +++++++++++++----- 1 file changed, 204 insertions(+), 68 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 716a8ecb3..b733725d2 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -535,39 +535,92 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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.setMalariaSlideTestType(disease.getMalariaSlideTestType()); - dto.setMalariaTestType(disease.getMalariaTestType()); - dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); - dto.setUserId(disease.getUserId()); - dto.setDiseaseTypeId(disease.getDiseaseTypeId()); - - // Parse symptoms (if present) + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getScreeningDate() != null) + dto.setScreeningDate(disease.getScreeningDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getCaseStatus() != null && !disease.getCaseStatus().trim().isEmpty()) + dto.setCaseStatus(disease.getCaseStatus()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getSlideTestPf() != null) + dto.setSlideTestPf(disease.getSlideTestPf()); + + if (disease.getSlideTestPv() != null) + dto.setSlideTestPv(disease.getSlideTestPv()); + + if (disease.getDateOfSlideTest() != null) + dto.setDateOfSlideTest(disease.getDateOfSlideTest()); + + if (disease.getSlideNo() != null && !disease.getSlideNo().trim().isEmpty()) + dto.setSlideNo(disease.getSlideNo()); + + if (disease.getReferredTo() != null) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getRemarks() != null && !disease.getRemarks().trim().isEmpty()) + dto.setRemarks(disease.getRemarks()); + + if (disease.getMalariaSlideTestType() != null && !disease.getMalariaSlideTestType().trim().isEmpty()) + dto.setMalariaSlideTestType(disease.getMalariaSlideTestType()); + + if (disease.getMalariaTestType() != null && !disease.getMalariaTestType().trim().isEmpty()) + dto.setMalariaTestType(disease.getMalariaTestType()); + + if (disease.getDateOfVisitBySupervisor() != null) + dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + // Symptoms JSON try { - if (disease.getSymptoms() != null && !disease.getSymptoms().isEmpty()) { - MalariaSymptomsDTO symptomsDTO = objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + if (disease.getSymptoms() != null && + !disease.getSymptoms().trim().isEmpty()) { + + MalariaSymptomsDTO symptomsDTO = + objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + dto.setFeverMoreThanTwoWeeks(symptomsDTO.isFeverMoreThanTwoWeeks()); dto.setFluLikeIllness(symptomsDTO.isFluLikeIllness()); dto.setShakingChills(symptomsDTO.isShakingChills()); @@ -579,7 +632,8 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { dto.setDiarrhea(symptomsDTO.isDiarrhea()); } } catch (Exception e) { - throw new RuntimeException("Error parsing symptoms JSON for Malaria Disease ID: " + disease.getId(), e); + logger.error("Error parsing symptoms for diseaseId={}", + disease.getId(), e); } return dto; @@ -625,30 +679,77 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) // 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()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getVisitDate() != null) + dto.setVisitDate(disease.getVisitDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getKalaAzarCaseStatus() != null && !disease.getKalaAzarCaseStatus().trim().isEmpty()) + dto.setKalaAzarCaseStatus(disease.getKalaAzarCaseStatus()); + + if (disease.getKalaAzarCaseCount() != null) + dto.setKalaAzarCaseCount(disease.getKalaAzarCaseCount()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getFollowUpPoint() != null) + dto.setFollowUpPoint(disease.getFollowUpPoint()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getBeneficiaryStatusId() != null) + dto.setBeneficiaryStatusId(disease.getBeneficiaryStatusId()); + + if (disease.getReferToName() != null && !disease.getReferToName().trim().isEmpty()) + dto.setReferToName(disease.getReferToName()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); return dto; }).collect(Collectors.toList()); @@ -678,23 +779,58 @@ public Object getAllFilaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getSufferingFromFilariasis() != null) + dto.setSufferingFromFilariasis(disease.getSufferingFromFilariasis()); + + if (disease.getAffectedBodyPart() != null && + !disease.getAffectedBodyPart().trim().isEmpty()) + dto.setAffectedBodyPart(disease.getAffectedBodyPart()); + + if (disease.getMdaHomeVisitDate() != null) + dto.setMdaHomeVisitDate(disease.getMdaHomeVisitDate()); + + if (disease.getDoseStatus() != null && + !disease.getDoseStatus().trim().isEmpty()) + dto.setDoseStatus(disease.getDoseStatus()); + + if (disease.getFilariasisCaseCount() != null) + dto.setFilariasisCaseCount(disease.getFilariasisCaseCount()); + + if (disease.getOtherDoseStatusDetails() != null && + !disease.getOtherDoseStatusDetails().trim().isEmpty()) + dto.setOtherDoseStatusDetails(disease.getOtherDoseStatusDetails()); + + if (disease.getMedicineSideEffect() != null) + dto.setMedicineSideEffect(disease.getMedicineSideEffect()); + + if (disease.getOtherSideEffectDetails() != null && + !disease.getOtherSideEffectDetails().trim().isEmpty()) + dto.setOtherSideEffectDetails(disease.getOtherSideEffectDetails()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && + !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; + }).collect(Collectors.toList()); return dtoList; From a6ab6e9f68ead8839ad67bdef87a2ed8902d9d2c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 17 Jun 2026 16:56:06 +0530 Subject: [PATCH 378/450] fix sync issue --- .../service/impl/ChildCareServiceImpl.java | 92 +++--- .../impl/DiseaseControlServiceImpl.java | 269 +++++++++++++----- 2 files changed, 252 insertions(+), 109 deletions(-) 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 27a18653f..d20d6bc41 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -348,7 +348,7 @@ public List getChildVaccinationDetails(GetBenRequestHandler vaccinationDTO.setBeneficiaryId(benId.longValue()); result.add(vaccinationDTO); - checkAndAddIncentives(vaccinationDetails); + // checkAndAddIncentives(vaccinationDetails); }); return result; } catch (Exception e) { @@ -840,53 +840,59 @@ private void checkAndAddHbncIncentives(List hbncVisits) { private void checkAndAddIncentives(List vaccinationList) { - - 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 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, immunizationActivityAM); - } + if(vaccination.getBeneficiaryRegId()!=null){ + BigInteger benIdObj = beneficiaryRepo.getBenIdFromRegID(vaccination.getBeneficiaryRegId()); + if(benIdObj!=null){ + Long benId = benIdObj.longValue(); + + Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); + Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); + 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, immunizationActivityAM); + } + + 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, immunizationActivity2AM); + } + 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); + } - 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, immunizationActivity2AM); - } - if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + IncentiveActivity immunizationActivity5CH = + incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.ACTIVITY.getDisplayName()); + if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); + } } } - 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); - } + }); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index f0edde4fc..a4fd8197a 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -472,37 +472,92 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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) + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getScreeningDate() != null) + dto.setScreeningDate(disease.getScreeningDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getCaseStatus() != null && !disease.getCaseStatus().trim().isEmpty()) + dto.setCaseStatus(disease.getCaseStatus()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getSlideTestPf() != null) + dto.setSlideTestPf(disease.getSlideTestPf()); + + if (disease.getSlideTestPv() != null) + dto.setSlideTestPv(disease.getSlideTestPv()); + + if (disease.getDateOfSlideTest() != null) + dto.setDateOfSlideTest(disease.getDateOfSlideTest()); + + if (disease.getSlideNo() != null && !disease.getSlideNo().trim().isEmpty()) + dto.setSlideNo(disease.getSlideNo()); + + if (disease.getReferredTo() != null) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getRemarks() != null && !disease.getRemarks().trim().isEmpty()) + dto.setRemarks(disease.getRemarks()); + + if (disease.getMalariaSlideTestType() != null && !disease.getMalariaSlideTestType().trim().isEmpty()) + dto.setMalariaSlideTestType(disease.getMalariaSlideTestType()); + + if (disease.getMalariaTestType() != null && !disease.getMalariaTestType().trim().isEmpty()) + dto.setMalariaTestType(disease.getMalariaTestType()); + + if (disease.getDateOfVisitBySupervisor() != null) + dto.setDateOfVisitBySupervisor(disease.getDateOfVisitBySupervisor()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); + + // Symptoms JSON try { - if (disease.getSymptoms() != null && !disease.getSymptoms().isEmpty()) { - MalariaSymptomsDTO symptomsDTO = objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + if (disease.getSymptoms() != null && + !disease.getSymptoms().trim().isEmpty()) { + + MalariaSymptomsDTO symptomsDTO = + objectMapper.readValue(disease.getSymptoms(), MalariaSymptomsDTO.class); + dto.setFeverMoreThanTwoWeeks(symptomsDTO.isFeverMoreThanTwoWeeks()); dto.setFluLikeIllness(symptomsDTO.isFluLikeIllness()); dto.setShakingChills(symptomsDTO.isShakingChills()); @@ -514,7 +569,8 @@ public Object getAllMalaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { dto.setDiarrhea(symptomsDTO.isDiarrhea()); } } catch (Exception e) { - throw new RuntimeException("Error parsing symptoms JSON for Malaria Disease ID: " + disease.getId(), e); + logger.error("Error parsing symptoms for diseaseId={}", + disease.getId(), e); } return dto; @@ -560,30 +616,77 @@ public Object getAllKalaAzar(GetDiseaseRequestHandler getDiseaseRequestHandler) // 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()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getVisitDate() != null) + dto.setVisitDate(disease.getVisitDate()); + + if (disease.getBeneficiaryStatus() != null && !disease.getBeneficiaryStatus().trim().isEmpty()) + dto.setBeneficiaryStatus(disease.getBeneficiaryStatus()); + + if (disease.getDateOfDeath() != null) + dto.setDateOfDeath(disease.getDateOfDeath()); + + if (disease.getPlaceOfDeath() != null && !disease.getPlaceOfDeath().trim().isEmpty()) + dto.setPlaceOfDeath(disease.getPlaceOfDeath()); + + if (disease.getOtherPlaceOfDeath() != null && !disease.getOtherPlaceOfDeath().trim().isEmpty()) + dto.setOtherPlaceOfDeath(disease.getOtherPlaceOfDeath()); + + if (disease.getReasonForDeath() != null && !disease.getReasonForDeath().trim().isEmpty()) + dto.setReasonForDeath(disease.getReasonForDeath()); + + if (disease.getOtherReasonForDeath() != null && !disease.getOtherReasonForDeath().trim().isEmpty()) + dto.setOtherReasonForDeath(disease.getOtherReasonForDeath()); + + if (disease.getKalaAzarCaseStatus() != null && !disease.getKalaAzarCaseStatus().trim().isEmpty()) + dto.setKalaAzarCaseStatus(disease.getKalaAzarCaseStatus()); + + if (disease.getKalaAzarCaseCount() != null) + dto.setKalaAzarCaseCount(disease.getKalaAzarCaseCount()); + + if (disease.getRapidDiagnosticTest() != null) + dto.setRapidDiagnosticTest(disease.getRapidDiagnosticTest()); + + if (disease.getDateOfRdt() != null) + dto.setDateOfRdt(disease.getDateOfRdt()); + + if (disease.getFollowUpPoint() != null) + dto.setFollowUpPoint(disease.getFollowUpPoint()); + + if (disease.getReferredTo() != null && !disease.getReferredTo().trim().isEmpty()) + dto.setReferredTo(disease.getReferredTo()); + + if (disease.getOtherReferredFacility() != null && !disease.getOtherReferredFacility().trim().isEmpty()) + dto.setOtherReferredFacility(disease.getOtherReferredFacility()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getBeneficiaryStatusId() != null) + dto.setBeneficiaryStatusId(disease.getBeneficiaryStatusId()); + + if (disease.getReferToName() != null && !disease.getReferToName().trim().isEmpty()) + dto.setReferToName(disease.getReferToName()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); + + if (disease.getDiseaseTypeId() != null) + dto.setDiseaseTypeId(disease.getDiseaseTypeId()); return dto; }).collect(Collectors.toList()); @@ -613,21 +716,55 @@ public Object getAllFilaria(GetDiseaseRequestHandler getDiseaseRequestHandler) { // 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()); + + if (disease.getId() != null) + dto.setId(disease.getId()); + + if (disease.getBenId() != null) + dto.setBenId(disease.getBenId()); + + if (disease.getHouseHoldDetailsId() != null) + dto.setHouseHoldDetailsId(disease.getHouseHoldDetailsId()); + + if (disease.getSufferingFromFilariasis() != null) + dto.setSufferingFromFilariasis(disease.getSufferingFromFilariasis()); + + if (disease.getAffectedBodyPart() != null && + !disease.getAffectedBodyPart().trim().isEmpty()) + dto.setAffectedBodyPart(disease.getAffectedBodyPart()); + + if (disease.getMdaHomeVisitDate() != null) + dto.setMdaHomeVisitDate(disease.getMdaHomeVisitDate()); + + if (disease.getDoseStatus() != null && + !disease.getDoseStatus().trim().isEmpty()) + dto.setDoseStatus(disease.getDoseStatus()); + + if (disease.getFilariasisCaseCount() != null) + dto.setFilariasisCaseCount(disease.getFilariasisCaseCount()); + + if (disease.getOtherDoseStatusDetails() != null && + !disease.getOtherDoseStatusDetails().trim().isEmpty()) + dto.setOtherDoseStatusDetails(disease.getOtherDoseStatusDetails()); + + if (disease.getMedicineSideEffect() != null) + dto.setMedicineSideEffect(disease.getMedicineSideEffect()); + + if (disease.getOtherSideEffectDetails() != null && + !disease.getOtherSideEffectDetails().trim().isEmpty()) + dto.setOtherSideEffectDetails(disease.getOtherSideEffectDetails()); + + if (disease.getCreatedDate() != null) + dto.setCreatedDate(disease.getCreatedDate()); + + if (disease.getCreatedBy() != null && + !disease.getCreatedBy().trim().isEmpty()) + dto.setCreatedBy(disease.getCreatedBy()); + + if (disease.getUserId() != null) + dto.setUserId(disease.getUserId()); return dto; }).collect(Collectors.toList()); From a09cb7ccf92e17fb4f75343e3df7ce95acd3d3d5 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 19 Jun 2026 20:49:34 +0530 Subject: [PATCH 379/450] feature of abha check in our system --- src/main/environment/common_ci.properties | 5 + src/main/environment/common_docker.properties | 5 + .../controller/AbhaBeneficiaryController.java | 4 +- .../flw/repo/identity/BeneficiaryRepo.java | 3 + .../impl/AbhaBeneficiaryServiceImpl.java | 105 ++++++++++++++---- 5 files changed, 99 insertions(+), 23 deletions(-) diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index af5c31d0b..490804fbf 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -43,3 +43,8 @@ abha.client.id=@env.ABHA_CLIENT_ID@ abha.client.secret=@env.ABHA_CLIENT_SECRET@ abha.token.url=@env.ABHA_TOKEN_URL@ abha.xcmid=@env.ABHA_XCM_ID@ + +# GovThealth API Config +govthealth.user.details.url=@env.GOVTHEALTH_USER_DETAILS_URL@ +govthealth.user.id=@env.GOVTHEALTH_USER_ID@ +govthealth.password=@env.GOVTHEALTH_PASSWORD@ \ No newline at end of file diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index cce60f894..073091334 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -43,5 +43,10 @@ abha.client.secret=${ABHA_CLIENT_SECRET} abha.token.url=${ABHA_TOKEN_URL} abha.xcmid=${ABHA_XCM_ID} +# GovThealth API Config +govthealth.user.details.url=${GOVTHEALTH_USER_DETAILS_URL} +govthealth.user.id=${GOVTHEALTH_USER_ID} +govthealth.password=${GOVTHEALTH_PASSWORD} + diff --git a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java index 28276cb86..8025de558 100644 --- a/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/AbhaBeneficiaryController.java @@ -18,7 +18,7 @@ import java.util.Map; @RestController -@RequestMapping("/abha") +@RequestMapping("/UserRegistration") public class AbhaBeneficiaryController { @Autowired private AbhaBeneficiaryService abhaBeneficiaryService; @@ -27,7 +27,7 @@ public class AbhaBeneficiaryController { - @RequestMapping(value = "/getBeneficiary",method = RequestMethod.POST) + @RequestMapping(value = "/GetUserDetailsByAyushmanCardNo",method = RequestMethod.POST) public ResponseEntity> getAllAdolescentHealth(@RequestBody AbhaRequestDTO request ) { Map response = new HashMap<>(); try { 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 fef08d7ff..cdad27285 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -111,4 +111,7 @@ Page getBenDataWithinDates( "FROM RMNCHBeneficiaryDetailsRmnch b " + "WHERE b.BenRegId IN :regIds AND b.benficieryid IS NOT NULL") List getBenIdsFromRegIDs(@Param("regIds") List regIds); + + @Query(nativeQuery = true, value = " SELECT HealthIdNumber,HealthID FROM db_iemr.m_benhealthidmapping WHERE HealthIdNumber = :HealthIdNumber ") + Object[] getHealthIdNumber(@Param("HealthIdNumber") String HealthIdNumber); } diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index ae96c1ee2..4a75c3b1b 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -1,16 +1,21 @@ package com.iemr.flw.service.impl; +import com.google.gson.Gson; +import com.iemr.flw.controller.AbhaBeneficiaryController; import com.iemr.flw.domain.iemr.AbhaApiResponse; import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; import com.iemr.flw.dto.iemr.AbhaRequestDTO; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.service.AbhaBeneficiaryService; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -18,42 +23,87 @@ @Service public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { + private final org.slf4j.Logger logger = LoggerFactory.getLogger(AbhaBeneficiaryService.class); @Autowired private BeneficiaryRepo beneficiaryRepo; - String url = "https://govthealth.cg.gov.in/sna/dkbssyapipool/api/UserRgistration/GetUserDetailsByAyushmanCardNo"; - @Override - public Object getBeneficiaryByAbha(AbhaRequestDTO request) { - List health = beneficiaryRepo.getBenHealthDetails(request.getCardNo()); - Map response = new HashMap<>(); + @Value("${govthealth.user.details.url}") + private String getUserDetailsUrl; + + @Value("${govthealth.user.id}") + private String govthealthUserId; - if (health != null && !health.isEmpty()) { - for (Object[] objects : health) { - if (request.getCardNo().equals(String.valueOf(objects[1]))) { + @Value("${govthealth.password}") + private String govthealthPassword; + + @Override + public Object getBeneficiaryByAbha(AbhaRequestDTO request) { + try { + Object[] benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(request.getCardNo()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (request.getCardNo().equals(healthIdNumber)) { + + Map response = new HashMap<>(); response.put("statusCode", 5000); - response.put("message", "This ABHA No already exists"); + response.put("message", + "This ABHA No already exists"); return response; } } - } - AbhaApiResponse abhaApiResponse = getAbhaResponse(request.getCardNo()).getBody(); + AbhaApiResponse abhaApiResponse = + getAbhaResponse(request.getCardNo()).getBody(); + + if (abhaApiResponse == null || abhaApiResponse.getData() == null) { - if (abhaApiResponse != null && abhaApiResponse.getData() != null) { + Map response = new HashMap<>(); + response.put("statusCode", 5001); + response.put("message", "No data found"); + + return response; + } for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { + // Check if ABHA already exists in system + benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(dto.getAbhaId()); + if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { + Object[] healthData = (Object[]) benHealthIdNumber[0]; + String healthIdNumber = healthData[0] != null ? healthData[0].toString() : null; + String healthId = healthData[1] != null ? healthData[1].toString() : null; + logger.info("healthIdNumber:"+healthIdNumber); + logger.info("healthId:"+healthId); + if (dto.getAbhaId().equals(healthIdNumber)) { + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "This ABHA No already exists"); + + return response; + } + } + + + // Split name into firstName and lastName String personName = dto.getPersonName(); - if (personName != null && !personName.trim().isEmpty()) { + if (personName != null + && !personName.trim().isEmpty()) { - String[] names = personName.trim().split("\\s+", 2); + String[] names = + personName.trim().split("\\s+", 2); dto.setFirstName(names[0]); @@ -64,20 +114,33 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { } } } - } - System.out.println("Status = " + abhaApiResponse.getStatusCode()); - System.out.println("Body = " + abhaApiResponse); + logger.info("ABHA Response Status : {}", + abhaApiResponse.getStatusCode()); + + logger.info("ABHA Response : {}", + new Gson().toJson(abhaApiResponse)); - return abhaApiResponse; + return abhaApiResponse; + + } catch (Exception e) { + + logger.error("Error while fetching beneficiary by ABHA", e); + + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", "Internal Server Error"); + + return response; + } } public ResponseEntity getAbhaResponse(String requestId) { RestTemplate restTemplate = new RestTemplate(); Map body = new HashMap<>(); - body.put("userId", "*"); - body.put("password", "*"); + body.put("userId",govthealthUserId); + body.put("password", govthealthPassword); body.put("cardNo", requestId); HttpHeaders headers = new HttpHeaders(); @@ -86,7 +149,7 @@ public ResponseEntity getAbhaResponse(String requestId) { HttpEntity request = new HttpEntity<>(body, headers); ResponseEntity response = restTemplate.exchange( - url, + getUserDetailsUrl, HttpMethod.POST, request, AbhaApiResponse.class From acc2e137c38454d6f895dbffad014ed0befd5d06 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 19 Jun 2026 20:54:08 +0530 Subject: [PATCH 380/450] feature of abha check in our system --- .../flw/controller/ChildCareController.java | 131 ++++++++++++------ 1 file changed, 85 insertions(+), 46 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/ChildCareController.java b/src/main/java/com/iemr/flw/controller/ChildCareController.java index cdba8704b..eeb853c6c 100644 --- a/src/main/java/com/iemr/flw/controller/ChildCareController.java +++ b/src/main/java/com/iemr/flw/controller/ChildCareController.java @@ -7,14 +7,19 @@ 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.domain.iemr.UserServiceRole; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; +import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.ChildCareService; +import com.iemr.flw.service.UserService; +import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.response.OutputResponse; import io.swagger.v3.oas.annotations.Operation; import jakarta.mail.Multipart; +import org.checkerframework.checker.units.qual.A; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -37,6 +42,14 @@ public class ChildCareController { @Autowired private ChildCareService childCareService; + @Autowired + private UserService userService; + + @Autowired + private JwtUtil jwtUtil; + + @Autowired + private UserServiceRoleRepo userServiceRoleRepo; @Operation(summary = "save HBYC details") @RequestMapping(value = {"/hbycVisit/saveAll"}, method = {RequestMethod.POST}) public String saveHbycRecords(@RequestBody List hbycDTOs, @@ -92,25 +105,27 @@ public String getHbycRecords(@RequestBody GetBenRequestHandler requestDTO) { @PostMapping("/hbncVisit/saveAll") public String saveHBNCVisit(@RequestBody List hbncRequestDTOs, - @RequestHeader(value = "Authorization") String Authorization) { + @RequestHeader(value = "jwtToken") String jwtToken) { OutputResponse response = new OutputResponse(); try { if (!hbncRequestDTOs.isEmpty()) { logger.info("Saving HBNC details at: " + new Timestamp(System.currentTimeMillis())); + if(jwtToken!=null){ + String result = childCareService.saveHBNCDetails(hbncRequestDTOs,jwtUtil.extractUserId(jwtToken)); // <-- actual save - String result = childCareService.saveHBNCDetails(hbncRequestDTOs); // <-- actual save + if (result != null) + response.setResponse(result); + else + response.setError(500, "Failed to save HBNC visit data."); + } - if (result != null) - response.setResponse(result); - else - response.setError(500, "Failed to save HBNC visit data."); } else { response.setError(400, "Empty request list."); } } catch (Exception e) { logger.error("Error saving HBNC visit: ", e); - response.setError(500, "Server error: " + e.getMessage()); + response.setError(5000, "Server error: " + e.getMessage()); } return response.toString(); } @@ -146,7 +161,7 @@ public ResponseEntity>> getHBNCVisit } catch (Exception e) { logger.error("Exception in fetching HBNC visits", e); - response.setStatusCode(500); + response.setStatusCode(5000); response.setStatus("Failed"); response.setErrorMessage("Internal Server Error: " + e.getMessage()); response.setData(null); @@ -228,7 +243,7 @@ public String getChildVaccinationDetails(@RequestParam(value = "category") Strin return response.toString(); } @RequestMapping(value = {"/sam/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List samRequest) { + public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List samRequest,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("SAM Request: {}", samRequest); @@ -240,21 +255,30 @@ public ResponseEntity saveSevereAcuteMalnutrition(@RequestBody List s } - 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); + if(token!=null){ + Integer userId = jwtUtil.extractUserId(token); + String userName = userService.getUserDetail(userId).getUserName(); + String responseObject = childCareService.saveSamDetails(samRequest,userId,userName); + + 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); + } + }else { + response.put("statusCode", HttpStatus.UNAUTHORIZED.value()); + response.put("message", "Invalid token"); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response); } + } catch (Exception e) { logger.error("Error saving SAM details:", e); - response.put("statusCode", 5000); + response.put("statusCode",5000); response.put("errorMessage", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); } @@ -272,9 +296,9 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques response.put("data", responseObject); return ResponseEntity.ok(response); } else { - response.put("statusCode", 5000); + response.put("statusCode", HttpStatus.OK.value()); response.put("message", "No SAM records found"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.status(HttpStatus.NO_CONTENT).body(response); } } catch (Exception e) { @@ -287,7 +311,7 @@ public ResponseEntity getAllSevereAcuteMalnutrition(@RequestBody GetBenReques @RequestMapping(value = {"/ors/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveOrsDistribution(@RequestBody List orsDistributionDTOS) { + public ResponseEntity saveOrsDistribution(@RequestBody List orsDistributionDTOS,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("ORS Request: {}", orsDistributionDTOS); @@ -297,18 +321,26 @@ public ResponseEntity saveOrsDistribution(@RequestBody List getAllOrDistribution(@RequestBody GetBenRequestHandler @RequestMapping(value = {"/ifa/saveAll"}, method = RequestMethod.POST) - public ResponseEntity saveIfDistribution(@RequestBody List ifaDistributionDTOS) { + public ResponseEntity saveIfDistribution(@RequestBody List ifaDistributionDTOS,@RequestHeader(value = "JwtToken") String token) { Map response = new LinkedHashMap<>(); logger.info("IFA Request: {}", ifaDistributionDTOS); @@ -356,18 +388,25 @@ public ResponseEntity saveIfDistribution(@RequestBody List responseObject = childCareService.saveAllIfa(ifaDistributionDTOS,userId); + + 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); + } + }else { + response.put("statusCode", HttpStatus.UNAUTHORIZED.value()); + response.put("message", "Invalid token"); + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).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); From c796f5e62be2426ae3d6b61c7895b4c95e380c13 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 15:36:00 +0530 Subject: [PATCH 381/450] hbyc issue fixed --- .../iemr/flw/service/impl/ChildCareServiceImpl.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) 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 bf66dd735..8fdfa7259 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; import com.iemr.flw.domain.iemr.*; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.*; @@ -107,14 +108,11 @@ public String registerHBYC(List hbycDTOs) { if (hbyc != null) { Long id = hbyc.getId(); - modelMapper.map(it, hbycDTO); hbyc.setId(id); hbyc.setUserId(userRepo.getUserIdByName(it.getUserName())); hbyc.setCreated_by(it.getUserName()); } else { 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()); @@ -151,14 +149,18 @@ public String registerHBYC(List hbycDTOs) { hbyc.setMcp_card_images(hbycDTO.getMcp_card_images()); } + logger.info("Saving HBYC Data : {}", new Gson().toJson(hbyc)); + hbycList.add(hbyc); }); hbycRepo.saveAll(hbycList); + logger.info("Total records to save : {}", hbycList.size()); checkAndAddHbyncIncentives(hbycList); return "no of hbyc details saved: " + hbycDTOs.size(); } catch (Exception e) { - logger.info("error while saving hbyc details: " + e.getMessage()); + logger.error("error while saving hbyc details", e); + } return null; } From c793b6fd6058f2d2cf5211ecd8c2ee2e699525d2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 15:43:41 +0530 Subject: [PATCH 382/450] hbyc issue fixed --- .../flw/service/impl/ChildCareServiceImpl.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) 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 8fdfa7259..0a4d5f353 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -293,11 +293,17 @@ private String convert(Boolean value) { } private Boolean convertBollen(String value) { - if (value.equals("Yes")) { - return true; - } else { - return false; + if(value!=null || !value.isEmpty()){ + if (value.equals("Yes")) { + return true; + } else { + return false; + } + }else { + return false; + } + } private String convert(Object value) { From a3ee21de782f4fa5c8c9483c28de531f56acb879 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 15:51:39 +0530 Subject: [PATCH 383/450] hbyc issue fixed --- .../flw/service/impl/ChildCareServiceImpl.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) 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 0a4d5f353..6a3390729 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -100,6 +100,8 @@ public String registerHBYC(List hbycDTOs) { try { List hbycList = new ArrayList<>(); + logger.info("Saving HBYC Data : {}", new Gson().toJson(hbycDTOs)); + hbycDTOs.forEach(it -> { HbycDTO hbycDTO = it.getFields(); hbycDTO.setVisit_date(it.getVisitDate()); @@ -293,17 +295,11 @@ private String convert(Boolean value) { } private Boolean convertBollen(String value) { - if(value!=null || !value.isEmpty()){ - if (value.equals("Yes")) { - return true; - } else { - return false; - } - }else { - return false; - + if (value != null && !value.isEmpty()) { + return value.equalsIgnoreCase("Yes"); + } else { + return false; } - } private String convert(Object value) { From 0845d436378bff890400ef9bec565ff3a3422b12 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 16:19:55 +0530 Subject: [PATCH 384/450] hbyc issue fixed --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 6a3390729..f11e52146 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -100,7 +100,6 @@ public String registerHBYC(List hbycDTOs) { try { List hbycList = new ArrayList<>(); - logger.info("Saving HBYC Data : {}", new Gson().toJson(hbycDTOs)); hbycDTOs.forEach(it -> { HbycDTO hbycDTO = it.getFields(); From 8c072a2d2094a1c68fff10d84cda8e5e9c22d41b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 16:25:30 +0530 Subject: [PATCH 385/450] hbyc issue fixed --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 f11e52146..65bd1d6b8 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -150,7 +150,6 @@ public String registerHBYC(List hbycDTOs) { hbyc.setMcp_card_images(hbycDTO.getMcp_card_images()); } - logger.info("Saving HBYC Data : {}", new Gson().toJson(hbyc)); hbycList.add(hbyc); }); From a9d8c4896aafcef14bdf878bb772e541a85e3213 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 22 Jun 2026 18:25:52 +0530 Subject: [PATCH 386/450] hbyc issue fixed --- .../identity/RMNCHMBeneficiarydetail.java | 4 +++ .../com/iemr/flw/dto/iemr/AbhaRequestDTO.java | 1 + .../impl/AbhaBeneficiaryServiceImpl.java | 30 ++++++++++++++++++- 3 files changed, 34 insertions(+), 1 deletion(-) 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 72e994f5b..779a09da4 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java @@ -186,4 +186,8 @@ public class RMNCHMBeneficiarydetail { @Transient private Integer ProviderServiceMapID; + @Expose + @Column(name = "familyid") + private String familyId; + } diff --git a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java index 0dba46d51..9ec31c6fd 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/AbhaRequestDTO.java @@ -5,5 +5,6 @@ @Data public class AbhaRequestDTO { private String cardNo; + private Long houseHoldId; } diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 245b12e2f..f62681389 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -6,6 +6,7 @@ import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; import com.iemr.flw.dto.iemr.AbhaRequestDTO; import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.identity.HouseHoldRepo; import com.iemr.flw.service.AbhaBeneficiaryService; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -15,6 +16,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -40,10 +42,22 @@ public class AbhaBeneficiaryServiceImpl implements AbhaBeneficiaryService { @Value("${govthealth.password}") private String govthealthPassword; + @Autowired + private HouseHoldRepo houseHoldRepo; + @Override public Object getBeneficiaryByAbha(AbhaRequestDTO request) { try { + Long benRedId = null; + BigInteger benDetailsdId = null; + String familyId =null; + if(request.getHouseHoldId()!=null){ + benRedId = houseHoldRepo.getByHouseHoldID(request.getHouseHoldId()).get(0).getBenRegId(); + benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); + familyId = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailsdId).getFamilyId(); + } + Object[] benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(request.getCardNo()); if (benHealthIdNumber != null && benHealthIdNumber.length > 0) { Object[] healthData = (Object[]) benHealthIdNumber[0]; @@ -74,6 +88,7 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { return response; } + for (AbhaBeneficiaryDTO dto : abhaApiResponse.getData()) { // Check if ABHA already exists in system @@ -89,13 +104,25 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { Map response = new HashMap<>(); response.put("statusCode", 5000); response.put("message", - "This ABHA No already exists"); + "Beneficiary is already exists"); + + return response; + } + } + if(familyId!=null){ + if(!dto.getFamilyid().toString().equals(familyId)){ + Map response = new HashMap<>(); + response.put("statusCode", 5000); + response.put("message", + "Beneficiary is not associated with this family."); return response; } } + + // Split name into firstName and lastName String personName = dto.getPersonName(); @@ -115,6 +142,7 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { } } + logger.info("ABHA Response Status : {}", abhaApiResponse.getStatusCode()); From 47076974eabbfc516d5657277f987bfeab23b6cd Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 23 Jun 2026 12:47:31 +0530 Subject: [PATCH 387/450] fix internal server error on abha id --- .../flw/service/impl/AbhaBeneficiaryServiceImpl.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index f62681389..5cfd6e7a5 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -54,8 +54,14 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { String familyId =null; if(request.getHouseHoldId()!=null){ benRedId = houseHoldRepo.getByHouseHoldID(request.getHouseHoldId()).get(0).getBenRegId(); - benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); - familyId = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailsdId).getFamilyId(); + if(benRedId!=null){ + benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); + + } + if(benDetailsdId!=null){ + familyId = beneficiaryRepo.findByBeneficiaryDetailsId(benDetailsdId).getFamilyId(); + + } } Object[] benHealthIdNumber = beneficiaryRepo.getHealthIdNumber(request.getCardNo()); From 79a1ab44ada59495fc461dbee589c2383b234f0d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 23 Jun 2026 13:23:43 +0530 Subject: [PATCH 388/450] fix internal server error on abha id --- .../impl/MaternalHealthServiceImpl.java | 3 +- .../impl/VillageLevelFormServiceImpl.java | 72 +++++++++++++++---- 2 files changed, 59 insertions(+), 16 deletions(-) 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 2cb4fca00..3813df546 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -142,12 +142,11 @@ public List getANCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List ancVisits = ancVisitRepo.getANCForPW(user, dto.getFromDate(), dto.getToDate()); - checkAndAddIncentives(ancVisits, dto.getAshaId()); return ancVisits.stream() .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error(e.getMessage()); + logger.error("ANC VISIT :---------------------"+e.getMessage()); } return null; } diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 7bc3c701c..4519bc623 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -226,20 +226,64 @@ 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.setImage2(vhndFormDTO.getImage2() != null ? vhndFormDTO.getImage2() : ""); + vhndForm.setImage1(vhndFormDTO.getImage1() != null ? vhndFormDTO.getImage1() : ""); + vhndForm.setPlace(vhndFormDTO.getPlace() != null ? vhndFormDTO.getPlace() : ""); + + vhndForm.setNoOfBeneficiariesAttended( + vhndFormDTO.getNoOfBeneficiariesAttended() != null + ? vhndFormDTO.getNoOfBeneficiariesAttended() + : 0); + + vhndForm.setPregnantWomenAnc( + vhndFormDTO.getPregnantWomenAnc() != null + ? vhndFormDTO.getPregnantWomenAnc() + : null); + + vhndForm.setLactatingMothersPnc( + vhndFormDTO.getLactatingMothersPnc() != null + ? vhndFormDTO.getLactatingMothersPnc() + : null); + + vhndForm.setChildrenImmunization( + vhndFormDTO.getChildrenImmunization() != null + ? vhndFormDTO.getChildrenImmunization() + : null); + + vhndForm.setSelectAllEducation( + vhndFormDTO.getSelectAllEducation() != null + ? vhndFormDTO.getSelectAllEducation() + : false); + + vhndForm.setKnowledgeBalancedDiet( + vhndFormDTO.getKnowledgeBalancedDiet() != null + ? vhndFormDTO.getKnowledgeBalancedDiet() + : null); + + vhndForm.setCareDuringPregnancy( + vhndFormDTO.getCareDuringPregnancy() != null + ? vhndFormDTO.getCareDuringPregnancy() + : null); + + vhndForm.setImportanceBreastfeeding( + vhndFormDTO.getImportanceBreastfeeding() != null + ? vhndFormDTO.getImportanceBreastfeeding() + : null); + + vhndForm.setComplementaryFeeding( + vhndFormDTO.getComplementaryFeeding() != null + ? vhndFormDTO.getComplementaryFeeding() + : null); + + vhndForm.setHygieneSanitation( + vhndFormDTO.getHygieneSanitation() != null + ? vhndFormDTO.getHygieneSanitation() + : null); + + vhndForm.setFamilyPlanningHealthcare( + vhndFormDTO.getFamilyPlanningHealthcare() != null + ? vhndFormDTO.getFamilyPlanningHealthcare() + : null); vhndForm.setFormType("VHND"); vhndRepo.save(vhndForm); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); From 61879ad1583d7a1b2b184507328c533de039097f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Tue, 23 Jun 2026 14:01:44 +0530 Subject: [PATCH 389/450] fix internal server error on abha id --- .../com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 5cfd6e7a5..15ca0e7cc 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -53,7 +53,7 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { BigInteger benDetailsdId = null; String familyId =null; if(request.getHouseHoldId()!=null){ - benRedId = houseHoldRepo.getByHouseHoldID(request.getHouseHoldId()).get(0).getBenRegId(); + benRedId = beneficiaryRepo.findByHouseoldId(request.getHouseHoldId()).get(0).getBenRegId(); if(benRedId!=null){ benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); From f437aeafe199c7e7068000b07dc1829952242bac Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 14:14:53 +0530 Subject: [PATCH 390/450] fix internal server error on abha id --- .../com/iemr/flw/controller/BeneficiaryController.java | 8 ++++---- .../java/com/iemr/flw/repo/identity/BeneficiaryRepo.java | 2 +- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 4 +++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index ee5730959..ba8958dcc 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -97,7 +97,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List 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); + return ResponseEntity.status(5000).body(response); } } @@ -117,14 +117,14 @@ public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler requ } else { response.put("statusCode", 5000); response.put("message", "No records found"); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + return ResponseEntity.status(5000).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); + return ResponseEntity.status(5000).body(response); } } @@ -186,7 +186,7 @@ public ResponseEntity saveIfaFormData( response.put("errorMessage", e.getMessage()); return ResponseEntity - .status(HttpStatus.INTERNAL_SERVER_ERROR) + .status(5000) .body(response); } } 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 b3988c3eb..dae1ad01b 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -75,7 +75,7 @@ Page getBenDataWithinDates( List getDetailsByRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBornBirthDetails t WHERE t.BenRegId =:benRegID ") - RMNCHBornBirthDetails getBornBirthByRegID(@Param("benRegID") Long benRegID); + List getBornBirthByRegID(@Param("benRegID") Long benRegID); @Query(" SELECT t.benRegId FROM RMNCHMBeneficiaryregidmapping t WHERE t.beneficiaryID = :benID ") Long getRegIDFromBenId(@Param("benID") Long benID); 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 d29fbab8b..2b663f207 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -217,8 +217,10 @@ private String getMappingsForAddressIDs(List addressLi .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); } + if(!beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()).isEmpty()){ + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()).get(0); - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); + } if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) if(!houseHoldRepo From 9022165967191333d89e81bac0d383775fce5435 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 15:23:21 +0530 Subject: [PATCH 391/450] fix internal server error on abha id --- .../iemr/flw/controller/BeneficiaryController.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java index ba8958dcc..d439fbf5d 100644 --- a/src/main/java/com/iemr/flw/controller/BeneficiaryController.java +++ b/src/main/java/com/iemr/flw/controller/BeneficiaryController.java @@ -97,7 +97,7 @@ public ResponseEntity saveEyeSurgery(@RequestBody List logger.error("Error saving eye checkup visit:", e); response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity.status(5000).body(response); + return ResponseEntity.ok(response); } } @@ -117,14 +117,14 @@ public ResponseEntity getAllEyeSurgery(@RequestBody GetBenRequestHandler requ } else { response.put("statusCode", 5000); response.put("message", "No records found"); - return ResponseEntity.status(5000).body(response); + return ResponseEntity.ok(response); } } catch (Exception e) { logger.error("Error fetching eye checkup visit:", e); response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity.status(5000).body(response); + return ResponseEntity.ok(response); } } @@ -185,9 +185,8 @@ public ResponseEntity saveIfaFormData( response.put("statusCode", 5000); response.put("errorMessage", e.getMessage()); - return ResponseEntity - .status(5000) - .body(response); + return ResponseEntity.ok(response); + } } From 8e479f5169e4836270fa28f2caecf78aff361a7e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 15:29:29 +0530 Subject: [PATCH 392/450] fix internal server error on abha id --- src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java | 2 +- .../com/iemr/flw/service/impl/BeneficiaryServiceImpl.java | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) 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 dae1ad01b..b3988c3eb 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -75,7 +75,7 @@ Page getBenDataWithinDates( List getDetailsByRegID(@Param("benRegID") Long benRegID); @Query(value = " SELECT t FROM RMNCHBornBirthDetails t WHERE t.BenRegId =:benRegID ") - List getBornBirthByRegID(@Param("benRegID") Long benRegID); + RMNCHBornBirthDetails getBornBirthByRegID(@Param("benRegID") Long benRegID); @Query(" SELECT t.benRegId FROM RMNCHMBeneficiaryregidmapping t WHERE t.beneficiaryID = :benID ") Long getRegIDFromBenId(@Param("benID") Long benID); 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 2b663f207..23c4bd602 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -217,10 +217,8 @@ private String getMappingsForAddressIDs(List addressLi .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); } - if(!beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()).isEmpty()){ - benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()).get(0); + benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); - } if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) if(!houseHoldRepo From 45e97b533908b27cc0749ee01e0974d627e16081 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 16:03:01 +0530 Subject: [PATCH 393/450] fix sam get api issue --- .../com/iemr/flw/service/impl/ChildCareServiceImpl.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 2a37d7b7b..aa45f30da 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -553,8 +553,10 @@ public List getSamVisitsByBeneficiary(GetBenRequestHandler reque // ✅ Final Visit Label dto.setVisitLabel("Visit-" + visitNo); - - dto.setMuac(Double.parseDouble(entity.getMuac())); + String muacVal = entity.getMuac(); + dto.setMuac((muacVal != null && !muacVal.trim().isEmpty()) + ? Double.parseDouble(muacVal.trim()) + : 0.0); dto.setWeightForHeightStatus(entity.getWeightForHeightStatus()); dto.setIsChildReferredNrc(entity.getIsChildReferredNrc()); dto.setIsChildAdmittedNrc(entity.getIsChildAdmittedNrc()); From a57491f2876d06d4dacf6d22e53b60651eda6a99 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 17:08:36 +0530 Subject: [PATCH 394/450] fix date of referral issue --- .../iemr/flw/service/impl/MalariaFollowUpServiceImpl.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index 7ae86c7b3..f5ef4a092 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -47,11 +47,6 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) return false; } - if (dto.getReferralDate() != null && - dto.getReferralDate().before(dto.getTreatmentStartDate())) { - return false; - } - dto.setUserId(jwtUtil.extractUserId(token)); MalariaFollowUp entity = new MalariaFollowUp(); From 7dc0bf78325e94cf87c7534ece05ed337c36dfc1 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 17:41:07 +0530 Subject: [PATCH 395/450] fix date of referral issue --- .../iemr/flw/repo/iemr/ChildRegisterRepo.java | 2 +- .../flw/service/impl/ChildServiceImpl.java | 96 ++++++------------- 2 files changed, 28 insertions(+), 70 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java index 499d7a5c9..f456428b3 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildRegisterRepo.java @@ -21,5 +21,5 @@ List getChildDetailsForUser(@Param("userId") String userId, Long countByBenId(Long benId); - List findByBenIdOrderByCreatedDateAsc(Long benId); + List findByBenId(Long benId); } diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index a641a2eff..1efd04e6c 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -92,46 +92,26 @@ public String save(List childRegisterDTOs) throws Exception { public void processFirstChildIncentive(ChildRegister childRegister) { Long benId = childRegister.getBenId(); - logger.info("BenId:"+benId); - - RMNCHBeneficiaryDetailsRmnch beneficiary = - beneficiaryRepo.findByBenficieryid(benId).orElse(null); - - logger.info("Child ben Id:" + beneficiary.getBenficieryid()); - - if (beneficiary == null || beneficiary.getDateMarriage() == null) { - return; - } // First child validation - Long childCount = childRepo.countByBenId(benId); + List childCount = childRepo.findByBenId(benId); - if (childCount != 1) { - return; - } + if(!childCount.isEmpty()){ + if(childCount.size()==1){ + Integer userId = + userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); - Timestamp marriageDate = beneficiary.getDateMarriage(); + incentiveLogicService.incentiveForChildBirthGap( + benId, + childRegister.getCreatedDate(), + childRegister.getCreatedDate(), + userId + ); + } + } - // Temporary: using createdDate as child DOB - Timestamp childBirthDate = childRegister.getCreatedDate(); - long diffMillis = childBirthDate.getTime() - marriageDate.getTime(); - long days = diffMillis / (1000 * 60 * 60 * 24); - - // >= 2 years - if (days >= 730) { - - Integer userId = - userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); - - incentiveLogicService.incentiveForChildBirthGap( - benId, - childBirthDate, - childBirthDate, - userId - ); - } } private void processSecondChildGapIncentive(ChildRegister currentChild) { @@ -139,48 +119,26 @@ private void processSecondChildGapIncentive(ChildRegister currentChild) { Long benId = currentChild.getBenId(); // Total children count - Long childCount = childRepo.countByBenId(benId); + List childCount = childRepo.findByBenId(benId); // Applicable only for second child - if (childCount != 2) { - return; - } - - List children = - childRepo.findByBenIdOrderByCreatedDateAsc(benId); - - if (children.size() < 2) { - return; - } - - // First child - ChildRegister firstChild = children.get(0); - // Second child - ChildRegister secondChild = children.get(1); + if(!childCount.isEmpty()){ + if(childCount.size()==2){ + Integer userId = + userServiceRoleRepo.getUserIdByName( + currentChild.getCreatedBy()); - Timestamp firstChildDob = firstChild.getCreatedDate(); + incentiveLogicService.incentiveForSecondChildGap( + benId, + currentChild.getCreatedDate(), + currentChild.getCreatedDate(), + userId + ); + } + } - Timestamp secondChildDob = secondChild.getCreatedDate(); - long diffMillis = - secondChildDob.getTime() - firstChildDob.getTime(); - long days = diffMillis / (1000 * 60 * 60 * 24); - - // >= 3 years - if (days >= 1095) { - - Integer userId = - userServiceRoleRepo.getUserIdByName( - currentChild.getCreatedBy()); - - incentiveLogicService.incentiveForSecondChildGap( - benId, - secondChildDob, - secondChildDob, - userId - ); - } } } From 1c51a78cc3a2bd46dab7f3923ae67d46f9d62598 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 17:48:24 +0530 Subject: [PATCH 396/450] fix date of referral issue --- .../java/com/iemr/flw/service/impl/ChildServiceImpl.java | 8 ++++++-- .../java/com/iemr/flw/service/impl/CoupleServiceImpl.java | 4 ---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java index 1efd04e6c..32c6d76ac 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildServiceImpl.java @@ -92,12 +92,16 @@ public String save(List childRegisterDTOs) throws Exception { public void processFirstChildIncentive(ChildRegister childRegister) { Long benId = childRegister.getBenId(); + logger.info("Child register {}"+childRegister.getBenId()); // First child validation List childCount = childRepo.findByBenId(benId); - if(!childCount.isEmpty()){ - if(childCount.size()==1){ + + if(!childCount.isEmpty()){ + logger.info("Child register {}"+childCount.size()); + + if(childCount.size()==1){ Integer userId = userServiceRoleRepo.getUserIdByName(childRegister.getCreatedBy()); 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 b78effe95..4fb218b98 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -427,10 +427,6 @@ public List getEligibleCoupleTracking(GetBenRequestHa List eligibleCoupleTrackingList = eligibleCoupleTrackingRepo.getECTrackRecords(user, dto.getFromDate(), dto.getToDate()); - eligibleCoupleTrackingList.forEach(eligibleCoupleTracking -> { - checkAndAddAntaraIncentive(recordList, eligibleCoupleTracking); - - }); recordRepo.saveAll(recordList); From 7357d0ef971afb8e2ae8aae09fde36d10f180555 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 24 Jun 2026 18:43:33 +0530 Subject: [PATCH 397/450] fix date of referral issue --- .../com/iemr/flw/service/impl/DiseaseControlServiceImpl.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 42a1af072..feb02d9ef 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1300,7 +1300,6 @@ public List getAllMosquitoMobilizationNet(Integer userId) { mosquitoNetListDTO.setVisit_date(entity.getVisitDate().format(formatter)); dto.setFields(mosquitoNetListDTO); - checkAndAddIncentives(entity); return dto; @@ -1365,12 +1364,11 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNe Timestamp visitTimestamp = Timestamp.valueOf(diseaseScreening.getVisitDate().atStartOfDay()); - IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId( diseaseScreeningActivity.getId(), visitTimestamp, - diseaseScreening.getBeneficiaryId().longValue()); + diseaseScreening.getBeneficiaryId()); if (record == null) { @@ -1390,6 +1388,7 @@ record = new IncentiveActivityRecord(); recordRepo.save(record); } + } From d1cab7831e1c5dd23d0a5428cf6383a0ea1ded5b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 11:34:55 +0530 Subject: [PATCH 398/450] fix hwc referral incentive issue --- .../flw/domain/iemr/MosquitoNetEntity.java | 5 +- .../flw/repo/iemr/BenReferDetailsRepo.java | 13 ++++ .../service/impl/IncentiveServiceImpl.java | 62 ++++++++++++++++++- 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java b/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java index 9444d1af6..1f57d23ae 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MosquitoNetEntity.java @@ -9,21 +9,22 @@ @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; diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java index f2c915f45..4ef076c22 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java @@ -46,4 +46,17 @@ public interface BenReferDetailsRepo extends JpaRepository findByCreatedBy(String userName); + + @Query(""" + SELECT COUNT(b) + FROM BenReferDetails b + WHERE b.createdBy = :userName + AND FUNCTION('MONTH', b.createdDate) = :month + AND FUNCTION('YEAR', b.createdDate) = :year + """) + Long countMonthlyReferrals( + @Param("userName") String userName, + @Param("month") Integer month, + @Param("year") Integer year); + } 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 55e04af99..459c9f697 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -550,11 +550,13 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { Map activityMap = incentivesRepo.findIncentiveMasterByNameAndGroup( - List.of("NCD_POP_ENUMERATION", "NCD_FOLLOWUP_TREATMENT"), groupName + List.of("NCD_POP_ENUMERATION", "HWC_REFERRAL_10_CASES"), groupName ).stream().collect(Collectors.toMap(IncentiveActivity::getName, Function.identity())); IncentiveActivity ncdPopEnumeration = activityMap.get("NCD_POP_ENUMERATION"); + IncentiveActivity hwcReferralEnumeration = activityMap.get("HWC_REFERRAL_10_CASES"); + CompletableFuture> benReferFuture = CompletableFuture.supplyAsync(() -> benReferDetailsRepo.findByCreatedBy(userName)); CompletableFuture> cbacFuture = @@ -589,6 +591,25 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { }); } + if (hwcReferralEnumeration != null) { + + LocalDate now = LocalDate.now(); + + Long referralCount = benReferDetailsRepo.countMonthlyReferrals( + userName, + now.getMonthValue(), + now.getYear()); + + if (referralCount >= 10) { + + addHwcReferalAshaIncentiveRecord( + hwcReferralEnumeration, + ashaId, + userName + ); + } + } + // ---- Single batch insert instead of N individual saves ---- if (!recordsToSave.isEmpty()) { recordRepo.saveAll(recordsToSave); @@ -717,6 +738,45 @@ record = new IncentiveActivityRecord(); } + private void addHwcReferalAshaIncentiveRecord(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.setIsEligible(true); + record.setIsDefaultActivity(false); + record.setAmount(Long.valueOf(incentiveActivity.getRate())); + recordRepo.save(record); + } + } catch (Exception e) { + logger.error("Error in addMonthlyAshaIncentiveRecord", e); + + } + + } + private void addIncentiveForIronTablets(Integer userId) { IncentiveActivity incentiveActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.CHILD_HEALTH.getDisplayName()); IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NATIONAL_IRON_PLUS", GroupName.ACTIVITY.getDisplayName()); From ebc7b980cd2be2ad8ebff24972e4a142204e1b62 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 11:41:53 +0530 Subject: [PATCH 399/450] fix hwc referral incentive issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 459c9f697..69bc729f0 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -592,7 +592,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { } if (hwcReferralEnumeration != null) { - + logger.info("hwcReferralEnumeration :"+hwcReferralEnumeration.getDescription()); LocalDate now = LocalDate.now(); Long referralCount = benReferDetailsRepo.countMonthlyReferrals( @@ -600,6 +600,9 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { now.getMonthValue(), now.getYear()); + logger.info("referralCount :"+referralCount); + + if (referralCount >= 10) { addHwcReferalAshaIncentiveRecord( From ec3e6aeb824409fc9a8ebfe56d08b37e61c43992 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 11:50:35 +0530 Subject: [PATCH 400/450] fix hwc referral incentive issue --- .../iemr/flw/repo/iemr/BenReferDetailsRepo.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java index 4ef076c22..9cb356626 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/BenReferDetailsRepo.java @@ -47,13 +47,13 @@ public interface BenReferDetailsRepo extends JpaRepository findByCreatedBy(String userName); - @Query(""" - SELECT COUNT(b) - FROM BenReferDetails b - WHERE b.createdBy = :userName - AND FUNCTION('MONTH', b.createdDate) = :month - AND FUNCTION('YEAR', b.createdDate) = :year - """) + @Query(value = """ + SELECT COUNT(*) + FROM db_iemr.t_benreferdetails + WHERE CreatedBy = :userName + AND MONTH(CreatedDate) = :month + AND YEAR(CreatedDate) = :year + """, nativeQuery = true) Long countMonthlyReferrals( @Param("userName") String userName, @Param("month") Integer month, From 7e4ebc308c44f6544bff32067445be71f723f6d4 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 12:09:58 +0530 Subject: [PATCH 401/450] fix hwc referral incentive issue --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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 69bc729f0..f85e47f6e 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -593,6 +593,8 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { if (hwcReferralEnumeration != null) { logger.info("hwcReferralEnumeration :"+hwcReferralEnumeration.getDescription()); + logger.info("userName={}", userName); + LocalDate now = LocalDate.now(); Long referralCount = benReferDetailsRepo.countMonthlyReferrals( From 4e1e1b861cabe8809c5e3c48d16f63257cb4f2e9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 12:11:33 +0530 Subject: [PATCH 402/450] fix hwc referral incentive issue --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 aa45f30da..91cad2e06 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -241,7 +241,10 @@ public List getHBNCDetails(GetBenRequestHandler dto) { // Convert all fields to Map Map fields = new HashMap<>(); - addIfValid(fields, "visit_day", visit.getVisit_day()); + if(visit.getVisit_day()!=null){ + 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()); From 73918cf659c293c5c341649f92211a3e8a1d274f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 12:34:56 +0530 Subject: [PATCH 403/450] Incentive logic for first-year child Immunization --- .../flw/repo/iemr/ChildVaccinationRepo.java | 24 ++++++++++++++++--- .../service/impl/ChildCareServiceImpl.java | 4 ++-- 2 files changed, 23 insertions(+), 5 deletions(-) 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 9ed0943c7..78d1e6dcd 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java @@ -18,9 +18,15 @@ List getChildVaccinationDetails(@Param("userId") String userId ChildVaccination findChildVaccinationByBeneficiaryRegIdAndCreatedDateAndVaccineName(Long benRegId, Timestamp createdDate, String vaccine); - @Query(value = "select count(*) from db_iemr.t_childvaccinedetail1 cv left outer join db_iemr.m_immunizationservicevaccination v on " + - "cv.VaccineName = v.VaccineName where cv.beneficiaryRegId = :benRegId and v.Currentimmunizationserviceid in (1,2,3,4,5) and " + - "v.category = 'CHILD'", nativeQuery = true) + @Query(value = """ + SELECT COUNT(DISTINCT cv.VaccineName) + FROM db_iemr.t_childvaccinedetail1 cv + JOIN db_iemr.m_immunizationservicevaccination v + ON cv.VaccineName = v.VaccineName + WHERE cv.BeneficiaryRegID = :benRegId + AND v.Currentimmunizationserviceid IN (1,2,3,4,5) + AND v.category = 'CHILD' + """, nativeQuery = true) Integer getFirstYearVaccineCountForBenId(@Param("benRegId") Long benRegId); @@ -42,4 +48,16 @@ List getChildVaccinationDetails(@Param("userId") String userId "cv.VaccineName = v.VaccineName where cv.beneficiaryRegId = :benRegId and v.Currentimmunizationserviceid = 8 and v.VaccineName = " + "'DPT Booster-2' and v.category = 'CHILD'), 1, 0);", nativeQuery = true) Integer checkDptVaccinatedUser(@Param("benRegId") Long benRegId); + + @Query(value = """ + SELECT COUNT(DISTINCT cv.VaccineName) + FROM db_iemr.t_childvaccinedetail1 cv + WHERE cv.BeneficiaryRegID = :benRegId + AND cv.VaccineName IN ( + 'DPT Booster-1', + 'Measles & Rubella (MR)-2', + 'OPV Booster' + ) + """, nativeQuery = true) + Integer getEligibleSecondYearVaccines(@Param("benRegId") Long benRegId); } 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 91cad2e06..85887961e 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -985,11 +985,11 @@ private void checkAndAddIncentives(List vaccinationList) { 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()) + if (immunizationActivity2AM != null && childVaccinationRepo.getEligibleSecondYearVaccines(vaccination.getBeneficiaryRegId()) .equals(childVaccinationRepo.getSecondYearVaccineCount())) { createIncentiveRecord(vaccination, benId, userId, immunizationActivity2AM); } - if (immunizationActivity2CH != null && childVaccinationRepo.getSecondYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + if (immunizationActivity2CH != null && childVaccinationRepo.getEligibleSecondYearVaccines(vaccination.getBeneficiaryRegId()) .equals(childVaccinationRepo.getSecondYearVaccineCount())) { createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); } From a95ab7407d4205d7c61e435c79e7f4e618f7646a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 12:43:59 +0530 Subject: [PATCH 404/450] Incentive logic for first-year child Immunization --- .../service/impl/ChildCareServiceImpl.java | 71 ++++++++++++++++--- 1 file changed, 62 insertions(+), 9 deletions(-) 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 85887961e..9a6b5c88d 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -371,6 +371,8 @@ public List getChildVaccinationDetails(GetBenRequestHandler vaccinationDTO.setBeneficiaryId(benId.longValue()); } + checkAndAddIncentives(vaccinationDetails); + result.add(vaccinationDTO); }); @@ -981,17 +983,68 @@ private void checkAndAddIncentives(List vaccinationList) { createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); } } else if (immunizationServiceId == 7) { + IncentiveActivity immunizationActivity2AM = - incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.IMMUNIZATION.getDisplayName()); + incentivesRepo.findIncentiveMasterByNameAndGroup( + "COMPLETE_IMMUNIZATION_1_2", + GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivity2CH = - incentivesRepo.findIncentiveMasterByNameAndGroup("COMPLETE_IMMUNIZATION_1_2", GroupName.ACTIVITY.getDisplayName()); - if (immunizationActivity2AM != null && childVaccinationRepo.getEligibleSecondYearVaccines(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2AM); - } - if (immunizationActivity2CH != null && childVaccinationRepo.getEligibleSecondYearVaccines(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getSecondYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity2CH); + incentivesRepo.findIncentiveMasterByNameAndGroup( + "COMPLETE_IMMUNIZATION_1_2", + GroupName.ACTIVITY.getDisplayName()); + + Integer completedVaccines = + childVaccinationRepo.getEligibleSecondYearVaccines( + vaccination.getBeneficiaryRegId()); + + logger.info( + "COMPLETE_IMMUNIZATION_1_2 :: BeneficiaryRegId={}, Vaccine={}, VaccineId={}, CompletedVaccines={}", + vaccination.getBeneficiaryRegId(), + vaccination.getVaccineName(), + vaccination.getVaccineId(), + completedVaccines + ); + + // Required vaccines count = 3 + if (completedVaccines != null && completedVaccines == 3) { + + logger.info( + "Beneficiary {} completed all required second year vaccines.", + vaccination.getBeneficiaryRegId()); + + if (immunizationActivity2AM != null) { + + logger.info( + "Creating IMMUNIZATION incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); + + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivity2AM); + } + + if (immunizationActivity2CH != null) { + + logger.info( + "Creating ACTIVITY incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); + + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivity2CH); + } + + } else { + + logger.info( + "BeneficiaryRegId={} not eligible. CompletedVaccines={}/3", + vaccination.getBeneficiaryRegId(), + completedVaccines); } } IncentiveActivity immunizationActivity5AM = From 6bc9bb51e208a914ecd5235c56ae434ba8717326 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 13:14:11 +0530 Subject: [PATCH 405/450] Incentive logic for first-year child Immunization --- .../service/impl/ChildCareServiceImpl.java | 89 ++++--- .../flw/service/impl/CoupleServiceImpl.java | 243 ++++++++++-------- .../impl/MaternalHealthServiceImpl.java | 2 +- 3 files changed, 197 insertions(+), 137 deletions(-) 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 9a6b5c88d..7229ac24b 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -371,7 +371,10 @@ public List getChildVaccinationDetails(GetBenRequestHandler vaccinationDTO.setBeneficiaryId(benId.longValue()); } - checkAndAddIncentives(vaccinationDetails); + if(!vaccinationDetails.isEmpty()){ + checkAndAddIncentives(vaccinationDetails); + + } result.add(vaccinationDTO); @@ -406,7 +409,10 @@ public String saveChildVaccinationDetails(List childVaccina vaccinationList.add(vaccination); }); childVaccinationRepo.saveAll(vaccinationList); - checkAndAddIncentives(vaccinationList); + if(!vaccinationList.isEmpty()){ + checkAndAddIncentives(vaccinationList); + + } logger.info("Child Vaccination details saved"); return "No of child vaccination details saved: " + vaccinationList.size(); } catch (Exception e) { @@ -954,8 +960,10 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI private void checkAndAddIncentives(List vaccinationList) { + String createdBy = vaccinationList.get(0).getCreatedBy(); - + Integer userId = userRepo.getUserIdByName(createdBy); + Integer stateId = userService.getUserDetail(userId).getStateId(); vaccinationList.forEach(vaccination -> { Long benId= null; if(vaccination.getBeneficiaryRegId()!=null){ @@ -964,7 +972,6 @@ private void checkAndAddIncentives(List vaccinationList) { benId = benIdObj.longValue(); } - Integer userId = userRepo.getUserIdByName(vaccination.getCreatedBy()); Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); if (immunizationServiceId < 6) { IncentiveActivity immunizationActivityAM = @@ -972,16 +979,20 @@ private void checkAndAddIncentives(List vaccinationList) { 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, immunizationActivityAM); + if(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())){ + if (immunizationActivityAM != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getFirstYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivityAM); + } + } + + if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())){ + if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) + .equals(childVaccinationRepo.getFirstYearVaccineCount())) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + } } - if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); - } } else if (immunizationServiceId == 7) { IncentiveActivity immunizationActivity2AM = @@ -1012,31 +1023,35 @@ private void checkAndAddIncentives(List vaccinationList) { logger.info( "Beneficiary {} completed all required second year vaccines.", vaccination.getBeneficiaryRegId()); + if(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { - if (immunizationActivity2AM != null) { + if (immunizationActivity2AM != null) { - logger.info( - "Creating IMMUNIZATION incentive for BeneficiaryRegId={}", - vaccination.getBeneficiaryRegId()); + logger.info( + "Creating IMMUNIZATION incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); - createIncentiveRecord( - vaccination, - benId, - userId, - immunizationActivity2AM); + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivity2AM); + } } + if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())) { - if (immunizationActivity2CH != null) { + if (immunizationActivity2CH != null) { - logger.info( - "Creating ACTIVITY incentive for BeneficiaryRegId={}", - vaccination.getBeneficiaryRegId()); + logger.info( + "Creating ACTIVITY incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); - createIncentiveRecord( - vaccination, - benId, - userId, - immunizationActivity2CH); + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivity2CH); + } } } else { @@ -1049,14 +1064,20 @@ private void checkAndAddIncentives(List vaccinationList) { } IncentiveActivity immunizationActivity5AM = incentivesRepo.findIncentiveMasterByNameAndGroup("DPT_IMMUNIZATION_5_YEARS", GroupName.IMMUNIZATION.getDisplayName()); - if (immunizationActivity5AM != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivity5AM); + if(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())) { + + 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); + if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())) { + + if (immunizationActivity5CH != null && childVaccinationRepo.checkDptVaccinatedUser(vaccination.getBeneficiaryRegId()) == 1) { + createIncentiveRecord(vaccination, benId, userId, immunizationActivity5CH); + } } } 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 4fb218b98..b8897fe4b 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -11,9 +11,11 @@ import com.iemr.flw.dto.iemr.EligibleCoupleDTO; import com.iemr.flw.dto.iemr.EligibleCoupleTrackingDTO; 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.CoupleService; +import com.iemr.flw.service.UserService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,6 +48,9 @@ public class CoupleServiceImpl implements CoupleService { @Autowired private UserServiceRoleRepo userRepo; + + @Autowired + private UserService userService; @Autowired private IncentiveRecordRepo recordRepo; @@ -92,11 +97,11 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, 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); + createIncentiveRecord(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); + createIncentiveRecord(it, activity2); } Long id = existingECR.getId(); @@ -111,7 +116,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, IncentiveActivity handoverKitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); if (handoverKitActivityAM != null) { - createIncentiveRecord(recordList, it, handoverKitActivityAM); + createIncentiveRecord(it, handoverKitActivityAM); } @@ -119,7 +124,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, IncentiveActivity handoverKitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); if (handoverKitActivityCH != null) { - createIncentiveRecord(recordList, it, handoverKitActivityCH); + createIncentiveRecord(it, handoverKitActivityCH); } } @@ -140,7 +145,6 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) List recordList = new ArrayList<>(); eligibleCoupleDTOs.forEach(it -> { EligibleCoupleRegister existingECR = -// eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenIdAndCreatedDate(it.getBenId(), it.getCreatedDate()); eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); if (existingECR != null && null != existingECR.getNumLiveChildren()) { @@ -151,16 +155,16 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) IncentiveActivity activityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecord(recordList, it, activity1); - createIncentiveRecord(recordList, it, activityCH); + createIncentiveRecord(it, activity1); + createIncentiveRecord(it, activityCH); } else if (it.getNumLiveChildren() >= 2 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 3) { IncentiveActivity activity2 = 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); + createIncentiveRecord(it, activity2); + createIncentiveRecord(it, activityCH); } Long id = existingECR.getId(); modelMapper.map(it, existingECR); @@ -176,7 +180,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) IncentiveActivity handoverKitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); if (handoverKitActivityAM != null) { - createIncentiveRecord(recordList, it, handoverKitActivityAM); + createIncentiveRecord(it, handoverKitActivityAM); } @@ -184,7 +188,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) IncentiveActivity handoverKitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); if (handoverKitActivityCH != null) { - createIncentiveRecord(recordList, it, handoverKitActivityCH); + createIncentiveRecord(it, handoverKitActivityCH); } } @@ -200,7 +204,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) } - private void createIncentiveRecord(List recordList, EligibleCoupleDTO eligibleCoupleDTO, IncentiveActivity activity) { + private void createIncentiveRecord(EligibleCoupleDTO eligibleCoupleDTO, IncentiveActivity activity) { if (activity != null) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(activity.getId(), eligibleCoupleDTO.getCreatedDate(), eligibleCoupleDTO.getBenId()); @@ -217,7 +221,7 @@ record = new IncentiveActivityRecord(); record.setBenId(eligibleCoupleDTO.getBenId()); record.setAshaId(userId); record.setAmount(Long.valueOf(activity.getRate())); - recordList.add(record); + recordRepo.save(record); } } } @@ -241,7 +245,7 @@ public String registerEligibleCoupleTracking(List eli ect.setId(null); } ectList.add(ect); - checkAndAddAntaraIncentive(recordList, ect); + checkAndAddAntaraIncentive(ect); }); eligibleCoupleTrackingRepo.saveAll(ectList); recordRepo.saveAll(recordList); @@ -251,133 +255,168 @@ public String registerEligibleCoupleTracking(List eli } } - private void checkAndAddAntaraIncentive(List recordList, EligibleCoupleTracking ect) { + private void checkAndAddAntaraIncentive(EligibleCoupleTracking ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); logger.info("Antra" + ect.getMethodOfContraception()); logger.info("Antra" + ect.getAntraDose()); + Integer stateId = userService.getUserDetail(userId).getStateId(); 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(stateId.equals(StateCode.CG.getStateCode())){ + // for CG incentive + IncentiveActivity antaraActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", GroupName.ACTIVITY.getDisplayName()); + if (antaraActivityCH != null) { + String dose = ect.getAntraDose(); - List validDoses = Arrays.asList("Dose-1", "Dose-2", "Dose-3", "Dose-4"); + List validDoses = Arrays.asList("Dose-1", "Dose-2", "Dose-3", "Dose-4"); - boolean isDose = validDoses.stream().anyMatch(dose::contains); + boolean isDose = validDoses.stream().anyMatch(dose::contains); - if (isDose) { - addIncenticeRecord(recordList, ect, userId, antaraActivityCH); + if (isDose) { + addIncenticeRecord(ect, userId, antaraActivityCH); + } } } - if (ect.getAntraDose().contains("Dose-1")) { - IncentiveActivity antaraActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", "FAMILY PLANNING"); - if (antaraActivity != null) { - addIncenticeRecord(recordList, ect, userId, antaraActivity); - } - } else if (ect.getAntraDose().contains("Dose-2")) { - IncentiveActivity antaraActivity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA2", "FAMILY PLANNING"); - if (antaraActivity2 != null) { - addIncenticeRecord(recordList, ect, userId, antaraActivity2); - } - } else if (ect.getAntraDose().contains("Dose-3")) { - IncentiveActivity antaraActivity3 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA3", "FAMILY PLANNING"); - if (antaraActivity3 != null) { - addIncenticeRecord(recordList, ect, userId, antaraActivity3); - } - } else if (ect.getAntraDose().contains("Dose-4")) { - IncentiveActivity antaraActivity4 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA4", "FAMILY PLANNING"); - if (antaraActivity4 != null) { - addIncenticeRecord(recordList, ect, userId, antaraActivity4); - } + if(stateId.equals(StateCode.AM.getStateCode())){ + if (ect.getAntraDose().contains("Dose-1")) { + IncentiveActivity antaraActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA1", "FAMILY PLANNING"); + if (antaraActivity != null) { + addIncenticeRecord(ect, userId, antaraActivity); + } + } else if (ect.getAntraDose().contains("Dose-2")) { + IncentiveActivity antaraActivity2 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA2", "FAMILY PLANNING"); + if (antaraActivity2 != null) { + addIncenticeRecord(ect, userId, antaraActivity2); + } + } else if (ect.getAntraDose().contains("Dose-3")) { + IncentiveActivity antaraActivity3 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA3", "FAMILY PLANNING"); + if (antaraActivity3 != null) { + addIncenticeRecord(ect, userId, antaraActivity3); + } + } else if (ect.getAntraDose().contains("Dose-4")) { + IncentiveActivity antaraActivity4 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA4", "FAMILY PLANNING"); + if (antaraActivity4 != null) { + addIncenticeRecord(ect, userId, antaraActivity4); + } - } else if (ect.getAntraDose().contains("Dose-5")) { - IncentiveActivity antaraActivity4 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA5", GroupName.FAMILY_PLANNING.getDisplayName()); + }else if (ect.getAntraDose().contains("Dose-5")) { + IncentiveActivity antaraActivity4 = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_ANC_MPA5", GroupName.FAMILY_PLANNING.getDisplayName()); + + if (antaraActivity4 != null) { + addIncenticeRecord(ect, userId, antaraActivity4); + } + } + } + if(stateId.equals(StateCode.CG.getStateCode())){ 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); + addIncenticeRecord(ect, userId, antaraActivity4CH); } } + + } 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(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity maleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", "FAMILY PLANNING"); + + if (maleSterilizationActivityAM != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityAM); + } + } - - if (maleSterilizationActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, maleSterilizationActivityCH); + if(stateId.equals(StateCode.CG.getStateCode())){ + + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); + + + if (maleSterilizationActivityCH != null) { + addIncenticeRecord(ect, userId, maleSterilizationActivityCH); + } } + } else if (ect.getMethodOfContraception() != null && ect.getMethodOfContraception().equals("FEMALE STERILIZATION")) { + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - 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(ect, userId, femaleSterilizationActivityCH); + } } + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity femaleSterilizationActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.FAMILY_PLANNING.getDisplayName()); + if (femaleSterilizationActivityAM != null) { + addIncenticeRecord(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("MiniLap")) { + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity miniLapActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MINILAP", "FAMILY PLANNING"); + if (miniLapActivity != null) { + addIncenticeRecord(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); + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity comdomActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", "FAMILY PLANNING"); + if (comdomActivity != null) { + addIncenticeRecord(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(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity copperTActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_CONDOM", "FAMILY PLANNING"); + if (copperTActivity != null) { + addIncenticeRecord(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(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity limitiing2ChildActivityAM = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_LIMIT_2CHILD", GroupName.FAMILY_PLANNING.getDisplayName()); + if (limitiing2ChildActivityAM != null) { + addIncenticeRecord(ect, userId, limitiing2ChildActivityAM); + } } + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity limitiing2ChildActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_LIMIT_2CHILD", GroupName.ACTIVITY.getDisplayName()); - if (limitiing2ChildActivityCH != null) { - addIncenticeRecord(recordList, ect, userId, limitiing2ChildActivityCH); + + if (limitiing2ChildActivityCH != null) { + addIncenticeRecord(ect, userId, limitiing2ChildActivityCH); + } } + + } } - private void addIncenticeRecord(List recordList, EligibleCoupleTracking ect, Integer userId, IncentiveActivity antaraActivity) { + private void addIncenticeRecord(EligibleCoupleTracking ect, Integer userId, IncentiveActivity antaraActivity) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); // get bene details @@ -394,7 +433,7 @@ record = new IncentiveActivityRecord(); record.setBenId(ect.getBenId()); record.setAshaId(userId); record.setAmount(Long.valueOf(antaraActivity.getRate())); - recordList.add(record); + recordRepo.save(record); } } 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 3813df546..6fa282c04 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -582,7 +582,7 @@ private Boolean yesNoToBoolean(String value) { } - private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { + private void checkAndAddAntaraIncentive(List PNCVisit ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); From ec529e4edc7f1c748370a330425732cbf70d9852 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 13:17:53 +0530 Subject: [PATCH 406/450] Incentive logic for first-year child Immunization --- src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java | 1 - .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) 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 b8897fe4b..29a67f2b9 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -68,7 +68,6 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, 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; 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 6fa282c04..3813df546 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -582,7 +582,7 @@ private Boolean yesNoToBoolean(String value) { } - private void checkAndAddAntaraIncentive(List PNCVisit ect) { + private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); From a0d6f2c29260f54aaa2a0ded73136e5979fda337 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 14:04:02 +0530 Subject: [PATCH 407/450] Incentive logic for first-year child Immunization --- .../flw/repo/iemr/ChildVaccinationRepo.java | 17 ++++ .../service/impl/ChildCareServiceImpl.java | 78 +++++++++++++++---- 2 files changed, 81 insertions(+), 14 deletions(-) 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 78d1e6dcd..99487cc2b 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/ChildVaccinationRepo.java @@ -29,6 +29,23 @@ AND v.Currentimmunizationserviceid IN (1,2,3,4,5) """, nativeQuery = true) Integer getFirstYearVaccineCountForBenId(@Param("benRegId") Long benRegId); + @Query(value = """ + SELECT COUNT(DISTINCT cv.VaccineName) + FROM db_iemr.t_childvaccinedetail1 cv + WHERE cv.BeneficiaryRegID = :benRegId + AND cv.VaccineName IN ( + 'BCG Vaccine', + 'OPV-1', + 'OPV-2', + 'OPV-3', + 'Pentavalent-1', + 'Pentavalent-2', + 'Pentavalent-3', + 'Measles & Rubella (MR)-1' + ) + """, nativeQuery = true) + Integer getEligibleFirstYearVaccines(@Param("benRegId") Long benRegId); + @Query(value = "select count(*) from db_iemr.m_immunizationservicevaccination v where v.Currentimmunizationserviceid in (1,2,3,4,5) " + 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 7229ac24b..d4a5936a5 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -974,23 +974,73 @@ private void checkAndAddIncentives(List vaccinationList) { Integer immunizationServiceId = getImmunizationServiceIdForVaccine(vaccination.getVaccineId().shortValue()); if (immunizationServiceId < 6) { + + Integer completedVaccines = + childVaccinationRepo.getEligibleFirstYearVaccines( + vaccination.getBeneficiaryRegId()); + + + logger.info( + "FULL_IMMUNIZATION_0_1 :: BeneficiaryRegId={}, Vaccine={}, VaccineId={}, CompletedVaccines={}, StateId={}", + vaccination.getBeneficiaryRegId(), + vaccination.getVaccineName(), + vaccination.getVaccineId(), + completedVaccines, + stateId + ); + IncentiveActivity immunizationActivityAM = - incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.IMMUNIZATION.getDisplayName()); + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FULL_IMMUNIZATION_0_1", + GroupName.IMMUNIZATION.getDisplayName()); + IncentiveActivity immunizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FULL_IMMUNIZATION_0_1", GroupName.ACTIVITY.getDisplayName()); - - if(userService.getUserDetail(userId).getStateId().equals(StateCode.AM.getStateCode())){ - if (immunizationActivityAM != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityAM); - } - } - - if(userService.getUserDetail(userId).getStateId().equals(StateCode.CG.getStateCode())){ - if (immunizationActivityCH != null && childVaccinationRepo.getFirstYearVaccineCountForBenId(vaccination.getBeneficiaryRegId()) - .equals(childVaccinationRepo.getFirstYearVaccineCount())) { - createIncentiveRecord(vaccination, benId, userId, immunizationActivityCH); + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FULL_IMMUNIZATION_0_1", + GroupName.ACTIVITY.getDisplayName()); + +// Required vaccines = 8 + if (completedVaccines != null && completedVaccines == 8) { + + logger.info( + "Beneficiary {} completed all required first year vaccines.", + vaccination.getBeneficiaryRegId()); + + if (stateId.equals(StateCode.AM.getStateCode()) + && immunizationActivityAM != null) { + + logger.info( + "Creating Assam FULL_IMMUNIZATION_0_1 incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); + + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivityAM); } + + if (stateId.equals(StateCode.CG.getStateCode()) + && immunizationActivityCH != null) { + + logger.info( + "Creating Chhattisgarh FULL_IMMUNIZATION_0_1 incentive for BeneficiaryRegId={}", + vaccination.getBeneficiaryRegId()); + + createIncentiveRecord( + vaccination, + benId, + userId, + immunizationActivityCH); + } + + } else { + + logger.info( + "BeneficiaryRegId={} not eligible for FULL_IMMUNIZATION_0_1. CompletedVaccines={}/8", + vaccination.getBeneficiaryRegId(), + completedVaccines + ); } } else if (immunizationServiceId == 7) { From 97e8bae20d9657c3fc8c25628ee72d41590237ae Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 14:25:23 +0530 Subject: [PATCH 408/450] Incentive logic for first-year child Immunization --- .../com/iemr/flw/repo/iemr/IncentiveRecordRepo.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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 9b36e9981..11710e4c1 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -17,9 +17,18 @@ @Repository public interface IncentiveRecordRepo extends JpaRepository { - @Query("select record from IncentiveActivityRecord record where record.activityId = :id and record.createdDate = :createdDate and record.benId = :benId") + @Query(value = """ + SELECT * + FROM db_iemr.incentive_activity_record r + WHERE r.activity_id = :id + AND r.ben_id = :benId + AND MONTH(r.created_date) = MONTH(:createdDate) + AND YEAR(r.created_date) = YEAR(:createdDate) + LIMIT 1 + """, nativeQuery = true) IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId(@Param("id") Long id, @Param("createdDate") Timestamp createdDate, @Param("benId") Long benId); + Optional findById(Long id); From ad6fb24c9474df57cbffb5ae6926a6b78dc73901 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 15:35:33 +0530 Subject: [PATCH 409/450] Incentive logic for first-year child Immunization --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 3813df546..3b639b61a 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -798,9 +798,9 @@ private void checkAndAddIncentives(List ancList, Integer userId) { - if (comprehensiveAbortionActivityCH != null && ancVisit.getIsAborted() != null + if (paiucdActivityCH != null && ancVisit.getIsAborted() != null && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(comprehensiveAbortionActivityCH, ancVisit); + recordAncRelatedIncentive(paiucdActivityCH, ancVisit); } From 7d8f721599362fb4029a47ce731b26518ab01c1b Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 15:55:23 +0530 Subject: [PATCH 410/450] Incentive logic for first-year child Immunization --- .../iemr/flw/service/impl/MaternalHealthServiceImpl.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) 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 3b639b61a..2c15b297a 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -785,7 +785,7 @@ private void checkAndAddIncentives(List ancList, Integer userId) { if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("1")) { + && ancVisit.getIsPaiucdId().toString().equals("2")) { recordAncRelatedIncentive(paiucdActivityCH, ancVisit); } @@ -797,13 +797,6 @@ private void checkAndAddIncentives(List ancList, Integer userId) { } - - if (paiucdActivityCH != null && ancVisit.getIsAborted() != null - && ancVisit.getIsAborted()) { - recordAncRelatedIncentive(paiucdActivityCH, ancVisit); - } - - if (identifiedHrpActivityCH != null && ancVisit.getIsHrpConfirmed() != null && ancVisit.getIsHrpConfirmed()) { recordAncRelatedIncentive(identifiedHrpActivityCH, ancVisit); From 8c8c2726a9391bed498f9c3851ed9a0684948a38 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 16:26:49 +0530 Subject: [PATCH 411/450] Incentive logic for first-year child Immunization --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 2c15b297a..43bb228dd 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -785,7 +785,7 @@ private void checkAndAddIncentives(List ancList, Integer userId) { if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("2")) { + && ancVisit.getIsPaiucdId().toString().equals("2") && ancVisit.getIsAborted()) { recordAncRelatedIncentive(paiucdActivityCH, ancVisit); } From a8c928cd1535e9fcadb8dd80a88b0b3f2ef98c2c Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Thu, 25 Jun 2026 16:39:29 +0530 Subject: [PATCH 412/450] Incentive logic for first-year child Immunization --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 43bb228dd..f973e77a2 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -784,8 +784,7 @@ private void checkAndAddIncentives(List ancList, Integer userId) { ancList.forEach(ancVisit -> { - if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("2") && ancVisit.getIsAborted()) { + if ( ancVisit.getIsAborted()) { recordAncRelatedIncentive(paiucdActivityCH, ancVisit); } From d9c16932e0c8644dd2de1f06a2980d82ef0fc6d0 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 13:23:21 +0530 Subject: [PATCH 413/450] fix child year gap --- .../service/impl/ChildCareServiceImpl.java | 2 - .../flw/service/impl/CoupleServiceImpl.java | 4 +- .../service/impl/IncentiveServiceImpl.java | 132 +++++++++++++++++- 3 files changed, 132 insertions(+), 6 deletions(-) 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 d4a5936a5..ba0bbb3cf 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -273,8 +273,6 @@ public List getHBNCDetails(GetBenRequestHandler dto) { result.add(responseDTO); } - checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); - } catch (Exception e) { logger.error("Error in getHBNCDetails: ", e); 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 29a67f2b9..eccc33b35 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -147,7 +147,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); if (existingECR != null && null != existingECR.getNumLiveChildren()) { - if (it.getNumLiveChildren() >= 1 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 2) { + if (it.getNumChildren() >= 1 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 2) { IncentiveActivity activity1 = incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()) ; @@ -156,7 +156,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(it, activity1); createIncentiveRecord(it, activityCH); - } else if (it.getNumLiveChildren() >= 2 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 3) { + } else if (it.getNumChildren() >= 2 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 3) { IncentiveActivity activity2 = incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); 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 f85e47f6e..7d815498e 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -199,6 +199,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } + checkIncentiveForChildGap(stateCode, userName); } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); @@ -592,7 +593,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { } if (hwcReferralEnumeration != null) { - logger.info("hwcReferralEnumeration :"+hwcReferralEnumeration.getDescription()); + logger.info("hwcReferralEnumeration :" + hwcReferralEnumeration.getDescription()); logger.info("userName={}", userName); LocalDate now = LocalDate.now(); @@ -602,7 +603,7 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { now.getMonthValue(), now.getYear()); - logger.info("referralCount :"+referralCount); + logger.info("referralCount :" + referralCount); if (referralCount >= 10) { @@ -860,4 +861,131 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent } } + private void checkIncentiveForChildGap(Integer stateId, String userName) { + + logger.info("Checking Child Gap Incentive for user: {}, stateId: {}", userName, stateId); + + List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); + + logger.info("Eligible Couple Records Found: {}", eligibleCoupleRegisters.size()); + + if (!eligibleCoupleRegisters.isEmpty()) { + + eligibleCoupleRegisters.forEach(eligibleCoupleRegister -> { + + logger.info( + "Processing EligibleCoupleRegister -> BenId: {}, NumChildren: {}, MarriageFirstChildGap: {}, FirstAndSecondChildGap: {}", + eligibleCoupleRegister.getBenId(), + eligibleCoupleRegister.getNumChildren(), + eligibleCoupleRegister.getMarriageFirstChildGap(), + eligibleCoupleRegister.getFirstAndSecondChildGap()); + + // Marriage -> First Child Gap + if (eligibleCoupleRegister.getNumChildren() >= 1 + && eligibleCoupleRegister.getMarriageFirstChildGap() >= 2) { + + logger.info("Marriage -> First Child Gap condition matched."); + + if (stateId.equals(StateCode.AM.getStateCode())) { + + logger.info("Fetching incentive for Assam."); + + IncentiveActivity activity1 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "MARRIAGE_1st_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); + + logger.info("Incentive Activity: {}", activity1); + + createIncentiveRecord(eligibleCoupleRegister, activity1); + + logger.info("Marriage -> First Child Gap incentive created."); + } + + if (stateId.equals(StateCode.CG.getStateCode())) { + + logger.info("Fetching incentive for Chhattisgarh."); + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "MARRIAGE_1st_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); + + logger.info("Incentive Activity: {}", activityCH); + + createIncentiveRecord(eligibleCoupleRegister, activityCH); + + logger.info("Marriage -> First Child Gap incentive created."); + } + } + + // First -> Second Child Gap + if (eligibleCoupleRegister.getNumChildren() >= 2 + && eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { + + logger.info("1st -> 2nd Child Gap condition matched."); + + if (stateId.equals(StateCode.AM.getStateCode())) { + + logger.info("Fetching incentive for Assam."); + + IncentiveActivity activity2 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); + + logger.info("Incentive Activity: {}", activity2); + + createIncentiveRecord(eligibleCoupleRegister, activity2); + + logger.info("1st -> 2nd Child Gap incentive created."); + } + + if (stateId.equals(StateCode.CG.getStateCode())) { + + logger.info("Fetching incentive for Chhattisgarh."); + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); + + logger.info("Incentive Activity: {}", activityCH); + + createIncentiveRecord(eligibleCoupleRegister, activityCH); + + logger.info("1st -> 2nd Child Gap incentive created."); + } + } + }); + + } else { + logger.info("No Eligible Couple Register records found for user: {}", userName); + } + + logger.info("Completed Child Gap Incentive check for user: {}", userName); + } + + private void createIncentiveRecord(EligibleCoupleRegister eligibleCoupleRegister, IncentiveActivity activity) { + if (activity != null) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), eligibleCoupleRegister.getCreatedDate(), eligibleCoupleRegister.getBenId()); + Integer userId = userRepo.getUserIdByName(eligibleCoupleRegister.getCreatedBy()); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(eligibleCoupleRegister.getCreatedDate()); + record.setCreatedBy(eligibleCoupleRegister.getCreatedBy()); + record.setStartDate(eligibleCoupleRegister.getCreatedDate()); + record.setEndDate(eligibleCoupleRegister.getCreatedDate()); + record.setUpdatedDate(eligibleCoupleRegister.getCreatedDate()); + record.setUpdatedBy(eligibleCoupleRegister.getCreatedBy()); + record.setBenId(eligibleCoupleRegister.getBenId()); + record.setAshaId(userId); + record.setAmount(Long.valueOf(activity.getRate())); + recordRepo.save(record); + } + } + } + } From bda04da25da6f2d44d8f02439091ddf80263d3ec Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 14:29:38 +0530 Subject: [PATCH 414/450] fix child year gap --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 7d815498e..03e8bd14b 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -881,8 +881,8 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { eligibleCoupleRegister.getFirstAndSecondChildGap()); // Marriage -> First Child Gap - if (eligibleCoupleRegister.getNumChildren() >= 1 - && eligibleCoupleRegister.getMarriageFirstChildGap() >= 2) { + if ((eligibleCoupleRegister.getNumChildren() >= 1 || eligibleCoupleRegister.getNumLiveChildren()>=1) + && eligibleCoupleRegister.getMarriageFirstChildGap() >= 2 ) { logger.info("Marriage -> First Child Gap condition matched."); @@ -920,7 +920,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { } // First -> Second Child Gap - if (eligibleCoupleRegister.getNumChildren() >= 2 + if ((eligibleCoupleRegister.getNumChildren() >= 2 || eligibleCoupleRegister.getNumLiveChildren()>=2) && eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { logger.info("1st -> 2nd Child Gap condition matched."); From f3b8e4e90d1968c13493c7a0bd2af9cca996d75e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 17:21:03 +0530 Subject: [PATCH 415/450] fix child year gap --- .../service/impl/MaternalHealthServiceImpl.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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 f973e77a2..8643874ad 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -142,6 +142,8 @@ public List getANCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List ancVisits = ancVisitRepo.getANCForPW(user, dto.getFromDate(), dto.getToDate()); + checkAndAddIncentives(ancVisits, dto.getAshaId()); + return ancVisits.stream() .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); @@ -373,6 +375,11 @@ public List getPNCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List pncVisits = pncVisitRepo.getPNCForPW(user); + pncVisits.forEach(pncVisit -> { + checkAndAddAntaraIncentive(pncVisit); + + }); + return pncVisits.stream() .map(pnc -> mapper.convertValue(pnc, PNCVisitDTO.class)) .collect(Collectors.toList()); @@ -424,7 +431,7 @@ public String savePNCVisit(List pncVisitDTOs) { pncCare.setLastModDate(it.getUpdatedDate()); pncCare.setProcessed("N"); pncCareList.add(pncCare); - checkAndAddAntaraIncentive(pncList, pncVisit); + checkAndAddAntaraIncentive(pncVisit); } pncList.add(pncVisit); }); @@ -582,7 +589,7 @@ private Boolean yesNoToBoolean(String value) { } - private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) { + private void checkAndAddAntaraIncentive(PNCVisit ect) { Integer userId = userRepo.getUserIdByName(ect.getCreatedBy()); Integer stateId = userRepo.getUserRole(userId).get(0).getStateId(); logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); @@ -636,6 +643,7 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) } + } // logic for cg if(stateId.equals(StateCode.CG.getStateCode())){ @@ -665,7 +673,7 @@ private void checkAndAddAntaraIncentive(List recordList, PNCVisit ect) if (ect.getMotherDangerSign() != null && !ect.getMotherDangerSign().isEmpty() - && ect.getPncPeriod() == 7) { + && ect.getPncPeriod() == 42) { IncentiveActivity highRiskPostpartumCareActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); From d362324ca1ffa9962f0043dc4707e2f01094c3fb Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 17:59:47 +0530 Subject: [PATCH 416/450] fix child year gap --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 03e8bd14b..0f04ec0d6 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -920,7 +920,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { } // First -> Second Child Gap - if ((eligibleCoupleRegister.getNumChildren() >= 2 || eligibleCoupleRegister.getNumLiveChildren()>=2) + if ((eligibleCoupleRegister.getNumChildren() >= 1 || eligibleCoupleRegister.getNumLiveChildren()>=1) && eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { logger.info("1st -> 2nd Child Gap condition matched."); From 06b6fa354007bc6b797a04410090add386602906 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 18:01:29 +0530 Subject: [PATCH 417/450] fix child year gap --- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 0f04ec0d6..070a96c88 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -881,8 +881,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { eligibleCoupleRegister.getFirstAndSecondChildGap()); // Marriage -> First Child Gap - if ((eligibleCoupleRegister.getNumChildren() >= 1 || eligibleCoupleRegister.getNumLiveChildren()>=1) - && eligibleCoupleRegister.getMarriageFirstChildGap() >= 2 ) { + if (eligibleCoupleRegister.getMarriageFirstChildGap() >= 2 ) { logger.info("Marriage -> First Child Gap condition matched."); @@ -920,8 +919,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { } // First -> Second Child Gap - if ((eligibleCoupleRegister.getNumChildren() >= 1 || eligibleCoupleRegister.getNumLiveChildren()>=1) - && eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { + if (eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { logger.info("1st -> 2nd Child Gap condition matched."); From a5caaf413093921f6996a464e377da78904beb6a Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 18:11:28 +0530 Subject: [PATCH 418/450] fix child year gap --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 070a96c88..0674818fb 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -881,7 +881,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { eligibleCoupleRegister.getFirstAndSecondChildGap()); // Marriage -> First Child Gap - if (eligibleCoupleRegister.getMarriageFirstChildGap() >= 2 ) { + if (eligibleCoupleRegister.getFirstAndSecondChildGap() >= 2 ) { logger.info("Marriage -> First Child Gap condition matched."); @@ -919,7 +919,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { } // First -> Second Child Gap - if (eligibleCoupleRegister.getFirstAndSecondChildGap() >= 3) { + if (eligibleCoupleRegister.getMarriageFirstChildGap() >= 3) { logger.info("1st -> 2nd Child Gap condition matched."); From d0d36dcca4fe13642f17c374f141dad5e334b5d9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 18:27:54 +0530 Subject: [PATCH 419/450] fix child year gap --- .../flw/service/impl/CoupleServiceImpl.java | 4 +- .../service/impl/IncentiveServiceImpl.java | 90 ++++++++++--------- 2 files changed, 50 insertions(+), 44 deletions(-) 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 eccc33b35..2778fffc7 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -147,7 +147,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); if (existingECR != null && null != existingECR.getNumLiveChildren()) { - if (it.getNumChildren() >= 1 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 2) { + if (it.getFirstAndSecondChildGap() >= 2) { IncentiveActivity activity1 = incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()) ; @@ -156,7 +156,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(it, activity1); createIncentiveRecord(it, activityCH); - } else if (it.getNumChildren() >= 2 && it.getMarriageFirstChildGap() != null && it.getMarriageFirstChildGap() >= 3) { + } else if (it.getMarriageFirstChildGap() >= 3) { IncentiveActivity activity2 = incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); 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 0674818fb..ddf02e32e 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -881,80 +881,86 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { eligibleCoupleRegister.getFirstAndSecondChildGap()); // Marriage -> First Child Gap - if (eligibleCoupleRegister.getFirstAndSecondChildGap() >= 2 ) { + if(eligibleCoupleRegister.getFirstAndSecondChildGap()!=null){ + if (eligibleCoupleRegister.getFirstAndSecondChildGap()>=2 ) { - logger.info("Marriage -> First Child Gap condition matched."); + logger.info("Marriage -> First Child Gap condition matched."); - if (stateId.equals(StateCode.AM.getStateCode())) { + if (stateId.equals(StateCode.AM.getStateCode())) { - logger.info("Fetching incentive for Assam."); + logger.info("Fetching incentive for Assam."); - IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "MARRIAGE_1st_CHILD_GAP", - GroupName.FAMILY_PLANNING.getDisplayName()); + IncentiveActivity activity1 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "MARRIAGE_1st_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); - logger.info("Incentive Activity: {}", activity1); + logger.info("Incentive Activity: {}", activity1); - createIncentiveRecord(eligibleCoupleRegister, activity1); + createIncentiveRecord(eligibleCoupleRegister, activity1); - logger.info("Marriage -> First Child Gap incentive created."); - } + logger.info("Marriage -> First Child Gap incentive created."); + } - if (stateId.equals(StateCode.CG.getStateCode())) { + if (stateId.equals(StateCode.CG.getStateCode())) { - logger.info("Fetching incentive for Chhattisgarh."); + logger.info("Fetching incentive for Chhattisgarh."); - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "MARRIAGE_1st_CHILD_GAP", - GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "MARRIAGE_1st_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); - logger.info("Incentive Activity: {}", activityCH); + logger.info("Incentive Activity: {}", activityCH); - createIncentiveRecord(eligibleCoupleRegister, activityCH); + createIncentiveRecord(eligibleCoupleRegister, activityCH); - logger.info("Marriage -> First Child Gap incentive created."); + logger.info("Marriage -> First Child Gap incentive created."); + } } } + // First -> Second Child Gap - if (eligibleCoupleRegister.getMarriageFirstChildGap() >= 3) { + if(eligibleCoupleRegister.getMarriageFirstChildGap()!=null){ + if (eligibleCoupleRegister.getMarriageFirstChildGap()>=3) { - logger.info("1st -> 2nd Child Gap condition matched."); + logger.info("1st -> 2nd Child Gap condition matched."); - if (stateId.equals(StateCode.AM.getStateCode())) { + if (stateId.equals(StateCode.AM.getStateCode())) { - logger.info("Fetching incentive for Assam."); + logger.info("Fetching incentive for Assam."); - IncentiveActivity activity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.FAMILY_PLANNING.getDisplayName()); + IncentiveActivity activity2 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); - logger.info("Incentive Activity: {}", activity2); + logger.info("Incentive Activity: {}", activity2); - createIncentiveRecord(eligibleCoupleRegister, activity2); + createIncentiveRecord(eligibleCoupleRegister, activity2); - logger.info("1st -> 2nd Child Gap incentive created."); - } + logger.info("1st -> 2nd Child Gap incentive created."); + } - if (stateId.equals(StateCode.CG.getStateCode())) { + if (stateId.equals(StateCode.CG.getStateCode())) { - logger.info("Fetching incentive for Chhattisgarh."); + logger.info("Fetching incentive for Chhattisgarh."); - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); - logger.info("Incentive Activity: {}", activityCH); + logger.info("Incentive Activity: {}", activityCH); - createIncentiveRecord(eligibleCoupleRegister, activityCH); + createIncentiveRecord(eligibleCoupleRegister, activityCH); - logger.info("1st -> 2nd Child Gap incentive created."); + logger.info("1st -> 2nd Child Gap incentive created."); + } } } + }); } else { From 52be8ba8ad5562d590d3868742f0e24314610eb7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Fri, 26 Jun 2026 18:50:04 +0530 Subject: [PATCH 420/450] fix child year gap --- .../java/com/iemr/flw/service/impl/CoupleServiceImpl.java | 6 +++--- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) 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 2778fffc7..39415a87d 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -146,14 +146,14 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) EligibleCoupleRegister existingECR = eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); - if (existingECR != null && null != existingECR.getNumLiveChildren()) { + if (existingECR !=null) { if (it.getFirstAndSecondChildGap() >= 2) { IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()) + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()) ; IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("MARRIAGE_1st_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(it, activity1); createIncentiveRecord(it, activityCH); } else if (it.getMarriageFirstChildGap() >= 3) { 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 ddf02e32e..a3e0a7907 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -892,7 +892,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { IncentiveActivity activity1 = incentivesRepo.findIncentiveMasterByNameAndGroup( - "MARRIAGE_1st_CHILD_GAP", + "FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()); logger.info("Incentive Activity: {}", activity1); @@ -908,7 +908,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { IncentiveActivity activityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( - "MARRIAGE_1st_CHILD_GAP", + "FP_DELAY_2Y", GroupName.ACTIVITY.getDisplayName()); logger.info("Incentive Activity: {}", activityCH); From 2b2c7c5c914eabda272781ab26a3795f53d87dc3 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 12:01:26 +0530 Subject: [PATCH 421/450] fix duplicate record in child gap incentive --- .../com/iemr/flw/service/impl/CoupleServiceImpl.java | 9 ++++----- .../com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 -- 2 files changed, 4 insertions(+), 7 deletions(-) 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 39415a87d..c783c55fd 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -147,16 +147,15 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); if (existingECR !=null) { - if (it.getFirstAndSecondChildGap() >= 2) { + if (it.getFirstAndSecondChildGap()!=null && it.getFirstAndSecondChildGap() >= 2) { IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()) - ; + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()); IncentiveActivity activityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecord(it, activity1); createIncentiveRecord(it, activityCH); - } else if (it.getMarriageFirstChildGap() >= 3) { + } else if (it.getFirstAndSecondChildGap()!=null && it.getMarriageFirstChildGap() >= 3) { IncentiveActivity activity2 = incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); @@ -175,7 +174,7 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) } - if (existingECR.getIsKitHandedOver()) { + if (existingECR.getIsKitHandedOver()!=null && existingECR.getIsKitHandedOver()) { IncentiveActivity handoverKitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); if (handoverKitActivityAM != null) { 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 a3e0a7907..612b41746 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -199,8 +199,6 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } - checkIncentiveForChildGap(stateCode, userName); - } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); } From a1ecc52016f00d6679049c5a7f536839f1694fce Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 13:29:57 +0530 Subject: [PATCH 422/450] fix duplicate record in child gap incentive --- .../flw/service/impl/CoupleServiceImpl.java | 277 +++++++++++++----- .../service/impl/IncentiveServiceImpl.java | 2 + 2 files changed, 199 insertions(+), 80 deletions(-) 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 c783c55fd..574b8fab4 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @@ -62,78 +63,95 @@ public class CoupleServiceImpl implements CoupleService { @Override - public String registerEligibleCouple(List eligibleCoupleDTOs, MultipartFile kitPhoto1, MultipartFile kitPhoto2) { + @Transactional + public String registerEligibleCouple(List eligibleCoupleDTOs, + MultipartFile kitPhoto1, + MultipartFile kitPhoto2) { try { + List ecrList = new ArrayList<>(); - List recordList = new ArrayList<>(); - eligibleCoupleDTOs.forEach(it -> { + + for (EligibleCoupleDTO it : eligibleCoupleDTOs) { + EligibleCoupleRegister existingECR = 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)); + boolean isNew = false; + + if (existingECR == null) { + existingECR = new EligibleCoupleRegister(); + isNew = true; } + Long id = existingECR.getId(); - 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)); + modelMapper.map(it, existingECR); + existingECR.setId(id); + + // Photo 1 + if (kitPhoto1 != null && !kitPhoto1.isEmpty()) { + existingECR.setKitPhoto1( + Base64.getEncoder().encodeToString(kitPhoto1.getBytes())); } - 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(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(it, activity2); + // Photo 2 + if (kitPhoto2 != null && !kitPhoto2.isEmpty()) { + existingECR.setKitPhoto2( + Base64.getEncoder().encodeToString(kitPhoto2.getBytes())); + } + + // Incentive only for new registration + if (isNew) { + + if (it.getMarriageFirstChildGap() != null + && it.getMarriageFirstChildGap() >= 2) { + + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.FAMILY_PLANNING.getDisplayName()); + + createIncentiveRecord(existingECR, activity); } - 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(it, handoverKitActivityAM); + if (it.getFirstAndSecondChildGap() != null + && it.getFirstAndSecondChildGap() >= 3) { + + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); + createIncentiveRecord(existingECR, activity); } + } + // Kit Incentive + if (Boolean.TRUE.equals(existingECR.getIsKitHandedOver()) + && ((existingECR.getKitPhoto1() != null && !existingECR.getKitPhoto1().isEmpty()) + || (existingECR.getKitPhoto2() != null && !existingECR.getKitPhoto2().isEmpty()))) { - IncentiveActivity handoverKitActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); - if (handoverKitActivityCH != null) { - createIncentiveRecord(it, handoverKitActivityCH); + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_NP_KIT", + GroupName.FAMILY_PLANNING.getDisplayName()); + if (activity != null) { + createIncentiveRecord(existingECR, activity); } } + ecrList.add(existingECR); - }); + } + eligibleCoupleRegisterRepo.saveAll(ecrList); - recordRepo.saveAll(recordList); - return "no of ecr details saved: " + ecrList.size(); + + return "No of ECR details saved: " + ecrList.size(); + } catch (Exception e) { - return "error while saving ecr details: " + e.getMessage(); + logger.error("Error while saving Eligible Couple Registration", e); + return "Error while saving ECR details: " + e.getMessage(); } } @@ -141,44 +159,141 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, public String registerEligibleCouple(List eligibleCoupleDTOs) { try { List ecrList = new ArrayList<>(); - List recordList = new ArrayList<>(); eligibleCoupleDTOs.forEach(it -> { EligibleCoupleRegister existingECR = eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); - - if (existingECR !=null) { - if (it.getFirstAndSecondChildGap()!=null && it.getFirstAndSecondChildGap() >= 2) { - IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.FAMILY_PLANNING.getDisplayName()); - - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_DELAY_2Y", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecord(it, activity1); - createIncentiveRecord(it, activityCH); - } else if (it.getFirstAndSecondChildGap()!=null && it.getMarriageFirstChildGap() >= 3) { - IncentiveActivity activity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.FAMILY_PLANNING.getDisplayName()); - - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("1st_2nd_CHILD_GAP", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecord(it, activity2); - createIncentiveRecord(it, activityCH); - } + if(existingECR!=null){ Long id = existingECR.getId(); modelMapper.map(it, existingECR); existingECR.setId(id); - } else { + }else { existingECR = new EligibleCoupleRegister(); modelMapper.map(it, existingECR); existingECR.setId(null); } + ecrList.add(existingECR); + + }); + + eligibleCoupleRegisterRepo.saveAll(ecrList); + if(!ecrList.isEmpty()){ + Integer userId = userRepo.getUserIdByName(ecrList.get(0).getCreatedBy()); + Integer stateId = userService.getUserDetail(userId).getStateId(); + checkIncentiveForChildGap(stateId,ecrList.get(0).getCreatedBy(),ecrList); + + } + return "no of ecr details saved: " + ecrList.size(); + } catch (Exception e) { + return "error while saving ecr details: " + e.getMessage(); + } + } + + + private void checkIncentiveForChildGap(Integer stateId, String userName,List eligibleCoupleRegisters) { + + logger.info("Checking Child Gap Incentive for user: {}, stateId: {}", userName, stateId); + + + logger.info("Eligible Couple Records Found: {}", eligibleCoupleRegisters.size()); + + if (!eligibleCoupleRegisters.isEmpty()) { + + eligibleCoupleRegisters.forEach(eligibleCoupleRegister -> { + + logger.info( + "Processing EligibleCoupleRegister -> BenId: {}, NumChildren: {}, MarriageFirstChildGap: {}, FirstAndSecondChildGap: {}", + eligibleCoupleRegister.getBenId(), + eligibleCoupleRegister.getNumChildren(), + eligibleCoupleRegister.getMarriageFirstChildGap(), + eligibleCoupleRegister.getFirstAndSecondChildGap()); + + // Marriage -> First Child Gap + if(eligibleCoupleRegister.getFirstAndSecondChildGap()!=null){ + if (eligibleCoupleRegister.getFirstAndSecondChildGap()>=2 ) { + + logger.info("Marriage -> First Child Gap condition matched."); + + if (stateId.equals(StateCode.AM.getStateCode())) { + + logger.info("Fetching incentive for Assam."); + + IncentiveActivity activity1 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.FAMILY_PLANNING.getDisplayName()); + + logger.info("Incentive Activity: {}", activity1); + + createIncentiveRecord(eligibleCoupleRegister, activity1); + + logger.info("Marriage -> First Child Gap incentive created."); + } + + if (stateId.equals(StateCode.CG.getStateCode())) { + + logger.info("Fetching incentive for Chhattisgarh."); + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.ACTIVITY.getDisplayName()); + + logger.info("Incentive Activity: {}", activityCH); + + createIncentiveRecord(eligibleCoupleRegister, activityCH); + + logger.info("Marriage -> First Child Gap incentive created."); + } + } + } + - if (existingECR.getIsKitHandedOver()!=null && existingECR.getIsKitHandedOver()) { + // First -> Second Child Gap + if(eligibleCoupleRegister.getMarriageFirstChildGap()!=null){ + if (eligibleCoupleRegister.getMarriageFirstChildGap()>=3) { + + logger.info("1st -> 2nd Child Gap condition matched."); + + if (stateId.equals(StateCode.AM.getStateCode())) { + + logger.info("Fetching incentive for Assam."); + + IncentiveActivity activity2 = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); + + logger.info("Incentive Activity: {}", activity2); + + createIncentiveRecord(eligibleCoupleRegister, activity2); + + logger.info("1st -> 2nd Child Gap incentive created."); + } + + if (stateId.equals(StateCode.CG.getStateCode())) { + + logger.info("Fetching incentive for Chhattisgarh."); + + IncentiveActivity activityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); + + logger.info("Incentive Activity: {}", activityCH); + + createIncentiveRecord(eligibleCoupleRegister, activityCH); + + logger.info("1st -> 2nd Child Gap incentive created."); + } + } + } + + if (eligibleCoupleRegister.getIsKitHandedOver()!=null && eligibleCoupleRegister.getIsKitHandedOver()) { IncentiveActivity handoverKitActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.FAMILY_PLANNING.getDisplayName()); if (handoverKitActivityAM != null) { - createIncentiveRecord(it, handoverKitActivityAM); + createIncentiveRecord(eligibleCoupleRegister, handoverKitActivityAM); } @@ -186,23 +301,25 @@ public String registerEligibleCouple(List eligibleCoupleDTOs) IncentiveActivity handoverKitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("FP_NP_KIT", GroupName.ACTIVITY.getDisplayName()); if (handoverKitActivityCH != null) { - createIncentiveRecord(it, handoverKitActivityCH); + createIncentiveRecord(eligibleCoupleRegister, 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(); + + } else { + logger.info("No Eligible Couple Register records found for user: {}", userName); } + + logger.info("Completed Child Gap Incentive check for user: {}", userName); } - private void createIncentiveRecord(EligibleCoupleDTO eligibleCoupleDTO, IncentiveActivity activity) { + private void createIncentiveRecord(EligibleCoupleRegister eligibleCoupleDTO, IncentiveActivity activity) { if (activity != null) { IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(activity.getId(), eligibleCoupleDTO.getCreatedDate(), eligibleCoupleDTO.getBenId()); 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 612b41746..a3e0a7907 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -199,6 +199,8 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } + checkIncentiveForChildGap(stateCode, userName); + } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); } From b59484e5e022fffc5db924c77bf3cc61d2484534 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 13:46:32 +0530 Subject: [PATCH 423/450] fix duplicate record in child gap incentive --- .../flw/service/impl/CoupleServiceImpl.java | 140 +++++++++++------- .../service/impl/IncentiveServiceImpl.java | 2 +- 2 files changed, 90 insertions(+), 52 deletions(-) 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 574b8fab4..332728e07 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -70,82 +70,120 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, try { List ecrList = new ArrayList<>(); + if(!eligibleCoupleDTOs.isEmpty()){ + for (EligibleCoupleDTO it : eligibleCoupleDTOs) { + Integer userId = userRepo.getUserIdByName(it.getCreatedBy()); + Integer stateId = userService.getUserDetail(userId).getStateId(); + EligibleCoupleRegister existingECR = + eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); + + boolean isNew = false; + + if (existingECR == null) { + existingECR = new EligibleCoupleRegister(); + isNew = true; + } - for (EligibleCoupleDTO it : eligibleCoupleDTOs) { + Long id = existingECR.getId(); - EligibleCoupleRegister existingECR = - eligibleCoupleRegisterRepo.findEligibleCoupleRegisterByBenId(it.getBenId()); + modelMapper.map(it, existingECR); - boolean isNew = false; + existingECR.setId(id); - if (existingECR == null) { - existingECR = new EligibleCoupleRegister(); - isNew = true; - } + // Photo 1 + if (kitPhoto1 != null && !kitPhoto1.isEmpty()) { + existingECR.setKitPhoto1( + Base64.getEncoder().encodeToString(kitPhoto1.getBytes())); + } - Long id = existingECR.getId(); + // Photo 2 + if (kitPhoto2 != null && !kitPhoto2.isEmpty()) { + existingECR.setKitPhoto2( + Base64.getEncoder().encodeToString(kitPhoto2.getBytes())); + } - modelMapper.map(it, existingECR); + // Incentive only for new registration + if (isNew) { - existingECR.setId(id); + if (it.getMarriageFirstChildGap() != null + && it.getMarriageFirstChildGap() >= 2) { - // Photo 1 - if (kitPhoto1 != null && !kitPhoto1.isEmpty()) { - existingECR.setKitPhoto1( - Base64.getEncoder().encodeToString(kitPhoto1.getBytes())); - } + IncentiveActivity activity = null; - // Photo 2 - if (kitPhoto2 != null && !kitPhoto2.isEmpty()) { - existingECR.setKitPhoto2( - Base64.getEncoder().encodeToString(kitPhoto2.getBytes())); - } + if (stateId.equals(StateCode.AM.getStateCode())) { + activity = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.FAMILY_PLANNING.getDisplayName()); - // Incentive only for new registration - if (isNew) { + } else if (stateId.equals(StateCode.CG.getStateCode())) { + activity = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.ACTIVITY.getDisplayName()); + } - if (it.getMarriageFirstChildGap() != null - && it.getMarriageFirstChildGap() >= 2) { + if (activity != null) { + createIncentiveRecord(existingECR, activity); + } + } - IncentiveActivity activity = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "FP_DELAY_2Y", - GroupName.FAMILY_PLANNING.getDisplayName()); + if (it.getFirstAndSecondChildGap() != null + && it.getFirstAndSecondChildGap() >= 3) { - createIncentiveRecord(existingECR, activity); - } + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); - if (it.getFirstAndSecondChildGap() != null - && it.getFirstAndSecondChildGap() >= 3) { + createIncentiveRecord(existingECR, activity); - IncentiveActivity activity = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.FAMILY_PLANNING.getDisplayName()); + } + } + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecord(existingECR, activity); + createIncentiveRecord(existingECR, activity); + } } - } - // Kit Incentive - if (Boolean.TRUE.equals(existingECR.getIsKitHandedOver()) - && ((existingECR.getKitPhoto1() != null && !existingECR.getKitPhoto1().isEmpty()) - || (existingECR.getKitPhoto2() != null && !existingECR.getKitPhoto2().isEmpty()))) { + // Kit Incentive + if (Boolean.TRUE.equals(existingECR.getIsKitHandedOver()) + && ((existingECR.getKitPhoto1() != null && !existingECR.getKitPhoto1().isEmpty()) + || (existingECR.getKitPhoto2() != null && !existingECR.getKitPhoto2().isEmpty()))) { + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_NP_KIT", + GroupName.FAMILY_PLANNING.getDisplayName()); + + if (activity != null) { + createIncentiveRecord(existingECR, activity); + } + } + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_NP_KIT", + GroupName.ACTIVITY.getDisplayName()); + + if (activity != null) { + createIncentiveRecord(existingECR, activity); + } + } - IncentiveActivity activity = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "FP_NP_KIT", - GroupName.FAMILY_PLANNING.getDisplayName()); - if (activity != null) { - createIncentiveRecord(existingECR, activity); } + + ecrList.add(existingECR); } - ecrList.add(existingECR); + eligibleCoupleRegisterRepo.saveAll(ecrList); + } - eligibleCoupleRegisterRepo.saveAll(ecrList); return "No of ECR details saved: " + ecrList.size(); 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 a3e0a7907..8d6db8999 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -199,7 +199,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } - checkIncentiveForChildGap(stateCode, userName); + // checkIncentiveForChildGap(stateCode, userName); } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); From 69123c1062d5bf8bbe2c9c9ea79193fee0ae09c2 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 14:02:44 +0530 Subject: [PATCH 424/450] fix duplicate record in child gap incentive --- .../iemr/flw/service/impl/CoupleServiceImpl.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) 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 332728e07..e6aca951b 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -138,15 +138,16 @@ public String registerEligibleCouple(List eligibleCoupleDTOs, createIncentiveRecord(existingECR, activity); } - } - if(stateId.equals(StateCode.CG.getStateCode())){ - IncentiveActivity activity = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.ACTIVITY.getDisplayName()); + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecord(existingECR, activity); + createIncentiveRecord(existingECR, activity); + } } + } // Kit Incentive From b13759f828245302a090f90a217979efef5f4ce9 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 14:18:57 +0530 Subject: [PATCH 425/450] fix duplicate record in child gap incentive --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8d6db8999..a3e0a7907 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -199,7 +199,7 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } - // checkIncentiveForChildGap(stateCode, userName); + checkIncentiveForChildGap(stateCode, userName); } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); From 08851c44fae6865f819085cf4ebd445430a65244 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 15:04:49 +0530 Subject: [PATCH 426/450] fix duplicate record in child gap incentive --- .../java/com/iemr/flw/service/impl/IncentiveServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 a3e0a7907..5ff7ddb25 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -882,7 +882,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { // Marriage -> First Child Gap if(eligibleCoupleRegister.getFirstAndSecondChildGap()!=null){ - if (eligibleCoupleRegister.getFirstAndSecondChildGap()>=2 ) { + if (eligibleCoupleRegister.getFirstAndSecondChildGap()>=3 ) { logger.info("Marriage -> First Child Gap condition matched."); @@ -923,7 +923,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName) { // First -> Second Child Gap if(eligibleCoupleRegister.getMarriageFirstChildGap()!=null){ - if (eligibleCoupleRegister.getMarriageFirstChildGap()>=3) { + if (eligibleCoupleRegister.getMarriageFirstChildGap()>=2) { logger.info("1st -> 2nd Child Gap condition matched."); From 4792fd887cebdb9e68f1283a98e9588b4c1f1322 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 17:23:23 +0530 Subject: [PATCH 427/450] fix hbnc incentive --- .../com/iemr/flw/repo/iemr/ANCVisitRepo.java | 3 + .../service/impl/ChildCareServiceImpl.java | 56 ++++++++++++------- 2 files changed, 39 insertions(+), 20 deletions(-) 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 6d22f7525..67e3e7b9d 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,9 @@ public interface ANCVisitRepo extends JpaRepository { List getANCForPW(@Param("userId") String userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + @Query(value = "SELECT anc FROM ANCVisit anc WHERE anc.createdBy = :userId and anc.isActive = true") + List getANCForPW(@Param("userId") String userId); + @Query List findANCVisitByBenIdAndAncVisitAndIsActive(Long benId, Integer ancVisit, boolean b); 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 ba0bbb3cf..f452916cf 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -271,6 +271,7 @@ public List getHBNCDetails(GetBenRequestHandler dto) { responseDTO.setFields(fields); result.add(responseDTO); + checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); } @@ -880,6 +881,8 @@ private void checkAndAddHbyncIncentives(List hbycList) { private void checkAndAddHbncIncentives(List hbncVisits, Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); + List pncVisits = pncVisitRepo.getPNCForPW(userRepo.getUserNamedByUserId(userId)); + List ancVisits = ancVisitRepo.getANCForPW(userRepo.getUserNamedByUserId(userId)); hbncVisits.forEach(hbncVisit -> { Long benId = hbncVisit.getBeneficiaryId(); if (stateCode.equals(StateCode.AM.getStateCode())) { @@ -889,25 +892,45 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityAM, "HBNC_0_42_DAYS"); } - if (hbncVisit.getVisit_day().equals("42th Day")) { - if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { - if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); - - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + pncVisits.forEach(pncVisit -> { + Long hbncHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(hbncVisit.getBeneficiaryId())).get(0).getHouseoldId(); + Long houseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(pncVisit.getBenId())).get(0).getHouseoldId(); + + if (hbncHouseHoldId.equals(houseHoldId)) { + if (hbncVisit.getVisit_day().equals("42th Day")) { + if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { + if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + createIncentiveRecordforHbncVisit(hbncVisit, pncVisit.getBenId(), visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + } + } + if (!pncVisitRepo.findByBenId(pncVisit.getBenId()).isEmpty()) { + if (!pncVisitRepo.findByBenId(pncVisit.getBenId()).get(0).getMotherDangerSign().isEmpty()) { + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + createIncentiveRecordforHbncVisit(hbncVisit, pncVisit.getBenId(), visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); + } + } } } - if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { - if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty()) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); - + }); + + ancVisits.forEach(ancVisit -> { + Long hbncHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(hbncVisit.getBeneficiaryId())).get(0).getHouseoldId(); + Long ancHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(ancVisit.getBenId())).get(0).getHouseoldId(); + + if (hbncHouseHoldId.equals(ancHouseHoldId)) { + if (hbncVisit.getVisit_day().equals("42th Day")) { + if (!ancVisitRepo.findByBenId(ancVisit.getBenId()).isEmpty()) { + if (ancVisitRepo.findByBenId(ancVisit.getBenId()).get(0).getIsHrpConfirmed()) { + IncentiveActivity visitActivityANC = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + createIncentiveRecordforHbncVisit(hbncVisit, ancVisit.getBenId(), visitActivityANC, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); + } + } } } + }); - } 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) { @@ -1177,13 +1200,6 @@ record = new IncentiveActivityRecord(); record.setUpdatedBy(hbncVisit.getCreatedBy()); record.setBenId(benId); record.setAshaId(hbncVisit.getAshaId()); - if (hbncVisit.getDischarge_summary_upload() == null || hbncVisit.getDischarge_summary_upload().isEmpty()) { - record.setIsEligible(false); - } else { - record.setIsEligible(false); - updatePendingActivity(hbncVisit.getAshaId(), hbncVisit.getId(), record.getActivityId(), immunizationActivity.getId()); - - } record.setAmount(Long.valueOf(immunizationActivity.getRate())); recordRepo.save(record); } From 83fc1d5bde69f566ba781a8e64ef23cfb9c83448 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 17:57:49 +0530 Subject: [PATCH 428/450] fix hbnc incentive --- .../flw/service/impl/MaternalHealthServiceImpl.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) 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 8643874ad..79fd7e7f2 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -671,17 +671,24 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { addIncenticeRecord(ect, userId, maleSterilizationActivityCH); } - if (ect.getMotherDangerSign() != null - && !ect.getMotherDangerSign().isEmpty() - && ect.getPncPeriod() == 42) { + if (ect.getPncPeriod() == 42) { IncentiveActivity highRiskPostpartumCareActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); + + IncentiveActivity highRiskPostpartumHealthCareActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); if (highRiskPostpartumCareActivityCH != null) { addIncenticeRecord(ect, userId, highRiskPostpartumCareActivityCH); } + if (highRiskPostpartumHealthCareActivityCH != null) { + addIncenticeRecord(ect, userId, highRiskPostpartumHealthCareActivityCH); + + } + + } if (ect.getPncPeriod() == 1 || ect.getPncPeriod() == 3 || ect.getPncPeriod() == 7) { From 544e9ba7407a9127bd327d232612d75b13718fa7 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 29 Jun 2026 19:37:38 +0530 Subject: [PATCH 429/450] fix hbnc incentive --- .../service/impl/MaternalHealthServiceImpl.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) 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 79fd7e7f2..0b14f90ab 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -670,19 +670,23 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { if (maleSterilizationActivityCH != null) { addIncenticeRecord(ect, userId, maleSterilizationActivityCH); } - - if (ect.getPncPeriod() == 42) { - + if(ect.getMotherDangerSign() != null + && !ect.getMotherDangerSign().isEmpty() + && ect.getPncPeriod() == 42){ IncentiveActivity highRiskPostpartumCareActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - - IncentiveActivity highRiskPostpartumHealthCareActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); if (highRiskPostpartumCareActivityCH != null) { addIncenticeRecord(ect, userId, highRiskPostpartumCareActivityCH); } + } + if (ect.getPncPeriod() == 42) { + + + IncentiveActivity highRiskPostpartumHealthCareActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + if (highRiskPostpartumHealthCareActivityCH != null) { addIncenticeRecord(ect, userId, highRiskPostpartumHealthCareActivityCH); From cb9d437fcf63a6d7a70bdbdc9e0a201a855e9373 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Fri, 3 Jul 2026 17:37:12 +0530 Subject: [PATCH 430/450] Fix/asha profile image issue (#265) * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue * fix asha profile image issue --- .../flw/controller/AshaProfileController.java | 20 +-- .../com/iemr/flw/domain/iemr/AshaWorker.java | 7 +- .../flw/service/impl/AshaProfileImpl.java | 138 +++++++++++++++--- 3 files changed, 133 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/iemr/flw/controller/AshaProfileController.java b/src/main/java/com/iemr/flw/controller/AshaProfileController.java index cedfcda06..2d02ce231 100644 --- a/src/main/java/com/iemr/flw/controller/AshaProfileController.java +++ b/src/main/java/com/iemr/flw/controller/AshaProfileController.java @@ -62,18 +62,18 @@ public ResponseEntity> getProfile(HttpServletRequest request 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); -// } +// 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 + int userId = jwtUtil.extractUserId(jwtFromHeader); // Make sure this returns 0 or throws for invalid token - if (employeeId == 0) { + if (userId == 0) { response.put("statusCode", 401); response.put("status", "Unauthorized"); response.put("errorMessage", "Invalid JWT token"); @@ -81,7 +81,7 @@ public ResponseEntity> getProfile(HttpServletRequest request } // Business logic - AshaWorker ashaWorker = ashaProfileService.getProfileData(employeeId); + AshaWorker ashaWorker = ashaProfileService.getProfileData(userId); logger.info("Asha Profile"+ashaWorker); response.put("statusCode", 200); diff --git a/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java b/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java index 36fba04ec..2df2bf43c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java +++ b/src/main/java/com/iemr/flw/domain/iemr/AshaWorker.java @@ -27,7 +27,7 @@ public class AshaWorker { private Integer employeeId; // Changed from Integer to String @Column(name = "dob") - private LocalDate dob; // Changed from String to LocalDate + private String dob; // Changed from String to LocalDate @Column(name = "mobile_number") @@ -40,7 +40,7 @@ public class AshaWorker { private String fatherOrSpouseName; @Column(name = "date_of_joining") - private LocalDate dateOfJoining; // Changed from String to LocalDate + private String dateOfJoining; // Changed from String to LocalDate @Column(name = "bank_account") @@ -98,8 +98,9 @@ public class AshaWorker { @Column(name = "ProviderServiceMapID") private Integer ProviderServiceMapID; + @Lob @Column(name = "profileImage") - private String profileImage; + private byte[] profileImage; @Column(name = "isFatherOrSpouse") private Boolean isFatherOrSpouse; diff --git a/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java index df86d7ec7..fe7b04dbb 100644 --- a/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AshaProfileImpl.java @@ -2,12 +2,14 @@ import com.iemr.flw.domain.iemr.AshaWorker; import com.iemr.flw.domain.iemr.User; +import com.iemr.flw.dto.iemr.UserServiceRoleDTO; 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.UserService; import com.iemr.flw.utils.JwtAuthenticationUtil; import com.iemr.flw.utils.JwtUtil; import jakarta.transaction.Transactional; @@ -18,6 +20,7 @@ import java.time.LocalDate; import java.util.Objects; +import java.util.Optional; import org.springframework.data.redis.core.RedisTemplate; @@ -37,6 +40,9 @@ public class AshaProfileImpl implements AshaProfileService { JwtAuthenticationUtil jwtAuthenticationUtil; @Autowired private UserServiceRoleRepo userServiceRoleRepo; + + @Autowired + private UserService userService; private final Logger logger = LoggerFactory.getLogger(AshaProfileImpl.class); @Transactional @@ -45,16 +51,17 @@ public AshaWorker saveEditData(AshaWorker request) { try { Objects.requireNonNull(request, "ASHA worker request must not be null"); - Long id = request.getId(); + Optional ashaWorker = ashaProfileRepo.findByEmployeeId(request.getEmployeeId()); // ---------- CREATE Case ---------- - if (id == null || id == 0) { - // treat id=0 as null (frontend mistake) - if (id != null && id == 0) { - request.setId(null); - } + if (!ashaWorker.isPresent()) { + request.setId(null); - AshaWorker saved = ashaProfileRepo.save(request); + UserServiceRoleDTO userServiceRoleDTO= userService.getUserDetail(request.getEmployeeId()); + if(userServiceRoleDTO!=null){ + request.setName(userServiceRoleDTO.getName()); + } + AshaWorker saved = saveProfile(request); logger.info("Created ASHA Worker: {}", saved.getId()); return saved; } @@ -91,19 +98,12 @@ private AshaWorker getDetails(Integer userID) { 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.setProfileImage(null); ashaWorker.setSupervisorName(""); ashaWorker.setAwwName(""); ashaWorker.setVillage(""); @@ -132,8 +132,104 @@ private AshaWorker getDetails(Integer userID) { throw new RuntimeException("Failed to create ASHA worker profile from user details", e); } } + @Transactional + public AshaWorker saveProfile(AshaWorker request) { + logger.info("Saving ASHA Profile for EmployeeId: {}", request.getEmployeeId()); + + logger.info("Received DOB: {}", request.getDob()); + logger.info("Received Date Of Joining: {}", request.getDateOfJoining()); + + AshaWorker existing = ashaProfileRepo + .findByEmployeeId(request.getEmployeeId()) + .orElse(new AshaWorker()); + + if (isValid(request.getName())) + existing.setName(request.getName()); + + if (isValid(request.getVillage())) + existing.setVillage(request.getVillage()); + + if (request.getEmployeeId() != null) + existing.setEmployeeId(request.getEmployeeId()); + + // Save even if null + existing.setDob(request.getDob()); + + if (isValid(request.getMobileNumber())) + existing.setMobileNumber(request.getMobileNumber()); + + if (isValid(request.getAlternateMobileNumber())) + existing.setAlternateMobileNumber(request.getAlternateMobileNumber()); + + if (isValid(request.getFatherOrSpouseName())) + existing.setFatherOrSpouseName(request.getFatherOrSpouseName()); + + // Save even if null + existing.setDateOfJoining(request.getDateOfJoining()); + + if (isValid(request.getBankAccount())) + existing.setBankAccount(request.getBankAccount()); + + if (isValid(request.getIfsc())) + existing.setIfsc(request.getIfsc()); + + if (request.getPopulationCovered() != null) + existing.setPopulationCovered(request.getPopulationCovered()); + + if (isValid(request.getChoName())) + existing.setChoName(request.getChoName()); + + if (isValid(request.getChoMobile())) + existing.setChoMobile(request.getChoMobile()); + + if (isValid(request.getAwwName())) + existing.setAwwName(request.getAwwName()); - public AshaWorker updateProfile(AshaWorker request) { + if (isValid(request.getAwwMobile())) + existing.setAwwMobile(request.getAwwMobile()); + + if (isValid(request.getAnm1Name())) + existing.setAnm1Name(request.getAnm1Name()); + + if (isValid(request.getAnm1Mobile())) + existing.setAnm1Mobile(request.getAnm1Mobile()); + + if (isValid(request.getAnm2Name())) + existing.setAnm2Name(request.getAnm2Name()); + + if (isValid(request.getAnm2Mobile())) + existing.setAnm2Mobile(request.getAnm2Mobile()); + + if (isValid(request.getAbhaNumber())) + existing.setAbhaNumber(request.getAbhaNumber()); + + if (isValid(request.getAshaHouseholdRegistration())) + existing.setAshaHouseholdRegistration(request.getAshaHouseholdRegistration()); + + if (isValid(request.getAshaFamilyMember())) + existing.setAshaFamilyMember(request.getAshaFamilyMember()); + + if (request.getProviderServiceMapID() != null) + existing.setProviderServiceMapID(request.getProviderServiceMapID()); + + if (request.getProfileImage() != null && request.getProfileImage().length > 0) + 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 ashaProfileRepo.save(existing); + } + + + + 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()); @@ -161,16 +257,20 @@ public AshaWorker updateProfile(AshaWorker request) { 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 (isValidImage(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; + return ashaProfileRepo.save(existing); } private boolean isValid(String value) { return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim()); } + private boolean isValidImage(byte[] value) { + return value != null && value.length > 0; + } + } From 8cec0c40681e325d712322206051475fb1aab63f Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 14:15:19 +0530 Subject: [PATCH 431/450] fix pnc incentive --- .../impl/MaternalHealthServiceImpl.java | 69 +++++++++++-------- 1 file changed, 40 insertions(+), 29 deletions(-) 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 0b14f90ab..e2d0856b9 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -148,7 +148,7 @@ public List getANCVisits(GetBenRequestHandler dto) { .map(anc -> mapper.convertValue(anc, ANCVisitDTO.class)) .collect(Collectors.toList()); } catch (Exception e) { - logger.error("ANC VISIT :---------------------"+e.getMessage()); + logger.error("ANC VISIT :---------------------" + e.getMessage()); } return null; } @@ -170,7 +170,7 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { List ancVisitList = ancVisitRepo.findANCVisitByBenIdAndAncVisitAndIsActive(it.getBenId(), it.getAncVisit(), true); ANCVisit ancVisit = new ANCVisit(); - if(!ancVisitList.isEmpty()){ + if (!ancVisitList.isEmpty()) { ancVisit = ancVisitList.get(0); } logger.info("ANC visit fetch completed"); @@ -448,7 +448,7 @@ public String savePNCVisit(List pncVisitDTOs) { @Override @Transactional public String saveANCVisitQuestions(List dtos, String authorization) throws IEMRException { - Integer userId = jwtUtil.extractUserId(authorization); + Integer userId = jwtUtil.extractUserId(authorization); String userName = userRepo.getUserNamedByUserId(userId); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -595,7 +595,7 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { logger.info("ContraceptionMethod:" + ect.getContraceptionMethod()); // logic for assam - if(stateId.equals(StateCode.AM.getStateCode())){ + if (stateId.equals(StateCode.AM.getStateCode())) { if (ect.getContraceptionMethod() != null && ect.getContraceptionMethod().equals("MALE STERILIZATION")) { IncentiveActivity maleSterilizationActivityAM = @@ -646,33 +646,49 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { } // logic for cg - if(stateId.equals(StateCode.CG.getStateCode())){ + if (stateId.equals(StateCode.CG.getStateCode())) { + if (ect.getAnyContraceptionMethod() != null) { + if (ect.getAnyContraceptionMethod()) { + IncentiveActivity femaleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); - IncentiveActivity PPIUCDActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity PPIUCDActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_PPIUCD", GroupName.ACTIVITY.getDisplayName()); - if (PPIUCDActivityCH != null) { - addIncenticeRecord(ect, userId, PPIUCDActivityCH); - } + IncentiveActivity maleSterilizationActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); - IncentiveActivity femaleSterilizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_FEMALE_STER", GroupName.ACTIVITY.getDisplayName()); + if (PPIUCDActivityCH != null) { + if (ect.getContraceptionMethod().equals("POST PARTUM IUCD (PPIUCD)")) { + addIncenticeRecord(ect, userId, PPIUCDActivityCH); - if (femaleSterilizationActivityCH != null) { - addIncenticeRecord(ect, userId, femaleSterilizationActivityCH); - } + } + } - IncentiveActivity maleSterilizationActivityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup("FP_MALE_STER", GroupName.ACTIVITY.getDisplayName()); - if (maleSterilizationActivityCH != null) { - addIncenticeRecord(ect, userId, maleSterilizationActivityCH); + if (femaleSterilizationActivityCH != null) { + if (ect.getContraceptionMethod().equals("FEMALE STERILIZATION")) { + addIncenticeRecord(ect, userId, femaleSterilizationActivityCH); + + } + } + + + if (maleSterilizationActivityCH != null) { + if (ect.getContraceptionMethod().equals("MALE STERILIZATION")) { + addIncenticeRecord(ect, userId, maleSterilizationActivityCH); + + } + } + } + } - if(ect.getMotherDangerSign() != null + + if (ect.getMotherDangerSign() != null && !ect.getMotherDangerSign().isEmpty() - && ect.getPncPeriod() == 42){ + && ect.getPncPeriod() == 42) { IncentiveActivity highRiskPostpartumCareActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); if (highRiskPostpartumCareActivityCH != null) { @@ -682,8 +698,6 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { } if (ect.getPncPeriod() == 42) { - - IncentiveActivity highRiskPostpartumHealthCareActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); @@ -748,7 +762,7 @@ private void checkAndAddIncentives(List ancList, Integer userId) { IncentiveActivity ancFullActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FULL_ANC", GroupName.MATERNAL_HEALTH.getDisplayName()); IncentiveActivity identifiedHrpActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup("EPMSMA_HRP_IDENTIFIED", GroupName.MATERNAL_HEALTH.getDisplayName()); - IncentiveActivity comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity comprehensiveAbortionActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.MATERNAL_HEALTH.getDisplayName()); IncentiveActivity paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); @@ -761,7 +775,6 @@ private void checkAndAddIncentives(List ancList, Integer userId) { } - if (anc1Activity != null && ancVisit.getAncVisit() != null && ancVisit.getAncVisit() == 1) { recordAncFirstTRIMIncentive(anc1Activity, ancVisit); @@ -791,7 +804,7 @@ private void checkAndAddIncentives(List ancList, Integer userId) { // ✅ State 8 if (stateId.equals(8)) { - IncentiveActivity ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + IncentiveActivity ancFullActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "ANC_FOUR_CHECKUPS_SUPPORT", GroupName.ACTIVITY.getDisplayName()); IncentiveActivity comprehensiveAbortionActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "COMPREHENSIVE_ABORTION_CARE", GroupName.ACTIVITY.getDisplayName()); @@ -803,12 +816,11 @@ private void checkAndAddIncentives(List ancList, Integer userId) { ancList.forEach(ancVisit -> { - if ( ancVisit.getIsAborted()) { + if (ancVisit.getIsAborted()) { recordAncRelatedIncentive(paiucdActivityCH, ancVisit); } - if (ancFullActivityCH != null && ancVisit.getAncVisit() != null && ancVisit.getAncVisit() == 4) { recordAncRelatedIncentive(ancFullActivityCH, ancVisit); @@ -823,7 +835,6 @@ private void checkAndAddIncentives(List ancList, Integer userId) { } - } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { From bfc5c30dc8ba64fe010f2125531625d2bf43a6e3 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 14:23:51 +0530 Subject: [PATCH 432/450] fix pnc incentive --- .../com/iemr/flw/service/impl/MaternalHealthServiceImpl.java | 5 ----- 1 file changed, 5 deletions(-) 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 e2d0856b9..79b9f1da8 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -375,11 +375,6 @@ public List getPNCVisits(GetBenRequestHandler dto) { try { String user = beneficiaryRepo.getUserName(dto.getAshaId()); List pncVisits = pncVisitRepo.getPNCForPW(user); - pncVisits.forEach(pncVisit -> { - checkAndAddAntaraIncentive(pncVisit); - - }); - return pncVisits.stream() .map(pnc -> mapper.convertValue(pnc, PNCVisitDTO.class)) .collect(Collectors.toList()); From 8337eb81757052d6a83fc79cba783c8de127f914 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 14:38:08 +0530 Subject: [PATCH 433/450] fix pnc incentive --- .../impl/MaternalHealthServiceImpl.java | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) 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 79b9f1da8..8bc197088 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -29,6 +29,7 @@ import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @Service @@ -91,6 +92,9 @@ public class MaternalHealthServiceImpl implements MaternalHealthService { public static final List PNC_PERIODS = Arrays.asList("1st Day", "3rd Day", "7th Day", "14th Day", "21st Day", "28th Day", "42nd Day"); + private final ConcurrentHashMap lockMap = new ConcurrentHashMap<>(); + + @Override public String registerPregnantWoman(List pregnantWomanDTOs) { @@ -723,25 +727,35 @@ private void checkAndAddAntaraIncentive(PNCVisit ect) { } + + @Transactional private void addIncenticeRecord(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); + String lockKey = antaraActivity.getId() + "_" + ect.getBenId() + "_" + ect.getPncDate(); + + Object lock = lockMap.computeIfAbsent(lockKey, k -> new Object()); + + synchronized (lock) { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getPncDate(), ect.getBenId()); + + 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); + } } + + lockMap.remove(lockKey, lock); } From 80132be3e1b5d047cf005b8a6139362f9ee4e99e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 21:57:14 +0530 Subject: [PATCH 434/450] fix vhnd incentive incentive --- .../iemr/flw/service/impl/CampaignServiceImpl.java | 2 +- .../flw/service/impl/DiseaseControlServiceImpl.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index 1d1988d4e..a55f1ff4f 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -449,7 +449,7 @@ private List parseBase64Json(String jsonString) { private void checkMonthlyPulsePolioIncentive(Integer ashaId,LocalDate startDate,LocalDate endDate) { - IncentiveActivity CHILD_MOBILIZATION_SESSIONS = incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_MOBILIZATION_SESSIONS", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity CHILD_MOBILIZATION_SESSIONS = incentivesRepo.findIncentiveMasterByNameAndGroup("PULSE_POLIO_SUPPORT", GroupName.ACTIVITY.getDisplayName()); if (CHILD_MOBILIZATION_SESSIONS != null) { addAshaIncentiveRecord(CHILD_MOBILIZATION_SESSIONS, ashaId,startDate,endDate); } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index feb02d9ef..c514881fb 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -305,8 +305,8 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForIdentificationLeprosy( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { @@ -322,8 +322,8 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { @@ -338,8 +338,8 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { From b248bc887603cb29538d1b1423008369c8bff38d Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 22:00:47 +0530 Subject: [PATCH 435/450] fix vhnd incentive incentive --- .../iemr/flw/service/MaaMeetingService.java | 27 ++++++++++--------- .../impl/TBConfirmedCaseServiceImpl.java | 1 - 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/MaaMeetingService.java b/src/main/java/com/iemr/flw/service/MaaMeetingService.java index d8fdd82b5..cfe6aa204 100644 --- a/src/main/java/com/iemr/flw/service/MaaMeetingService.java +++ b/src/main/java/com/iemr/flw/service/MaaMeetingService.java @@ -239,20 +239,23 @@ record = new IncentiveActivityRecord(); record.setBenId(0L); record.setAshaId(meeting.getAshaId()); record.setAmount(Long.valueOf(incentiveActivity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); - if (meeting.getMeetingImagesJson() != null) { - record.setIsEligible(true); - recordRepo.save(record); - - } else { - record.setIsEligible(false); - IncentiveActivityRecord activityRecord = recordRepo.save(record); - if (activityRecord != null) { - updatePendingActivity(meeting.getAshaId(), meeting.getId(), activityRecord.getId(), incentiveActivity.getId()); - - } - } +// if (meeting.getMeetingImagesJson() != null) { +// record.setIsEligible(true); +// recordRepo.save(record); +// +// } else { +// record.setIsEligible(false); +// IncentiveActivityRecord activityRecord = recordRepo.save(record); +// if (activityRecord != null) { +// updatePendingActivity(meeting.getAshaId(), meeting.getId(), activityRecord.getId(), incentiveActivity.getId()); +// +// } +// +// } } } diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 92493c751..8e7542a28 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -66,7 +66,6 @@ public String save(List request, String authorisation) throw entity.setReasonForNotCompleting(dto.getReasonForNotCompleting()); if(entity!=null){ repository.save(entity); - checkIncentive(entity); } From 21b12d3ce7584d7d52eab5e143b7f083cb655128 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 22:01:11 +0530 Subject: [PATCH 436/450] fix vhnd incentive error --- src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java index adacdb1b8..8310eb65a 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -70,4 +70,5 @@ public class TBConfirmedCase { @Column(name = "updated_at") private LocalDate updatedAt; + } From e97a130f250291940bcd5e038ff70e51fffc97da Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 22:17:36 +0530 Subject: [PATCH 437/450] fix vhnd incentive error --- .../flw/service/impl/DiseaseControlServiceImpl.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index c514881fb..7850c9892 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -453,8 +453,8 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForIdentificationLeprosy( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), userId); if (incentiveActivityRecord != null) { @@ -470,8 +470,8 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), userId); if (incentiveActivityRecord != null) { @@ -486,8 +486,8 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), - screeningLeprosy.getTreatmentEndDate(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), userId); if (incentiveActivityRecord != null) { From 6eb2a934cd89fb5ca7f2d0c8872b93e41954f013 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 22:28:11 +0530 Subject: [PATCH 438/450] fix vhnd incentive error --- .../impl/VillageLevelFormServiceImpl.java | 83 ++++++++++++++++--- 1 file changed, 73 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 4519bc623..01a47dccd 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -24,7 +24,6 @@ */ 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; @@ -150,12 +149,8 @@ private Boolean saveVhncFormData(VhncFormDTO vhncFormDTO, Integer userID) { vhncForm.setFormType("VHNC"); vhncFormRepo.save(vhncForm); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - LocalDate localDate = LocalDate.parse(vhncForm.getVhncDate(), formatter); - Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - incentiveLogicService.incentiveForAttendingVhsnc(0L,date,date,Math.toIntExact(vhncForm.getUserId())); + checkVhncIncentive(vhncForm.getCreatedDate(),Math.toIntExact(vhncForm.getUserId())); return true; } @@ -286,18 +281,86 @@ private Boolean saveVhndFormData(VHNDFormDTO vhndFormDTO, Integer userID) { : null); vhndForm.setFormType("VHND"); vhndRepo.save(vhndForm); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - LocalDate localDate = LocalDate.parse(vhndForm.getVhndDate(), formatter); - Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - incentiveLogicService.incentiveForVhndMeeting(0L,date,date,vhndForm.getUserId()); + checkVhndIncentive(vhndForm.getCreatedDate(),vhndForm.getUserId()); return true; } + private void checkVhndIncentive(Timestamp startTimestamp, Integer userId){ + + try { + IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup("VHND_PARTICIPATION", GroupName.ACTIVITY.getDisplayName()); + if(activity!=null){ + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), startTimestamp, 0L,userId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(startTimestamp); + record.setCreatedBy(userRepo.getUserNamedByUserId(userId)); + record.setStartDate(startTimestamp); + record.setEndDate(startTimestamp); + record.setUpdatedDate(startTimestamp); + record.setUpdatedBy(userRepo.getUserNamedByUserId(userId)); + record.setAshaId(userId); + record.setBenId(0L); + record.setAmount(Long.valueOf(activity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + + } + } + + + + } catch (Exception e) { + logger.error("Process Incentive Exception: ", e); + + + } + + } + + + private void checkVhncIncentive(Timestamp startTimestamp, Integer userId){ + + try { + IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup("VHSNC_MEETING", GroupName.ACTIVITY.getDisplayName()); + if(activity!=null){ + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), startTimestamp, 0L,userId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(startTimestamp); + record.setCreatedBy(userRepo.getUserNamedByUserId(userId)); + record.setStartDate(startTimestamp); + record.setEndDate(startTimestamp); + record.setUpdatedDate(startTimestamp); + record.setUpdatedBy(userRepo.getUserNamedByUserId(userId)); + record.setAshaId(userId); + record.setBenId(0L); + record.setAmount(Long.valueOf(activity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + + } + } + + + + } catch (Exception e) { + logger.error("Process Incentive Exception: ", e); + + + } + + } + @Override public List getAll(GetVillageLevelRequestHandler getVillageLevelRequestHandler) { From 755ab5f0970b71d87b3756a96e095d7a848bd5ff Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 22:31:27 +0530 Subject: [PATCH 439/450] fix vhnd incentive error --- .../service/impl/DiseaseControlServiceImpl.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 7850c9892..ccfa5d17b 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -322,8 +322,8 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { @@ -338,8 +338,8 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), diseaseControlDTO.getUserId()); if (incentiveActivityRecord != null) { @@ -470,8 +470,8 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), userId); if (incentiveActivityRecord != null) { @@ -486,8 +486,8 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), userId); if (incentiveActivityRecord != null) { From 7a381cd68a0a6bc37326618fb52159d058640e71 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 23:03:15 +0530 Subject: [PATCH 440/450] fix cluster meeting incentive error --- .../impl/DiseaseControlServiceImpl.java | 8 ++-- .../impl/VillageLevelFormServiceImpl.java | 41 ++++++++++++++++--- 2 files changed, 40 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index ccfa5d17b..0a762dc20 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -322,7 +322,7 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), screeningLeprosy.getTreatmentEndDate(), diseaseControlDTO.getUserId()); @@ -338,7 +338,7 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), screeningLeprosy.getTreatmentEndDate(), diseaseControlDTO.getUserId()); @@ -470,7 +470,7 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), screeningLeprosy.getTreatmentEndDate(), userId); @@ -486,7 +486,7 @@ private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId) IncentiveActivityRecord incentiveActivityRecord = incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentStartDate(), + screeningLeprosy.getTreatmentEndDate(), screeningLeprosy.getTreatmentEndDate(), userId); diff --git a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java index 01a47dccd..7f1104d1d 100644 --- a/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/VillageLevelFormServiceImpl.java @@ -170,12 +170,8 @@ private Boolean savePhcForm(PhcReviewMeetingFormDTO dto, Integer userID) { phcReviewForm.setImage2(dto.getImage2()); phcReviewForm.setFormType("PHC"); phcReviewFormRepo.save(phcReviewForm); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); - - LocalDate localDate = LocalDate.parse(phcReviewForm.getPhcReviewDate(), formatter); - Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); - incentiveLogicService.incentiveForClusterMeeting(0L,date,date,Math.toIntExact(phcReviewForm.getUserId())); + checkPhcMeetingIncentive(phcReviewForm.getCreatedDate(),Math.toIntExact(phcReviewForm.getUserId())); return true; } @@ -317,6 +313,41 @@ record = new IncentiveActivityRecord(); + } catch (Exception e) { + logger.error("Process Incentive Exception: ", e); + + + } + + } + + private void checkPhcMeetingIncentive(Timestamp startTimestamp, Integer userId){ + + try { + IncentiveActivity activity = incentivesRepo.findIncentiveMasterByNameAndGroup("CLUSTER_MEETING", GroupName.ACTIVITY.getDisplayName()); + if(activity!=null){ + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), startTimestamp, 0L,userId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(startTimestamp); + record.setCreatedBy(userRepo.getUserNamedByUserId(userId)); + record.setStartDate(startTimestamp); + record.setEndDate(startTimestamp); + record.setUpdatedDate(startTimestamp); + record.setUpdatedBy(userRepo.getUserNamedByUserId(userId)); + record.setAshaId(userId); + record.setBenId(0L); + record.setAmount(Long.valueOf(activity.getRate())); + record.setIsEligible(true); + recordRepo.save(record); + + } + } + + + } catch (Exception e) { logger.error("Process Incentive Exception: ", e); From 19c3218d8005437b1fbaf942bcd04a07e6dad96e Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Sat, 4 Jul 2026 23:22:39 +0530 Subject: [PATCH 441/450] fix cluster meeting incentive error --- .../impl/DiseaseControlServiceImpl.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 0a762dc20..fe1861332 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1475,8 +1475,9 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, Integer stateId = userService.getUserDetail(ashaId).getStateId(); IncentiveActivity incentiveActivity = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.NCD.getDisplayName()); IncentiveActivity incentiveActivityCG = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_FOLLOWUP_TREATMENT", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity incentiveActivityCGForNCDnewPatient = incentivesRepo.findIncentiveMasterByNameAndGroup("NCD_NEW_PATIENT_MEDICATION_SUPPORT", GroupName.ACTIVITY.getDisplayName()); logger.info("incentiveActivity:" + incentiveActivity.getId()); - if (incentiveActivity != null) { + if (chronicDiseaseVisitEntity.getFollowUpNo() != null && chronicDiseaseVisitEntity.getCreatedDate() != null && chronicDiseaseVisitEntity.getDiagnosisCodes() != null) { @@ -1487,6 +1488,7 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, "Cancer" ); + List diagnosisList = Arrays.asList( chronicDiseaseVisitEntity.getDiagnosisCodes().split(",") ); @@ -1494,7 +1496,18 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, boolean matchFound = diagnosisList.stream() .map(String::trim) .anyMatch(targetDiseases::contains); - + if(matchFound & Integer.valueOf(0).equals(chronicDiseaseVisitEntity.getFollowUpNo()) ){ + LocalDateTime localDateTime = chronicDiseaseVisitEntity.getTreatmentStartDate().atStartOfDay(); + + Timestamp treatmentStartDate = Timestamp.valueOf(localDateTime); + addNCDFolloupIncentiveRecord( + incentiveActivityCGForNCDnewPatient, + ashaId, + chronicDiseaseVisitEntity.getBenId(), + treatmentStartDate, + userName + ); + } if (matchFound && Integer.valueOf(6).equals(chronicDiseaseVisitEntity.getFollowUpNo())) { LocalDateTime localDateTime = chronicDiseaseVisitEntity.getFollowUpDate().atStartOfDay(); @@ -1520,7 +1533,7 @@ private void checkIncentive(ChronicDiseaseVisitEntity chronicDiseaseVisitEntity, } } - } + } From b44492715f70ff0151591f4006290db69818b358 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Jul 2026 11:31:10 +0530 Subject: [PATCH 442/450] fix tb incentive --- .../repo/iemr/DiseaseLeprosyRepository.java | 2 + .../repo/iemr/LeprosyFollowUpRepository.java | 2 +- .../impl/DiseaseControlServiceImpl.java | 162 ++++-------------- .../impl/TBConfirmedCaseServiceImpl.java | 13 +- 4 files changed, 45 insertions(+), 134 deletions(-) diff --git a/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java b/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java index 567b62a53..36873319e 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/DiseaseLeprosyRepository.java @@ -16,4 +16,6 @@ public interface DiseaseLeprosyRepository extends JpaRepository getByCreatedBy(@Param("createdBy") String createdBy); + + } \ No newline at end of file diff --git a/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java b/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java index 4227fb3a2..a2b38f555 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/LeprosyFollowUpRepository.java @@ -12,7 +12,7 @@ @Repository public interface LeprosyFollowUpRepository extends JpaRepository { - Optional findByBenId(Long benId); + List findByBenId(Long benId); // Custom queries can be added here if needed @Query("SELECT s FROM LeprosyFollowUp s WHERE s.createdBy = :createdBy") diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index fe1861332..c413dca8b 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -316,44 +316,6 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { logger.info("Incentive not created"); } } - if (screeningLeprosy.getIsConfirmed()) { - if(screeningLeprosy.getTypeOfLeprosy()!=null){ - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentEndDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentEndDate(), - screeningLeprosy.getTreatmentEndDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - - } - } - - - } return "Data add successfully"; @@ -391,38 +353,46 @@ private LeprosyFollowUp saveLeprosyFollowUpData(LeprosyFollowUpDTO data) { entity.setModifiedBy(data.getModifiedBy()); entity.setLastModDate( data.getLastModDate() != null ? data.getLastModDate() : new Timestamp(System.currentTimeMillis())); - + if(!leprosyFollowUpRepository.findByBenId(entity.getBenId()).isEmpty()){ + if(leprosyFollowUpRepository.findByBenId(entity.getBenId()).size()>=6 && leprosyFollowUpRepository.findByBenId(entity.getBenId()).size()<=12){ + Integer userId = userRepo.getUserIdByName(entity.getCreatedBy()); + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( + entity.getBenId(), + entity.getTreatmentEndDate(), + entity.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } + } + + if(!leprosyFollowUpRepository.findByBenId(entity.getBenId()).isEmpty()){ + if(leprosyFollowUpRepository.findByBenId(entity.getBenId()).size()>=12){ + Integer userId = userRepo.getUserIdByName(entity.getCreatedBy()); + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( + entity.getBenId(), + entity.getTreatmentEndDate(), + entity.getTreatmentEndDate(), + userId); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); + } + } + } 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) @@ -443,68 +413,10 @@ public List getAllLeprosyData(String createdBy) { List dtos = new ArrayList<>(); leprosyList.forEach(leprosy -> { dtos.add(modelMapper.map(leprosy, DiseaseGetLeprosyDTO.class)); - checkAndIncentive(leprosy,leprosy.getUserId()); }); return dtos; } - private void checkAndIncentive(ScreeningLeprosy screeningLeprosy,Integer userId){ - if(screeningLeprosy.getIsConfirmed()){ - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForIdentificationLeprosy( - screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - } - if (screeningLeprosy.getIsConfirmed()) { - if(screeningLeprosy.getTypeOfLeprosy()!=null){ - if (screeningLeprosy.getTypeOfLeprosy().equals("PB (Paucibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyPaucibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentEndDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - - } - if (screeningLeprosy.getTypeOfLeprosy().equals("MB (Multibacillary)")) { - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForLeprosyMultibacillaryConfirmed( - screeningLeprosy.getBenId(), - screeningLeprosy.getTreatmentEndDate(), - screeningLeprosy.getTreatmentEndDate(), - userId); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } - - } - } - - - - } - } - @Override public List getAllLeprosyFollowUpData(String createdBy) { logger.info("Fetching leprosy data for createdBy: " + createdBy); diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index 8e7542a28..e89928def 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -71,9 +71,6 @@ public String save(List request, String authorisation) throw } } - - - response.setResponse("TB Confirmed case saved successfully"); } else { @@ -95,21 +92,21 @@ private void checkIncentive(TBConfirmedCase entity){ || "Longer Regimen (18–24 Months)".equalsIgnoreCase(regimen); if (Boolean.TRUE.equals(entity.getTreatmentCompleted()) - && entity.getActualTreatmentCompletionDate() != null) { + && entity.getExpectedTreatmentCompletionDate() != null) { if (isDrTb) { incentiveLogicService.incentiveForTbFollowUpIsDrTb( entity.getBenId(), - Timestamp.valueOf(entity.getTreatmentStartDate().atStartOfDay()), - Timestamp.valueOf(entity.getActualTreatmentCompletionDate().atStartOfDay()), + Timestamp.valueOf(entity.getExpectedTreatmentCompletionDate().atStartOfDay()), + Timestamp.valueOf(entity.getExpectedTreatmentCompletionDate().atStartOfDay()), entity.getUserId() ); } else { incentiveLogicService.incentiveForTbFollowUp( entity.getBenId(), - Timestamp.valueOf(entity.getTreatmentStartDate().atStartOfDay()), - Timestamp.valueOf(entity.getActualTreatmentCompletionDate().atStartOfDay()), + Timestamp.valueOf(entity.getExpectedTreatmentCompletionDate().atStartOfDay()), + Timestamp.valueOf(entity.getExpectedTreatmentCompletionDate().atStartOfDay()), entity.getUserId() ); From 733796c9b06a44bca5cf2ea797ec8f1076090e82 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Mon, 6 Jul 2026 12:24:30 +0530 Subject: [PATCH 443/450] fix slide test incentive --- .../flw/service/impl/DiseaseControlServiceImpl.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index c413dca8b..2746fa785 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1306,16 +1306,19 @@ record = new IncentiveActivityRecord(); private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningMalaria diseaseScreening) { try { + Timestamp screeningTimestamp = diseaseScreening.getScreeningDate() != null + ? new Timestamp(diseaseScreening.getScreeningDate().getTime()) + : null; IncentiveActivityRecord record = recordRepo .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(diseaseScreeningActivity.getId()); - record.setCreatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setCreatedDate(screeningTimestamp); record.setCreatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); - record.setStartDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setEndDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); - record.setUpdatedDate(Timestamp.valueOf(diseaseScreening.getCreatedDate().toString())); + record.setStartDate(screeningTimestamp); + record.setEndDate(screeningTimestamp); + record.setUpdatedDate(screeningTimestamp); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setUpdatedBy(userService.getUserDetail(diseaseScreening.getUserId()).getUserName()); record.setBenId(diseaseScreening.getBenId().longValue()); From fa4b66278bf1c8663b85e02354a87691d5d5aecf Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Wed, 8 Jul 2026 16:30:38 +0530 Subject: [PATCH 444/450] Fix/pb mb incentive issue 3.8.2 (#271) * fix duplicate incentive issue * fix duplicate incentive issue * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix child after 2 year gap after marriage * fix hbyc incentive logic * fix hbyc incentive logic * fix hbyc incentive logic * optmiz query for incentive logic for hbnc --- .../flw/repo/identity/BeneficiaryRepo.java | 2 +- .../com/iemr/flw/repo/iemr/HbncVisitRepo.java | 5 +- .../flw/repo/iemr/IncentiveRecordRepo.java | 56 ++- .../impl/AdolescentHealthServiceImpl.java | 4 +- .../flw/service/impl/CampaignServiceImpl.java | 6 +- .../service/impl/ChildCareServiceImpl.java | 190 ++++---- .../flw/service/impl/CoupleServiceImpl.java | 57 ++- .../service/impl/DeathReportsServiceImpl.java | 46 +- .../impl/DeliveryOutcomeServiceImpl.java | 237 +++++++--- .../impl/DiseaseControlServiceImpl.java | 6 +- .../impl/IFAFormSubmissionServiceImpl.java | 2 +- .../flw/service/impl/IncentiveLogicImpl.java | 6 +- .../service/impl/IncentiveServiceImpl.java | 410 +++++++----------- .../flw/service/impl/InfantServiceImpl.java | 2 +- .../impl/MaternalHealthServiceImpl.java | 53 ++- 15 files changed, 571 insertions(+), 511 deletions(-) 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 b3988c3eb..e4ce22f04 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -26,7 +26,7 @@ public interface BeneficiaryRepo extends JpaRepository findById(Long benID); List findByHouseoldId(Long houseHoldId); - Optional findByBenficieryid(Long benID); + List findByBenficieryid(Long benID); @Query(value = "SELECT beneficiaryRegID FROM db_identity.i_beneficiarydetails_rmnch WHERE BeneficiaryId = :benId", nativeQuery = true) Long getBenRegIdFromBenId(@Param("benId") Long benId); 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 655c05471..cbc7f568d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/HbncVisitRepo.java @@ -1,6 +1,8 @@ package com.iemr.flw.repo.iemr; import com.iemr.flw.domain.iemr.HbncVisit; +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.data.repository.query.Param; @@ -20,6 +22,5 @@ public interface HbncVisitRepo extends JpaRepository { HbncVisit findByBeneficiaryIdAndVisit_day(@Param("beneficiaryId") Long beneficiaryId, @Param("visitDay") String visitDay); - List findByAshaId(Integer ashaId); - + Page findByAshaId(Integer ashaId, Pageable pageable); } 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 11710e4c1..8c21f0e9f 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/IncentiveRecordRepo.java @@ -3,6 +3,8 @@ import com.iemr.flw.domain.iemr.IncentiveActivityRecord; import jakarta.persistence.Column; +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.Modifying; import org.springframework.data.jpa.repository.Query; @@ -18,41 +20,51 @@ public interface IncentiveRecordRepo extends JpaRepository { @Query(value = """ - SELECT * - FROM db_iemr.incentive_activity_record r - WHERE r.activity_id = :id - AND r.ben_id = :benId - AND MONTH(r.created_date) = MONTH(:createdDate) - AND YEAR(r.created_date) = YEAR(:createdDate) - LIMIT 1 - """, nativeQuery = true) - IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId(@Param("id") Long id, @Param("createdDate") Timestamp createdDate, @Param("benId") Long benId); + SELECT * + FROM db_iemr.incentive_activity_record r + WHERE r.activity_id = :id + AND r.ben_id = :benId + AND r.asha_id = :ashaId + AND MONTH(r.start_date) = MONTH(:createdDate) + AND YEAR(r.start_date) = YEAR(:createdDate) + LIMIT 1 + """, nativeQuery = true) + IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( + @Param("id") Long id, + @Param("createdDate") Timestamp createdDate, + @Param("benId") Long benId, + @Param("ashaId") Integer ashaId); Optional findById(Long id); - @Query("select record from IncentiveActivityRecord record where record.activityId = :id and record.createdDate = :createdDate and record.benId = :benId and record.ashaId = :ashaId") - IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId(@Param("id") Long id, @Param("createdDate") Timestamp createdDate, @Param("benId") Long benId, @Param("ashaId") Integer ashaId); - - - @Query("SELECT record FROM IncentiveActivityRecord record " + - "WHERE record.activityId = :id " + - "AND record.createdDate BETWEEN :startDate AND :endDate " + - "AND record.benId = :benId " + // ← space added here - "AND record.ashaId = :ashaId") + @Query(value = """ + SELECT * + FROM incentive_activity_record + WHERE activity_id = :activityId + AND ben_id = :benId + AND asha_id = :ashaId + AND created_date >= :startOfMonth + AND created_date < :startOfNextMonth + ORDER BY created_date DESC + LIMIT 1 + """, nativeQuery = true) IncentiveActivityRecord findRecordByActivityIdCreatedDateBenId( - @Param("id") Long id, - @Param("startDate") Timestamp startDate, - @Param("endDate") Timestamp endDate, + @Param("activityId") Long activityId, @Param("benId") Long benId, - @Param("ashaId") Integer ashaId + @Param("ashaId") Integer ashaId, + @Param("startOfMonth") Timestamp startOfMonth, + @Param("startOfNextMonth") Timestamp startOfNextMonth ); @Query("select record from IncentiveActivityRecord record where record.ashaId = :ashaId and record.startDate >= :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 DISTINCT record FROM IncentiveActivityRecord record WHERE record.ashaId = :ashaId") + Page findRecordsByAsha(@Param("ashaId") Integer ashaId, Pageable pageable); + @Query("SELECT DISTINCT record FROM IncentiveActivityRecord record WHERE record.ashaId = :ashaId") List findRecordsByAsha(@Param("ashaId") Integer ashaId); diff --git a/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java index 43986a8c9..8be992afe 100644 --- a/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AdolescentHealthServiceImpl.java @@ -126,7 +126,7 @@ private void checkAndAddIncentives(AdolescentHealth adolescentHealth) { if (sellingSanitaryActivity != null) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(sellingSanitaryActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue()); + .findRecordByActivityIdCreatedDateBenId(sellingSanitaryActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue(),adolescentHealth.getUserId()); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(sellingSanitaryActivity.getId()); @@ -151,7 +151,7 @@ record = new IncentiveActivityRecord(); if (mobilizingADHActivity != null) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(mobilizingADHActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue()); + .findRecordByActivityIdCreatedDateBenId(mobilizingADHActivity.getId(), adolescentHealth.getCreatedDate(), adolescentHealth.getBenId().longValue(),adolescentHealth.getUserId()); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(mobilizingADHActivity.getId()); diff --git a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java index a55f1ff4f..f9c076327 100644 --- a/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CampaignServiceImpl.java @@ -480,10 +480,10 @@ private void addAshaIncentiveRecord(IncentiveActivity incentiveActivity, Integer IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), - startOfMonth, - endOfMonth, 0L, - ashaId + ashaId, + startOfMonth, + endOfMonth ); 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 f452916cf..01acddf8e 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -21,6 +21,10 @@ import org.slf4j.Logger; 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.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @@ -229,51 +233,63 @@ public List getHbycRecords(GetBenRequestHandler dto) { @Override public List getHBNCDetails(GetBenRequestHandler dto) { List result = new ArrayList<>(); + int page = 0; + int size = 20; + + Page visitPage; try { - List hbncVisits = hbncVisitRepo.findByAshaId(dto.getAshaId()); + do { + Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending()); - 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() + visitPage = hbncVisitRepo.findByAshaId(dto.getAshaId(), pageable); - // Convert all fields to Map - Map fields = new HashMap<>(); - if(visit.getVisit_day()!=null){ - addIfValid(fields, "visit_day", visit.getVisit_day()); + List hbncVisits = visitPage.getContent(); + + 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() + + // Convert all fields to Map + Map fields = new HashMap<>(); + if(visit.getVisit_day()!=null){ + 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()); + + // Add more fields as required + + responseDTO.setFields(fields); + result.add(responseDTO); } - 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()); - - // Add more fields as required - - responseDTO.setFields(fields); - result.add(responseDTO); + page++; checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); - } + }while (visitPage.hasNext()); } catch (Exception e) { logger.error("Error in getHBNCDetails: ", e); @@ -826,55 +842,58 @@ private void checkAndAddOrdDistributionIncentive(List orsDistri 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()); + if(!hbycList.isEmpty()){ + Integer userId = hbycList.get(0).getUserId(); + Integer stateId = userService.getUserDetail(userId).getStateId(); + 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"); + IncentiveActivity hbyncLactatingIronPacketActivityCH = + incentivesRepo.findIncentiveMasterByNameAndGroup("LACTATING_MOTHERS_HOME_VISIT", GroupName.ACTIVITY.getDisplayName()); - 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()); - } + hbycList.forEach(hbyc -> { + Set eligibleHbycVisits = Set.of("3 Months", "6 Months", "9 Months", "12 Months", "15 Months"); + if(stateId.equals(StateCode.AM.getStateCode())){ + if (hbyncVisitActivity != null && eligibleHbycVisits.contains(hbyc.getVisit_day())) { + createIncentiveRecordforHbyncVisit(hbyc, hbyc.getBeneficiaryId(), hbyncVisitActivity, hbyc.getCreated_by()); + } + } + if(stateId.equals(StateCode.CG.getStateCode())){ + if (hbync15MonethVisitActivityCH != null && eligibleHbycVisits.contains(hbyc.getVisit_day())) { + createIncentiveRecordforHbyncVisit(hbyc, hbyc.getBeneficiaryId(), hbync15MonethVisitActivityCH, hbyc.getCreated_by()); + } + if(hbyc.getIfa_given() && eligibleHbycVisits.contains(hbyc.getVisit_day())){ + if(hbyncLactatingIronPacketActivityCH!=null){ + createIncentiveRecordforHbyncVisit(hbyc, hbyc.getBeneficiaryId(), hbyncLactatingIronPacketActivityCH, hbyc.getCreated_by()); - if (hbyncOrsPacketActivityCH != null) { - if (hbyc.getOrs_given()) { - createIncentiveRecordforHbyncOrsDistribution(hbyc, hbyc.getBeneficiaryId(), hbyncOrsPacketActivityCH, hbyc.getCreated_by()); + } + } } - } - }); + + + }); + } + } @@ -1158,7 +1177,7 @@ private void checkAndAddIncentives(List vaccinationList) { private void createIncentiveRecord(ChildVaccination vaccination, Long benId, Integer userId, IncentiveActivity immunizationActivity) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), vaccination.getCreatedDate(), benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), vaccination.getCreatedDate(), benId,userId); if (record == null) { record = new IncentiveActivityRecord(); @@ -1180,7 +1199,7 @@ private void createIncentiveRecordforHbncVisit(HbncVisit hbncVisit, Long benId, logger.info("RecordIncentive" + activityName); IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), hbncVisit.getCreatedDate(), benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), hbncVisit.getCreatedDate(), benId,hbncVisit.getAshaId()); if (record == null) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @@ -1267,7 +1286,7 @@ private void createIncentiveRecordforHbyncVisit(HbycChildVisit data, Long benId, // Convert LocalDate to Timestamp (00:00:00 by default) Timestamp visitDate = Timestamp.valueOf(localDate.atStartOfDay()); IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId,data.getUserId()); if (record == null) { @@ -1288,41 +1307,12 @@ record = new IncentiveActivityRecord(); } - 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(data.getUserId()); - 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); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), visitDate, benId,data.getUserId()); double packets = Double.parseDouble(data.getNumOrsPackets()); double rate = immunizationActivity.getRate(); @@ -1336,7 +1326,7 @@ record = new IncentiveActivityRecord(); record.setEndDate(visitDate); record.setUpdatedDate(visitDate); record.setUpdatedBy(createdBy); - record.setBenId(benId); + record.setBenId(0L); record.setAshaId(data.getUserId()); if (isCH) { record.setAmount((long) rate); @@ -1359,7 +1349,7 @@ private void createIncentiveRecordforSamReferalToNrc(SamVisit data, Long benId, // Convert to LocalDate Timestamp visitDate = Timestamp.valueOf(data.getVisitDate().atStartOfDay()); IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), visitDate, benId); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), visitDate, benId,data.getUserId()); if (record == null) { 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 e6aca951b..e22147afa 100644 --- a/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/CoupleServiceImpl.java @@ -30,6 +30,7 @@ import java.util.Arrays; import java.util.Base64; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @Service @@ -60,6 +61,8 @@ public class CoupleServiceImpl implements CoupleService { private BeneficiaryRepo beneficiaryRepo; private final Logger logger = LoggerFactory.getLogger(CoupleServiceImpl.class); + private final ConcurrentHashMap lockMap = new ConcurrentHashMap<>(); + @Override @@ -259,7 +262,7 @@ private void checkIncentiveForChildGap(Integer stateId, String userName,List new Object()); + synchronized (lock){ + if (activity != null) { + Integer userId = userRepo.getUserIdByName(eligibleCoupleDTO.getCreatedBy()); + + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(activity.getId(), eligibleCoupleDTO.getCreatedDate(), eligibleCoupleDTO.getBenId(),userId); + if (record == null) { + record = new IncentiveActivityRecord(); + record.setActivityId(activity.getId()); + record.setCreatedDate(eligibleCoupleDTO.getCreatedDate()); + record.setCreatedBy(eligibleCoupleDTO.getCreatedBy()); + record.setStartDate(eligibleCoupleDTO.getCreatedDate()); + record.setEndDate(eligibleCoupleDTO.getCreatedDate()); + record.setUpdatedDate(eligibleCoupleDTO.getCreatedDate()); + record.setUpdatedBy(eligibleCoupleDTO.getCreatedBy()); + record.setBenId(eligibleCoupleDTO.getBenId()); + record.setAshaId(userId); + record.setAmount(Long.valueOf(activity.getRate())); + recordRepo.save(record); + } } } + lockMap.remove(lockKey, lock); + + + } @Override @@ -572,7 +585,7 @@ private void checkAndAddAntaraIncentive(EligibleCoupleTracking ect) { private void addIncenticeRecord(EligibleCoupleTracking ect, Integer userId, IncentiveActivity antaraActivity) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getCreatedDate(), ect.getBenId()); + .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getVisitDate(), ect.getBenId(),userId); // get bene details if (record == null) { 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 2bd0ead83..b7eee7dd0 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeathReportsServiceImpl.java @@ -216,17 +216,21 @@ public List getMdsrRecords(GetBenRequestHandler dto) { } private void checkAndAddIncentives(List cdrList) { + if(!cdrList.isEmpty()){ + Integer userId = userRepo.getUserIdByName(cdrList.get(0).getCreatedBy()); + cdrList.forEach(cdr -> { + IncentiveActivity immunizationActivity = + incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); + createIncentiveRecord(cdr, cdr.getBenId(), userId, immunizationActivity); + if(immunizationActivity!=null){ + createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); + + } + }); + + } - cdrList.forEach(cdr -> { - Integer userId = userRepo.getUserIdByName(cdr.getCreatedBy()); - IncentiveActivity immunizationActivity = - incentivesRepo.findIncentiveMasterByNameAndGroup("CHILD_DEATH_REPORTING", GroupName.CHILD_HEALTH.getDisplayName()); - createIncentiveRecord(cdr, cdr.getBenId(), userId, immunizationActivity); - if(immunizationActivity!=null){ - createIncentiveRecord(cdr,cdr.getBenId(),userId,immunizationActivity); - } - }); } @@ -263,7 +267,7 @@ private void checkAndAddIncentivesMdsr(List mdsrList) { private void createIncentiveRecord(CDR cdr, Long benId, Integer userId, IncentiveActivity immunizationActivity) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), cdr.getCreatedDate(), benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), cdr.getCreatedDate(), benId,userId); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(immunizationActivity.getId()); @@ -276,32 +280,16 @@ record = new IncentiveActivityRecord(); record.setBenId(benId); record.setAshaId(userId); record.setAmount(Long.valueOf(immunizationActivity.getRate())); - if (userRepo.getUserRole(userId).get(0).getStateId() == StateCode.AM.getStateCode()) { - if (cdr.getDeathCertImage1() != null && cdr.getCdrImage() != null && cdr.getCdrImage2() != null && cdr.getDeathCertImage2() != null) { - record.setIsEligible(true); - recordRepo.save(record); + record.setIsEligible(true); + recordRepo.save(record); - } else { - record.setIsEligible(false); - IncentiveActivityRecord incentiveActivityRecord = recordRepo.save(record); - if (incentiveActivityRecord == null) { - recordRepo.save(record); - pendindDocService.updatePendingActivity(userId, cdr.getId(), record.getId(), immunizationActivity.getId()); - - } - - } - } else { - recordRepo.save(record); - - } } } private void createIncentiveRecord(MDSR mdsr, Long benId, Integer userId, IncentiveActivity immunizationActivity) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), mdsr.getCreatedDate(), benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), mdsr.getCreatedDate(), benId,userId); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(immunizationActivity.getId()); 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 3ccd99736..3170deba0 100644 --- a/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DeliveryOutcomeServiceImpl.java @@ -11,6 +11,7 @@ import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.DeliveryOutcomeDTO; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.masterEnum.StateCode; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.identity.HouseHoldRepo; import com.iemr.flw.repo.iemr.DeliveryOutcomeRepo; @@ -18,6 +19,7 @@ import com.iemr.flw.repo.iemr.IncentivesRepo; import com.iemr.flw.repo.iemr.UserServiceRoleRepo; import com.iemr.flw.service.DeliveryOutcomeService; +import com.iemr.flw.service.UserService; import jakarta.annotation.PostConstruct; import org.apache.commons.lang3.Validate; import org.modelmapper.ModelMapper; @@ -27,6 +29,10 @@ import org.springframework.stereotype.Service; import java.math.BigInteger; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -51,6 +57,9 @@ public class DeliveryOutcomeServiceImpl implements DeliveryOutcomeService { @Autowired private UserServiceRoleRepo userRepo; + @Autowired + private UserService userService; + @Autowired private IncentiveRecordRepo recordRepo; @@ -122,85 +131,171 @@ public List getDeliveryOutcome(GetBenRequestHandler dto) { public void checkAndAddJsyIncentive(List delOutList) { + if(!delOutList.isEmpty()){ + Integer userID = userRepo.getUserIdByName(delOutList.get(0).getCreatedBy()); + Integer stateId = userService.getUserDetail(userID).getStateId(); + 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); + } - 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 (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); + } + } } - } - } - 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()); + 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) { - 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); + 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 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) { + 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); - createIncentiveRecordforJsy(deliveryOutcome, deliveryOutcome.getBenId(), incentiveActivityInstJSY2); + } } } + } + if(deliveryOutcome.getDeliveryOutcome()!=null){ + if(!beneficiaryRepo.findByBenficieryid(deliveryOutcome.getBenId()).isEmpty()){ + RMNCHBeneficiaryDetailsRmnch rmnchBeneficiaryDetailsRmnch = beneficiaryRepo.findByBenficieryid(deliveryOutcome.getBenId()).get(0); + LocalDate marriageDate = rmnchBeneficiaryDetailsRmnch.getDateMarriage() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + + LocalDate deliveryDate = deliveryOutcome.getDateOfDelivery() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + + long years = ChronoUnit.YEARS.between(marriageDate, deliveryDate); + if (years >= 2 && !rmnchBeneficiaryDetailsRmnch.getDoYouHavechildren()) { + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforYearGap(deliveryOutcome, deliveryOutcome.getBenId(), activity); + } + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_DELAY_2Y", + GroupName.FAMILY_PLANNING.getDisplayName()); + + createIncentiveRecordforYearGap(deliveryOutcome, deliveryOutcome.getBenId(), activity); + } + - 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); + if(deliveryOutcome.getDeliveryOutcome()!=null){ + if(!beneficiaryRepo.findByBenficieryid(deliveryOutcome.getBenId()).isEmpty()){ + RMNCHBeneficiaryDetailsRmnch rmnchBeneficiaryDetailsRmnch = beneficiaryRepo.findByBenficieryid(deliveryOutcome.getBenId()).get(0); + LocalDate marriageDate = rmnchBeneficiaryDetailsRmnch.getDateMarriage() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + + LocalDate deliveryDate = deliveryOutcome.getDateOfDelivery() + .toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate(); + + long years = ChronoUnit.YEARS.between(marriageDate, deliveryDate); + + if (years >= 3 && rmnchBeneficiaryDetailsRmnch.getDoYouHavechildren()) { + if(stateId.equals(StateCode.AM.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.FAMILY_PLANNING.getDisplayName()); + + createIncentiveRecordforYearGap(deliveryOutcome, deliveryOutcome.getBenId(), activity); + } + if(stateId.equals(StateCode.CG.getStateCode())){ + IncentiveActivity activity = + incentivesRepo.findIncentiveMasterByNameAndGroup( + "1st_2nd_CHILD_GAP", + GroupName.ACTIVITY.getDisplayName()); + + createIncentiveRecordforYearGap(deliveryOutcome, deliveryOutcome.getBenId(), activity); + } + } } + + + } - } + + }); + } - }); // JSY_ANC_URBAN // JSY_INST_URBAN @@ -213,7 +308,41 @@ private void createIncentiveRecordforJsy(DeliveryOutcome delOutList, Long benId, try { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), delOutList.getCreatedDate(), benId); + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), delOutList.getDateOfDelivery(), benId,userRepo.getUserIdByName(delOutList.getUpdatedBy())); + + + 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.getDateOfDelivery()); + 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); + } + + + } + + private void createIncentiveRecordforYearGap(DeliveryOutcome delOutList, Long benId, IncentiveActivity immunizationActivity) { + logger.info("benId" + benId); + + try { + IncentiveActivityRecord record = recordRepo + .findRecordByActivityIdCreatedDateBenId(immunizationActivity.getId(), delOutList.getDateOfDelivery(), benId,userRepo.getUserIdByName(delOutList.getUpdatedBy())); if (record == null) { @@ -225,7 +354,7 @@ record = new IncentiveActivityRecord(); record.setCreatedBy(delOutList.getCreatedBy()); record.setStartDate(delOutList.getDateOfDelivery()); record.setEndDate(delOutList.getDateOfDelivery()); - record.setUpdatedDate(delOutList.getCreatedDate()); + record.setUpdatedDate(delOutList.getDateOfDelivery()); record.setUpdatedBy(delOutList.getCreatedBy()); record.setBenId(benId); record.setAshaId(userRepo.getUserIdByName(delOutList.getUpdatedBy())); diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index 2746fa785..e6a69ba22 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -1280,7 +1280,7 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, MosquitoNe .findRecordByActivityIdCreatedDateBenId( diseaseScreeningActivity.getId(), visitTimestamp, - diseaseScreening.getBeneficiaryId()); + diseaseScreening.getBeneficiaryId(),diseaseScreening.getUserId()); if (record == null) { @@ -1310,7 +1310,7 @@ private void addIncentive(IncentiveActivity diseaseScreeningActivity, ScreeningM ? new Timestamp(diseaseScreening.getScreeningDate().getTime()) : null; IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue()); + .findRecordByActivityIdCreatedDateBenId(diseaseScreeningActivity.getId(), Timestamp.valueOf(diseaseScreening.getCreatedDate().toString()), diseaseScreening.getBenId().longValue(),diseaseScreening.getUserId()); if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(diseaseScreeningActivity.getId()); @@ -1457,7 +1457,7 @@ private void addNCDFolloupIncentiveRecord(IncentiveActivity incentiveActivity, I Long benId, Timestamp createdDate, String userName) { try { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), createdDate, benId); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), createdDate, benId,ashaId); Timestamp now = Timestamp.valueOf(LocalDateTime.now()); if (record == null) { diff --git a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java index 76e8dc586..362dc1ea8 100644 --- a/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IFAFormSubmissionServiceImpl.java @@ -121,7 +121,7 @@ private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, Incent Timestamp ifaVisitDateTimestamp = Timestamp.valueOf(ifaVisitDate.atStartOfDay()); - IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId()); + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivityAM.getId(),ifaVisitDateTimestamp,ifaFormSubmissionData.getBeneficiaryId(),userServiceRoleRepo.getUserIdByName(ifaFormSubmissionData.getUserName())); if(incentiveActivityRecord==null){ incentiveActivityRecord = new IncentiveActivityRecord(); incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); diff --git a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java index 2802fa925..b6e4b7c7a 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveLogicImpl.java @@ -132,7 +132,7 @@ public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( return null; } - String activityName = "NLEP_PB_TREATMENT"; + String activityName = "NLEP_MB_TREATMENT"; if (stateCode.equals(StateCode.AM.getStateCode())) { return processIncentive( @@ -159,7 +159,7 @@ public IncentiveActivityRecord incentiveForLeprosyMultibacillaryConfirmed( return null; } catch (Exception e) { - logger.error("Check NLEP_PB_TREATMENT Incentive Exception: ", e); + logger.error("Check NLEP_MB_TREATMENT Incentive Exception: ", e); return null; } } @@ -672,7 +672,7 @@ private IncentiveActivityRecord saveIncentive( // 🔍 duplicate check IncentiveActivityRecord existing = incentiveRecordRepo .findRecordByActivityIdCreatedDateBenId( - activity.getId(), startTimestamp, benId); + activity.getId(), startTimestamp, benId,userId); if (existing != null) { logger.info("Incentive already exists for benId: {}, activityId: {}", 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 5ff7ddb25..f109c88a8 100644 --- a/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/IncentiveServiceImpl.java @@ -22,6 +22,10 @@ import org.slf4j.Logger; 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.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; @@ -33,6 +37,7 @@ import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; @@ -78,6 +83,9 @@ public class IncentiveServiceImpl implements IncentiveService { @Autowired private IFAFormSubmissionRepository ifaFormSubmissionRepository; + private final ConcurrentHashMap lockMap = new ConcurrentHashMap<>(); + + // ================= MASTER SAVE ================= @Override @@ -187,6 +195,10 @@ public String getIncentiveMaster(IncentiveRequestDTO incentiveRequestDTO) { @Override public String getAllIncentivesByUserId(GetBenRequestHandler request) { + int page = 0; + int size = 20; + Page pageResult; + List finalDtos = new ArrayList<>(); Integer stateCode = userService.getUserDetail(request.getAshaId()).getStateId(); String userName = userService.getUserDetail(request.getAshaId()).getUserName(); @@ -199,7 +211,6 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { checkMonthlyAshaIncentiveForCg(request.getAshaId()); } - checkIncentiveForChildGap(stateCode, userName); } catch (Exception e) { logger.error("Error in checkMonthlyAshaIncentive: ", e); @@ -215,86 +226,105 @@ public String getAllIncentivesByUserId(GetBenRequestHandler request) { boolean isCG = stateCode != null && stateCode.equals(StateCode.CG.getStateCode()); - // Step 1: Fetch all records for this ASHA - List entities = recordRepo.findRecordsByAsha(request.getAshaId()); + do { - if (entities.isEmpty()) { - return new Gson().toJson(Collections.emptyList()); - } + Pageable pageable = PageRequest.of( + page, + size, + Sort.by("id").descending() // latest first + ); - // Step 2: Collect all activityIds — fetch valid ones in ONE query - List activityIds = entities.stream() - .map(IncentiveActivityRecord::getActivityId) - .distinct() - .collect(Collectors.toList()); + pageResult = recordRepo.findRecordsByAsha( + request.getAshaId(), + pageable + ); - // Single bulk query instead of N individual findIncentiveMasterById() calls - Set validActivityIds = isCG - ? incentivesRepo.findValidActivityIds(activityIds, true) - : incentivesRepo.findValidActivityIds(activityIds, false); + List entities = pageResult.getContent(); - // Filter entities based on valid activity IDs - entities = entities.stream() - .filter(e -> validActivityIds.contains(e.getActivityId())) - .collect(Collectors.toList()); + if (entities.isEmpty()) { + return new Gson().toJson(Collections.emptyList()); + } - // 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 2: Collect all activityIds — fetch valid ones in ONE query + List activityIds = entities.stream() + .map(IncentiveActivityRecord::getActivityId) + .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()); - } - } + // Single bulk query instead of N individual findIncentiveMasterById() calls + Set validActivityIds = isCG + ? incentivesRepo.findValidActivityIds(activityIds, true) + : incentivesRepo.findValidActivityIds(activityIds, false); - // 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(""); - } - if (entry.getVerifiedByUserId() != null) { - entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); - entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); + // 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()); } - if (entry.getAshaId() != null) { - if (entry.getCreatedBy() == null) { - entry.setCreatedBy(userName); + } + + // 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(""); } + if (entry.getVerifiedByUserId() != null) { + entry.setSupervisorRole(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getRoleName()); + entry.setVerifiedByUserName(userRepo.getUserRole(entry.getVerifiedByUserId()).get(0).getName()); - if (entry.getUpdatedBy() == null) { - entry.setUpdatedBy(userName); } + if (entry.getAshaId() != null) { + if (entry.getCreatedBy() == null) { + entry.setCreatedBy(userName); + } + + if (entry.getUpdatedBy() == null) { + entry.setUpdatedBy(userName); + } - if (entry.getIsEligible() == null) { - entry.setIsEligible(true); + if (entry.getIsEligible() == null) { + entry.setIsEligible(true); + } } + + } + return modelMapper.map(entry, IncentiveRecordDTO.class); + }).collect(Collectors.toList()); + finalDtos.addAll(dtos); + + page++; + + } while (pageResult.hasNext()); - } - 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); + return gson.toJson(finalDtos); } // ================= GROUPED SUMMARY ================= @@ -569,27 +599,13 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { 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)); - } - }); + cbacDetailsImer.forEach(cbacDetailsImer1 -> { + if(cbacDetailsImer1!=null){ + addNCDandCBACIncentiveRecord(activity, ashaId, cbacDetailsImer1.getBeneficiaryRegId(), cbacDetailsImer1.getCreatedDate(), userName); + } + }); } if (hwcReferralEnumeration != null) { @@ -627,21 +643,34 @@ private void incentiveOfNcdReferal(Integer ashaId, Integer stateId) { } // Helper — record banana - private IncentiveActivityRecord addNCDandCBACIncentiveRecord(IncentiveActivity activity, Integer ashaId, + private void 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; + + String lockKey = activity.getId() + "_" + benId + "_" + createdDate; + + Object lock = lockMap.computeIfAbsent(lockKey, k -> new Object()); + synchronized (lock){ + IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId(activity.getId(),createdDate,benId,ashaId); + if(incentiveActivityRecord==null){ + 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())); + recordRepo.save(record); + } + lockMap.remove(lockKey, lock); + + } + + } private String resolveGroupName(Integer stateId) { @@ -654,6 +683,7 @@ private String resolveGroupName(Integer stateId) { } private void checkMonthlyAshaIncentive(Integer ashaId) { + try { String userName = userRepo.getUserNamedByUserId(ashaId); @@ -714,10 +744,10 @@ private void addMonthlyAshaIncentiveRecord(IncentiveActivity incentiveActivity, IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), - startOfMonth, - endOfMonth, 0L, - ashaId + ashaId, + startOfMonth, + endOfMonth ); @@ -753,10 +783,10 @@ private void addHwcReferalAshaIncentiveRecord(IncentiveActivity incentiveActivit IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), - startOfMonth, - endOfMonth, 0L, - ashaId + ashaId, + startOfMonth, + endOfMonth ); @@ -830,166 +860,46 @@ private void addIncentiveForIronTablets(Integer userId) { } private void addIFAIncentive(IFAFormSubmissionData ifaFormSubmissionData, IncentiveActivity incentiveActivityAM, Integer userId, String userName) { - 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)); - logger.info("IFA incentive"); - IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( - incentiveActivityAM.getId(), - startOfMonth, - endOfMonth, - 0L, - userId - ); - if (incentiveActivityRecord == null) { - incentiveActivityRecord = new IncentiveActivityRecord(); - incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); - incentiveActivityRecord.setCreatedDate(timestamp); - incentiveActivityRecord.setStartDate(timestamp); - incentiveActivityRecord.setEndDate(timestamp); - incentiveActivityRecord.setUpdatedDate(timestamp); - incentiveActivityRecord.setUpdatedBy(ifaFormSubmissionData.getUserName()); - incentiveActivityRecord.setCreatedBy(ifaFormSubmissionData.getUserName()); - incentiveActivityRecord.setBenId(0L); - incentiveActivityRecord.setAshaId(userId); - incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); - recordRepo.save(incentiveActivityRecord); - logger.info("saved IFA incentive"); - - } - } - - private void checkIncentiveForChildGap(Integer stateId, String userName) { - - logger.info("Checking Child Gap Incentive for user: {}, stateId: {}", userName, stateId); - - List eligibleCoupleRegisters = eligibleCoupleRegisterRepo.findByCreatedBy(userName); - - logger.info("Eligible Couple Records Found: {}", eligibleCoupleRegisters.size()); - - if (!eligibleCoupleRegisters.isEmpty()) { - - eligibleCoupleRegisters.forEach(eligibleCoupleRegister -> { - - logger.info( - "Processing EligibleCoupleRegister -> BenId: {}, NumChildren: {}, MarriageFirstChildGap: {}, FirstAndSecondChildGap: {}", - eligibleCoupleRegister.getBenId(), - eligibleCoupleRegister.getNumChildren(), - eligibleCoupleRegister.getMarriageFirstChildGap(), - eligibleCoupleRegister.getFirstAndSecondChildGap()); - - // Marriage -> First Child Gap - if(eligibleCoupleRegister.getFirstAndSecondChildGap()!=null){ - if (eligibleCoupleRegister.getFirstAndSecondChildGap()>=3 ) { - - logger.info("Marriage -> First Child Gap condition matched."); - - if (stateId.equals(StateCode.AM.getStateCode())) { - - logger.info("Fetching incentive for Assam."); - - IncentiveActivity activity1 = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "FP_DELAY_2Y", - GroupName.FAMILY_PLANNING.getDisplayName()); - - logger.info("Incentive Activity: {}", activity1); - - createIncentiveRecord(eligibleCoupleRegister, activity1); - - logger.info("Marriage -> First Child Gap incentive created."); - } - - if (stateId.equals(StateCode.CG.getStateCode())) { - - logger.info("Fetching incentive for Chhattisgarh."); - - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "FP_DELAY_2Y", - GroupName.ACTIVITY.getDisplayName()); - - logger.info("Incentive Activity: {}", activityCH); - - createIncentiveRecord(eligibleCoupleRegister, activityCH); - - logger.info("Marriage -> First Child Gap incentive created."); - } - } - } - + String lockKey = incentiveActivityAM.getId() + "_" + 0 + "_" + startOfMonth; - // First -> Second Child Gap - if(eligibleCoupleRegister.getMarriageFirstChildGap()!=null){ - if (eligibleCoupleRegister.getMarriageFirstChildGap()>=2) { - - logger.info("1st -> 2nd Child Gap condition matched."); - - if (stateId.equals(StateCode.AM.getStateCode())) { - - logger.info("Fetching incentive for Assam."); - - IncentiveActivity activity2 = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.FAMILY_PLANNING.getDisplayName()); - - logger.info("Incentive Activity: {}", activity2); - - createIncentiveRecord(eligibleCoupleRegister, activity2); - - logger.info("1st -> 2nd Child Gap incentive created."); - } - - if (stateId.equals(StateCode.CG.getStateCode())) { - - logger.info("Fetching incentive for Chhattisgarh."); - - IncentiveActivity activityCH = - incentivesRepo.findIncentiveMasterByNameAndGroup( - "1st_2nd_CHILD_GAP", - GroupName.ACTIVITY.getDisplayName()); - - logger.info("Incentive Activity: {}", activityCH); + Object lock = lockMap.computeIfAbsent(lockKey, k -> new Object()); + Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now()); - createIncentiveRecord(eligibleCoupleRegister, activityCH); - logger.info("1st -> 2nd Child Gap incentive created."); - } - } - } + logger.info("IFA incentive"); + synchronized (lock){ + IncentiveActivityRecord incentiveActivityRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( + incentiveActivityAM.getId(), + 0L, + userId, + startOfMonth, + endOfMonth + ); + if (incentiveActivityRecord == null) { + incentiveActivityRecord = new IncentiveActivityRecord(); + incentiveActivityRecord.setActivityId(incentiveActivityAM.getId()); + incentiveActivityRecord.setCreatedDate(timestamp); + incentiveActivityRecord.setStartDate(timestamp); + incentiveActivityRecord.setEndDate(timestamp); + incentiveActivityRecord.setUpdatedDate(timestamp); + incentiveActivityRecord.setUpdatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setCreatedBy(ifaFormSubmissionData.getUserName()); + incentiveActivityRecord.setBenId(0L); + incentiveActivityRecord.setAshaId(userId); + incentiveActivityRecord.setAmount(Long.valueOf(incentiveActivityAM.getRate())); + recordRepo.save(incentiveActivityRecord); + logger.info("saved IFA incentive"); - }); + } - } else { - logger.info("No Eligible Couple Register records found for user: {}", userName); } + lockMap.remove(lockKey, lock); - logger.info("Completed Child Gap Incentive check for user: {}", userName); - } - private void createIncentiveRecord(EligibleCoupleRegister eligibleCoupleRegister, IncentiveActivity activity) { - if (activity != null) { - IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(activity.getId(), eligibleCoupleRegister.getCreatedDate(), eligibleCoupleRegister.getBenId()); - Integer userId = userRepo.getUserIdByName(eligibleCoupleRegister.getCreatedBy()); - if (record == null) { - record = new IncentiveActivityRecord(); - record.setActivityId(activity.getId()); - record.setCreatedDate(eligibleCoupleRegister.getCreatedDate()); - record.setCreatedBy(eligibleCoupleRegister.getCreatedBy()); - record.setStartDate(eligibleCoupleRegister.getCreatedDate()); - record.setEndDate(eligibleCoupleRegister.getCreatedDate()); - record.setUpdatedDate(eligibleCoupleRegister.getCreatedDate()); - record.setUpdatedBy(eligibleCoupleRegister.getCreatedBy()); - record.setBenId(eligibleCoupleRegister.getBenId()); - record.setAshaId(userId); - record.setAmount(Long.valueOf(activity.getRate())); - recordRepo.save(record); - } - } } + } 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 03af282a7..bd0409903 100644 --- a/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/InfantServiceImpl.java @@ -98,7 +98,7 @@ private void checkAndGenerateIncentive(List infantList) { } private void addIsSncuIncentive(IncentiveActivity activity, Long benId, String createdBy, Timestamp createdDate) { - IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(activity.getId(),createdDate,benId); + IncentiveActivityRecord incentiveActivityRecord = incentiveRecordRepo.findRecordByActivityIdCreatedDateBenId(activity.getId(),createdDate,benId,userServiceRoleRepo.getUserIdByName(createdBy)); if(incentiveActivityRecord==null){ incentiveActivityRecord = new IncentiveActivityRecord(); 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 8bc197088..41849ee3c 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -355,7 +355,7 @@ private void checkAndAddHighRisk(List pmsmaList) { private void addIncentiveForHighRisk(IncentiveActivity incentiveActivity, PMSMA pmsma) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), pmsma.getCreatedDate(), pmsma.getBenId()); + .findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), pmsma.getCreatedDate(), pmsma.getBenId(),userRepo.getUserIdByName(pmsma.getCreatedBy())); // get bene details if (record == null) { @@ -737,7 +737,7 @@ private void addIncenticeRecord(PNCVisit ect, Integer userId, IncentiveActivity synchronized (lock) { IncentiveActivityRecord record = recordRepo - .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getPncDate(), ect.getBenId()); + .findRecordByActivityIdCreatedDateBenId(antaraActivity.getId(), ect.getPncDate(), ect.getBenId(),userId); if (record == null) { record = new IncentiveActivityRecord(); @@ -776,14 +776,22 @@ private void checkAndAddIncentives(List ancList, Integer userId) { IncentiveActivity paiucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.FAMILY_PLANNING.getDisplayName()); + IncentiveActivity iucdActivityAM = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_IUCD", GroupName.FAMILY_PLANNING.getDisplayName()); ancList.forEach(ancVisit -> { - - if (paiucdActivityAM != null && ancVisit.getIsPaiucdId() != null - && ancVisit.getIsPaiucdId().toString().equals("1")) { - recordAncRelatedIncentive(paiucdActivityAM, ancVisit); + if(ancVisit.getIsAborted()){ + if (paiucdActivityAM != null && ancVisit.getIsPaiucdId() != null && ancVisit.getIsPaiucdId()==2 && + ancVisit.getIsPaiucd().toString().contains("Tubectomy")) { + recordAncRelatedIncentive(paiucdActivityAM, ancVisit); + } + if (iucdActivityAM != null && ancVisit.getIsPaiucdId() != null && ancVisit.getIsPaiucdId()==1 && + ancVisit.getIsPaiucd().toString().contains("Copper-T")) { + recordAncRelatedIncentive(iucdActivityAM, ancVisit); + } } + if (anc1Activity != null && ancVisit.getAncVisit() != null && ancVisit.getAncVisit() == 1) { recordAncFirstTRIMIncentive(anc1Activity, ancVisit); @@ -822,11 +830,21 @@ private void checkAndAddIncentives(List ancList, Integer userId) { IncentiveActivity paiucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( "FP_PAIUCD", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity iucdActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup( + "FP_IUCD", GroupName.ACTIVITY.getDisplayName()); + ancList.forEach(ancVisit -> { if (ancVisit.getIsAborted()) { - recordAncRelatedIncentive(paiucdActivityCH, ancVisit); + if (paiucdActivityCH != null && ancVisit.getIsPaiucdId() != null && ancVisit.getIsPaiucdId()==2 && + ancVisit.getIsPaiucd().toString().contains("Tubectomy")) { + recordAncRelatedIncentive(paiucdActivityCH, ancVisit); + } + if (iucdActivityCH != null && ancVisit.getIsPaiucdId() != null && ancVisit.getIsPaiucdId()==1 + && ancVisit.getIsPaiucd().toString().contains("Copper-T")) { + recordAncRelatedIncentive(iucdActivityCH, ancVisit); + } } @@ -847,9 +865,10 @@ private void checkAndAddIncentives(List ancList, Integer userId) { } private void recordAncRelatedIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { - IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId()); Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); + IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId(incentiveActivity.getId(), ancVisit.getCreatedDate(), ancVisit.getBenId(),userId); + if (record == null) { record = new IncentiveActivityRecord(); record.setActivityId(incentiveActivity.getId()); @@ -868,6 +887,7 @@ record = new IncentiveActivityRecord(); } private void recordAncFirstTRIMIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { + Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); if (ancVisit.getAncDate() == null || ancVisit.getLmpDate() == null) { return; @@ -885,10 +905,9 @@ private void recordAncFirstTRIMIncentive(IncentiveActivity incentiveActivity, AN IncentiveActivityRecord record = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), ancVisit.getCreatedDate(), - ancVisit.getBenId() + ancVisit.getBenId(),userId ); - Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); if (record == null) { record = new IncentiveActivityRecord(); @@ -907,11 +926,14 @@ record = new IncentiveActivityRecord(); } private void recordFullAncIncentive(IncentiveActivity incentiveActivity, ANCVisit ancVisit) { - + Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); + if (userId == null) { + return; + } IncentiveActivityRecord existRecord = recordRepo.findRecordByActivityIdCreatedDateBenId( incentiveActivity.getId(), - ancVisit.getCreatedDate(), - ancVisit.getBenId() + ancVisit.getAncDate(), + ancVisit.getBenId(),userId ); @@ -919,11 +941,6 @@ private void recordFullAncIncentive(IncentiveActivity incentiveActivity, ANCVisi return; } - Integer userId = userRepo.getUserIdByName(ancVisit.getCreatedBy()); - if (userId == null) { - return; - } - IncentiveActivityRecord record = new IncentiveActivityRecord(); record.setActivityId(incentiveActivity.getId()); record.setCreatedDate(ancVisit.getAncDate()); From 336daab5947b3bea0c081b0dcd81451bcd410235 Mon Sep 17 00:00:00 2001 From: Saurav Mishra Date: Wed, 8 Jul 2026 16:40:57 +0530 Subject: [PATCH 445/450] optmiz query for incentive logic for hbnc --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 1 - 1 file changed, 1 deletion(-) 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 01acddf8e..4903e1fc3 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -287,7 +287,6 @@ public List getHBNCDetails(GetBenRequestHandler dto) { } page++; - checkAndAddHbncIncentives(hbncVisits, dto.getAshaId()); }while (visitPage.hasNext()); From 629397d04791591788259ffd4e69b6ef02008c5e Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 20 Jul 2026 15:53:50 +0530 Subject: [PATCH 446/450] fixed hbnc and leprosy incentive (#290) --- .../service/impl/ChildCareServiceImpl.java | 57 +------------------ .../impl/DiseaseControlServiceImpl.java | 26 ++++----- 2 files changed, 15 insertions(+), 68 deletions(-) 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 4903e1fc3..dac04ade1 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -911,43 +911,7 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } - pncVisits.forEach(pncVisit -> { - Long hbncHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(hbncVisit.getBeneficiaryId())).get(0).getHouseoldId(); - Long houseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(pncVisit.getBenId())).get(0).getHouseoldId(); - - if (hbncHouseHoldId.equals(houseHoldId)) { - if (hbncVisit.getVisit_day().equals("42th Day")) { - if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { - if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed()) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, pncVisit.getBenId(), visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); - } - } - if (!pncVisitRepo.findByBenId(pncVisit.getBenId()).isEmpty()) { - if (!pncVisitRepo.findByBenId(pncVisit.getBenId()).get(0).getMotherDangerSign().isEmpty()) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, pncVisit.getBenId(), visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); - } - } - } - } - }); - - ancVisits.forEach(ancVisit -> { - Long hbncHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(hbncVisit.getBeneficiaryId())).get(0).getHouseoldId(); - Long ancHouseHoldId = beneficiaryRepo.getDetailsByRegID(beneficiaryRepo.getRegIDFromBenId(ancVisit.getBenId())).get(0).getHouseoldId(); - - if (hbncHouseHoldId.equals(ancHouseHoldId)) { - if (hbncVisit.getVisit_day().equals("42th Day")) { - if (!ancVisitRepo.findByBenId(ancVisit.getBenId()).isEmpty()) { - if (ancVisitRepo.findByBenId(ancVisit.getBenId()).get(0).getIsHrpConfirmed()) { - IncentiveActivity visitActivityANC = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); - createIncentiveRecordforHbncVisit(hbncVisit, ancVisit.getBenId(), visitActivityANC, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); - } - } - } - } - }); + logger.info("getDischarged_from_sncu" + hbncVisit.getDischarged_from_sncu()); @@ -969,24 +933,9 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI if (stateCode.equals(StateCode.CG.getStateCode())) { if (hbncVisit.getVisit_day().equals("42th Day")) { - if (!ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { - if (ancVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getIsHrpConfirmed() && pncVisitRepo.findByBenId(hbncVisit - .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_HEALTH_CHECK", GroupName.ACTIVITY.getDisplayName()); + IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); + createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS"); - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_HEALTH_CHECK"); - - } - } - if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).isEmpty()) { - if (!pncVisitRepo.findByBenId(hbncVisit.getBeneficiaryId()).get(0).getMotherDangerSign().isEmpty() && pncVisitRepo.findByBenId(hbncVisit - .getBeneficiaryId()).get(0).getPncPeriod().toString().equals("42")) { - IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HIGH_RISK_POSTPARTUM_CARE", GroupName.ACTIVITY.getDisplayName()); - - createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HIGH_RISK_POSTPARTUM_CARE"); - - } - } } } diff --git a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java index e6a69ba22..35746b2f8 100644 --- a/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/DiseaseControlServiceImpl.java @@ -301,20 +301,18 @@ public String saveLeprosy(LeprosyDTO diseaseControlDTO) { diseaseControlData.setUserId(diseaseControlDTO.getUserId()); } ScreeningLeprosy screeningLeprosy = diseaseLeprosyRepository.save(saveLeprosyData(diseaseControlData)); - if(screeningLeprosy.getIsConfirmed()){ - IncentiveActivityRecord incentiveActivityRecord = - incentiveLogicService.incentiveForIdentificationLeprosy( - screeningLeprosy.getBenId(), - screeningLeprosy.getHomeVisitDate(), - screeningLeprosy.getHomeVisitDate(), - diseaseControlDTO.getUserId()); - - if (incentiveActivityRecord != null) { - logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", - incentiveActivityRecord.getId()); - } else { - logger.info("Incentive not created"); - } + IncentiveActivityRecord incentiveActivityRecord = + incentiveLogicService.incentiveForIdentificationLeprosy( + screeningLeprosy.getBenId(), + screeningLeprosy.getHomeVisitDate(), + screeningLeprosy.getHomeVisitDate(), + diseaseControlDTO.getUserId()); + + if (incentiveActivityRecord != null) { + logger.info("Incentive processed for Screening Leprosy successfully. RecordId={}", + incentiveActivityRecord.getId()); + } else { + logger.info("Incentive not created"); } return "Data add successfully"; From 732bfa6e33e116ff6d30179335dbd269046fe014 Mon Sep 17 00:00:00 2001 From: Saurav Mishra <80103738+SauravBizbRolly@users.noreply.github.com> Date: Mon, 20 Jul 2026 17:59:58 +0530 Subject: [PATCH 447/450] fixed hbnc and leprosy incentive (#291) --- .../java/com/iemr/flw/service/impl/ChildCareServiceImpl.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 dac04ade1..e65e0f53e 100644 --- a/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/ChildCareServiceImpl.java @@ -899,8 +899,6 @@ private void checkAndAddHbyncIncentives(List hbycList) { private void checkAndAddHbncIncentives(List hbncVisits, Integer userId) { Integer stateCode = userService.getUserDetail(userId).getStateId(); - List pncVisits = pncVisitRepo.getPNCForPW(userRepo.getUserNamedByUserId(userId)); - List ancVisits = ancVisitRepo.getANCForPW(userRepo.getUserNamedByUserId(userId)); hbncVisits.forEach(hbncVisit -> { Long benId = hbncVisit.getBeneficiaryId(); if (stateCode.equals(StateCode.AM.getStateCode())) { @@ -932,7 +930,7 @@ private void checkAndAddHbncIncentives(List hbncVisits, Integer userI } if (stateCode.equals(StateCode.CG.getStateCode())) { - if (hbncVisit.getVisit_day().equals("42th Day")) { + if (hbncVisit.getVisit_day().equals("42nd Day")) { IncentiveActivity visitActivityCH = incentivesRepo.findIncentiveMasterByNameAndGroup("HBNC_0_42_DAYS", GroupName.ACTIVITY.getDisplayName()); createIncentiveRecordforHbncVisit(hbncVisit, benId, visitActivityCH, "HBNC_0_42_DAYS"); From 0ace8289f8b5e244c59417412918158a44b9b987 Mon Sep 17 00:00:00 2001 From: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Date: Thu, 23 Jul 2026 11:05:50 +0530 Subject: [PATCH 448/450] Merging 3.8.2 Branch (#294) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(linting): commitlint ,Commitzen, Husky configuration * feat: added new register api for stoptb * feat: added new register api for stoptb * feat: added new api for nurse * fix: populate workingDistrictId from blockId in getUserDetail when district is null Co-Authored-By: Claude Sonnet 4.6 * feat: align Stop TB APIs with BRD — village scoping + correct field names - StopTBGeneralExamination: rewrite with BRD-correct fields (pallorId+pallor string pairs, pulseRate, randomBloodSugar, oedema, beneficiaryRegID, keyPopulationRiskFactorIds, hivStatusId — no more boolean clinical signs) - StopTBRegistration: add villageId + villageName from i_bendemographics.districtBranchID - StopTBRegistrationDto: add villageId + villageName for worklist requests - StopTBRegistrationRepo: scope registrar worklist by psmId + villageId - BenFlowStatusRepo: scope nurse worklist by psmId + villageId - StopTBGeneralExaminationRepo: rename findByBeneficiaryRegID - StopTBServiceImpl: extract village from demographics on registration, set on both tb_stoptb_registration and i_ben_flow_outreach flow record, fix all BRD field names throughout, add toJsonString for array fields Co-Authored-By: Claude Sonnet 4.6 * refactor: replace tb_stoptb_registration with BenFlowStatus for registrar worklist and add beneficiary details endpoint - getRegistrarWorklist now queries i_ben_flow_outreach by villageID + visitCategory instead of tb_stoptb_registration - add getRegistrarWorklist query to BenFlowStatusRepo - add getBeneficiaryDetails endpoint that proxies TM-API quickSearchNew and merges otherFields into flat response object Co-Authored-By: Claude Sonnet 4.6 * fix: worklist chnges * fix: use JwtToken header for getBeneficiaryDetails TM-API call Co-Authored-By: Claude Sonnet 4.6 * fix: use okhttp User-Agent pattern for TM-API call in getBeneficiaryDetails Co-Authored-By: Claude Sonnet 4.6 * fix: look up 12-digit beneficiaryID from BenFlowStatus for TM-API quickSearchNew Co-Authored-By: Claude Sonnet 4.6 * refactor: redesign Stop TB worklist to return full beneficiary data in getBeneficiaryData style - saveRegistration: forward full payload to TM-API without stripping Stop TB/anthropometry fields — they land in ExtraFields via checkExtraFields; enrich BenFlowStatus with benName, dob, gender, phone, district extracted from registration payload - getRegistrarWorklist: returns getBeneficiaryData-style response — BenFlowStatus fields + db_identity detail (community, education, fatherName, motherName) + otherFields parsed for anthropometry and Stop TB details (personFrom, caseFindingType, tuId, weight, height, bmi, temp) - getNurseWorklist: same rich response + generalExamination, tbScreening, generalOpd attached if already saved (null if not yet captured) - Remove getRegistration and getBeneficiaryDetails endpoints — worklist covers both - Add otherFields (ExtraFields column) mapping to RMNCHMBeneficiarydetail entity - BenFlowStatusRepo worklist queries scoped to psmId + villageId only (visitCategory column not guaranteed to exist in i_ben_flow_outreach table) Co-Authored-By: Claude Sonnet 4.6 * fix: use mapping table two-step lookup to fetch beneficiary details in Stop TB worklist getDetailByBenRegID queries i_beneficiarydetails.beneficiaryRegID which is unpopulated; correct path is i_beneficiarymapping → BenDetailsId → i_beneficiarydetails. Co-Authored-By: Claude Sonnet 4.6 * refactor: use OutputResponse for all StopTBController endpoints to match AMRIT standard format Co-Authored-By: Claude Sonnet 4.6 * feat: add Stop TB worklist path and anthropometry to getBeneficiaryData - Add providerServiceMapID to GetBenRequestHandler for Stop TB filtering - Add getAddressesByBenRegIds repo query to fetch addresses by benRegId list - Add Stop TB path in getBenData: filter by providerServiceMapID+villageID via BenFlowStatus - Parse i_beneficiarydetails.ExtraFields to include anthropometry (weight/height/bmi/temperatureValue) in response Co-Authored-By: Claude Sonnet 4.6 * fix: use JOIN query for getAddressesByBenRegIds and accept villageId alias - Replace subquery with JOIN to fix Hibernate 6 multi-valued binding error - Add setVillageId setter as alias for villageID in GetBenRequestHandler Co-Authored-By: Claude Sonnet 4.6 * fix: switch getAddressesByBenRegIds to native SQL to avoid Hibernate 6 IN binding issue JPQL IN with collection param throws multi-valued binding error in Hibernate 6 — native query bypasses this. Co-Authored-By: Claude Sonnet 4.6 * fix: use per-row mapping lookup for Stop TB worklist to avoid Hibernate IN binding issue Replace bulk native query with per-row findByBenRegIdFromMapping + getAddressById calls — same pattern as existing FLW code, avoids Object[] mapping error from native SELECT *. Co-Authored-By: Claude Sonnet 4.6 * feat: add stopTBDetails block (personFrom, caseFindingType, isMobileAvailable, tuId, tuName) to getBeneficiaryData response Co-Authored-By: Claude Sonnet 4.6 * feat: add occupation, economicStatus, residentialArea to stopTBDetails in worklist response - occupation read from i_beneficiarydetails (already stored by Identity-API) - economicStatus and residentialArea promoted to top-level in registration payload so Identity-API saves them in ExtraFields; read back in worklist Co-Authored-By: Claude Sonnet 4.6 * feat: add demographics block with address, occupation, economicStatus, residentialArea to worklist response Co-Authored-By: Claude Sonnet 4.6 * Revert "feat: add demographics block with address, occupation, economicStatus, residentialArea to worklist response" This reverts commit 3695522d5139363e8eba335d6142cb5526af7ec0. * feat: use tb-prefixed keys for economicStatus and residentialArea to ensure ExtraFields storage Identity-API ignores unknown processing of economicStatus/residentialArea to DB columns silently; using tbEconomicStatus/tbResidentialArea as keys ensures they land in ExtraFields and are returned in worklist Co-Authored-By: Claude Sonnet 4.6 * feat: move occupation, economicStatus, residentialArea into beneficiaryDetails object Co-Authored-By: Claude Sonnet 4.6 * fix: read economicStatus and residentialArea directly from ExtraFields (not tb-prefixed keys) Mobile sends these as top-level fields to TM-API; Identity-API saves them in ExtraFields as-is Co-Authored-By: Claude Sonnet 4.6 * feat: add Diagnostics module and Yes/No ID fields across Stop TB nurse flow - Add StopTBDiagnostics entity, repo, service, and controller (save/get/getAll) - Add village-scoped getAll (villageID optional) to GeneralExamination, TBScreening, GeneralOpd, Diagnostics via BenFlowStatus subquery - Fix TBScreening visitDate to accept user-provided date; preserve on update (not editable once submitted) - Fix referralToHWCNeeded to trust mobile-computed value instead of server recalculating - Fix chiefComplaint to support multi-select (JSON array) - Add Yes/No boolean ID counterpart fields to TBScreening (14 fields), GeneralExamination (referralToHWCNeededId), Registration (isMobileAvailableId), and Diagnostics (6 fields) - Add getTimestamp helper to StopTBServiceImpl Co-Authored-By: Claude Sonnet 4.6 * feat: accept array of objects in all 4 Stop TB nurse save APIs generalExamination, tbScreening, generalOpd, and diagnostics save endpoints now take List instead of a single Map, allowing bulk save in one request. Each item is processed within the same transaction. Co-Authored-By: Claude Sonnet 4.6 * fix supervisor name * fix supervisor name * fix supervisor name * add update date on get ben api * add update date on get ben api * feat: return updateDate and updatedBy in all Stop TB getAll APIs - Add lastModDate + modifiedBy fields to TBScreening, TBSuspected, TBConfirmedCase, MalariaFollowUp entities (columns already exist in DB) - Set modifiedBy in all save methods across StopTB, TBSuspected, TBConfirmed, MalariaFollowUp services - Return updateDate/updatedBy in all 8 getAll API responses so mobile app can detect and refresh stale local records - Fix TBConfirmedCase save duplicate bug — now looks up existing record by benId before inserting new entity - Add updateDate to getBeneficiaryData response from i_beneficiarydetails Co-Authored-By: Claude Sonnet 4.6 * fix: resolve compile errors — move resultMap.put after initialization, add Map import Co-Authored-By: Claude Sonnet 4.6 * feat: add chest xray, sputum, NAAT reason fields to StopTB diagnostics Added isReferredForDigitalChestXray, reasonForDenialChestXray, reasonNotConductedChestXray, isReferredForSputumCollection, reasonForDenialSputum, sputumSubmittedAt, reasonNotConductedNaat and their *Other variants to domain, save, and get map. Co-Authored-By: Claude Sonnet 4.6 * feat(stoptb): add local-to-central sync fields for Stop TB mobile flow - Add vanID, parkingPlaceID, visitCode, processed, vanSerialNo to all Stop TB entities (TBScreening, GeneralExamination, GeneralOpd, Diagnostics, TBSuspected, TBConfirmedCase) - Add updateVanSerialNo() to all 6 repos for MMU DataSync pattern - Add CampConfigService to read camp:vanID from Redis (set by MMU login) - Stamp vanID + processed='N' on every save in StopTBServiceImpl, TBSuspectedServiceImpl, TBConfirmedCaseServiceImpl Co-Authored-By: Claude Sonnet 4.6 * fix: make vanID stamping conditional — skip gracefully when camp not configured When FLW-API is used without a Stop TB camp setup (no MMU login, no camp:vanID in Redis), getVanID() now returns null instead of throwing. All save methods guard with vanID != null before stamping, so regular FLW/ASHA usage is completely unaffected. Co-Authored-By: Claude Sonnet 4.6 * feat(stoptb): add stoptb.enforce.vanid flag to fail loudly when camp not configured CampConfigService.getVanID() previously returned null silently whenever camp:vanID was missing from Redis, letting Stop TB records save with vanID=NULL — these then never sync to central since the fetch query filters on vanID IS NOT NULL. When stoptb.enforce.vanid=true, the save now throws immediately so the error surfaces to the user instead of being discovered later as an un-synced record. * fix(stoptb): correct symptomatic/asymptomatic save and retrieve mapping Frontend sends a single "symptomatic" Yes/No value, but the DB has two separate columns (symptomatic, asymptomatic) with swapped semantics. Yes now stores asymptomatic=Yes (symptomatic=null), No stores symptomatic=Yes (asymptomatic=null). Retrieval derives the response "symptomatic" value back from whichever column is Yes, so it always echoes the original input. Co-Authored-By: Claude Sonnet 4.6 * fix sync issue * feat(counselling): implement dynamic form management for TB counselling Introduces dynamic form definition management with versioning and response lifecycle support (draft, submit, complete, and bulk sync) for the TB counselling module. Includes: - Dynamic form and response APIs - QuestionType and ValidationType enums - TbCounsellingFormSeeder for initial form setup - JWT-based audit stamping (createdBy/updatedBy) - SecurityWhitelistConfig for endpoint-level authentication control * feat(stoptb): add per-visit history to General Examination, TB Screening, OPD, Suspected, Confirmed Every Stop TB clinical save previously upserted by beneficiaryRegID/benId alone, so a beneficiary's second camp visit silently overwrote their first - no history was ever kept. Adds a new tb_stoptb_visit table (mirrors MMU's t_benvisitdetail visitNo pattern, scoped entirely to Stop TB's own schema) and a getOrCreateVisitForToday() helper that infers "new visit" purely from the save date, with no mobile change required. - New TBStopVisit entity/repo/service: visitNo counting, role-handoff flags reserved for future Doctor/Counsellor screens, full sync field set (processed/vanSerialNo/SyncedDate/Syncedby/SyncFailureReason) matching the existing AMRIT-wide DataSyncRepository convention. - StopTBGeneralExamination/TBScreening/StopTBGeneralOpd/TBSuspected/ TBConfirmedCase now upsert keyed by (beneficiaryRegID, visitCode) instead of beneficiaryRegID alone. Reused the existing dormant visitCode column on 4 of 6 tables rather than adding a new one. - Fixed 4 read methods (getNurseWorklist, getGeneralExamination, getNurseTBScreening, getGeneralOpd) that would have thrown NonUniqueResultException once a beneficiary had more than one visit row - switched to findLatestBy... + PageRequest.of(0,1). - StopTBDiagnostics deliberately excluded: liquid culture results arrive 40-45 days after the original encounter and must update the same row, which visit-keying would have broken. Requires DB migration (not included): CREATE TABLE tb_stoptb_visit, plus ALTER TABLE tb_suspected/tb_confirmed_cases ADD COLUMN visitCode BIGINT. Co-Authored-By: Claude Sonnet 4.6 * Merge remote-tracking branch 'origin/vb/stoptb' into vb/stoptb * chore(local-env): update local datasource/redis/jwt config and add dynamic form schema SQL Adds manual DDL/seed script for the dynamic form tables since ddl-auto wasn't creating them in local runs, and syncs local properties with the values needed to run submitBulk locally. Co-Authored-By: Claude Sonnet 4.6 * chore(local-env): keep backup copy of common_local.properties Co-Authored-By: Claude Sonnet 4.6 * token chnges * Vb/counselling (#254) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. --------- Co-authored-by: Sehjot Singh Pannu * Vb/counselling (#255) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Vb/counselling (#256) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support --------- Co-authored-by: Sehjot Singh Pannu * fix(user-service): handle empty result from getDistrictByBlockId fallback Native query result must be mapped to List, not a bare Object[]; the previous signature caused getUserDetail() to silently skip the workingDistrictId fallback for block-only users. * Vb/counselling (#257) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> * fix(dynamic-form): default processed to N via @Builder.Default Lombok @Builder ignores field initializers, so FormResponse, QuestionResponse, and SectionResponse were inserting NULL into the processed column instead of the intended "N" default, causing "Column 'processed' cannot be null" on submitBulk. Co-Authored-By: Claude Sonnet 4.6 * Vb/counselling (#258) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * Vb/counselling (#259) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * Vb/counselling (#261) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * feat(stoptb): dual-write clinical data to AMRIT standard tables via t_benvisitdetail - Replace tb_stoptb_visit with t_benvisitdetail (MMU-compatible visitCode formula) - Dual-write exam data to t_phy_anthropometry, t_phy_vitals, t_Phy_GeneralExam, t_benreferdetails - Dual-write OPD data to t_benchiefcomplaint, t_prescription, t_prescribeddrug - Add 6 new JPA entities and repos for standard tables (db_iemr schema) - Update TBSuspectedServiceImpl and TBConfirmedCaseServiceImpl to use BenVisitDetail - Fix vanID/parkingPlaceID not being stored in t_form_response, t_section_response, t_question_response - Delete orphaned TBStopVisit entity and TBStopVisitRepo Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): getBeneficiaryData reads anthropometry/vitals from standard tables - getBeneficiaryData now reads height/weight/bmi from t_phy_anthropometry and temperature/pulse/BP/RBS from t_phy_vitals (latest row per beneficiary) - Fallback to otherFields if exam not yet saved for the beneficiary - Stop TB specific fields (personFrom, caseFindingType etc.) still from otherFields - Add findByBeneficiaryRegIDOrderByCreatedDateDesc and findByBenVisitID to BenAnthropometryRepo and BenPhysicalVitalRepo - Add StopTB_Future_Roadmap.md for future HWC integration and edit support Co-Authored-By: Claude Sonnet 4.6 * fix(compile): rename variable 'a' to 'anthro' to avoid conflict with outer loop variable Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): set CreatedDate on t_benvisitdetail insert to prevent NOT NULL constraint violation Co-Authored-By: Claude Sonnet 4.6 * fix(anc-pnc): guard CreatedDate on BenVisitDetail insert for ANC and PNC flows If mobile does not send createdDate, ModelMapper leaves it null and MySQL rejects the insert with NOT NULL constraint. Set server timestamp as fallback. Co-Authored-By: Claude Sonnet 4.6 * fix(docker): set TZ=Asia/Kolkata to prevent UTC/IST date mismatch Without explicit timezone, Docker defaults to UTC. This causes LocalDate.now() in getOrCreateVisitForToday() to use UTC date, so evening IST registrations appear as next-day July 1 in DB and visit lookups fail after UTC midnight. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): handle ISO 8601 Z suffix in parseDob to fix beneficiary age display Timestamp.valueOf() throws on "yyyy-MM-dd HH:mm:ss.SSSZ" format because the trailing Z is not a valid nanosecond value. Strip Z before parsing so mobile DOB like "1987-07-01T00:00:00.000Z" is correctly stored in i_ben_flow_outreach.ben_dob. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): fallback to i_ben_flow_outreach.ben_dob when i_beneficiarydetails.dob is null Identity-API mapper (@Mapping source=dto.dob) is commented out, causing dob to be null for all mobile registrations. Fall back to ben_dob from i_ben_flow_outreach so getBeneficiaryData returns correct DOB and mobile shows correct age. Co-Authored-By: Claude Sonnet 4.6 * fix: use saveAndFlush to prevent FK violation in t_benchiefcomplaint save() leaves VisitCode UPDATE pending in JPA session — t_benchiefcomplaint INSERT runs before the UPDATE reaches DB, causing FK constraint failure and full transaction rollback. saveAndFlush forces the UPDATE to DB immediately. Co-Authored-By: Claude Sonnet 4.6 * Vb/counselling (#262) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder * Add optional villageId and providerServiceMapId filters to getCompletedBeneficiaries --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * Vb/counselling (#263) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder * Add optional villageId and providerServiceMapId filters to getCompletedBeneficiaries * Removing section f from seeder --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * Vb/counselling (#264) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder * Add optional villageId and providerServiceMapId filters to getCompletedBeneficiaries * Removing section f from seeder * Removing already existing check in /complete api --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 * fix(stoptb): compute age from benDetailsRMNCH_OBJ.dob instead of benDetailsOBJ.dob benDetailsOBJ.dob (i_beneficiarydetails) is null for Stop TB mobile registrations, which is why c22b3fd2 added a fallback that fills benDetailsRMNCH_OBJ.dob from i_ben_flow_outreach. The age calculation block still read the original, still-null benDetailsOBJ.dob, so dob came back correct but age/ageFull stayed 0/"". Point it at the already-corrected benDetailsRMNCH_OBJ.dob instead. Co-Authored-By: Claude Sonnet 5 * field missing * fix(stoptb): scope Suspected/Confirmed getAll by facility+village instead of userId Nurse and Counsellor are different logins hitting the same /tb/suspected/getAll and /tb/confirmed/getAll endpoints, but both queries filtered by the calling user's own userId. So a Counsellor pulling data after a Nurse creates a Suspected/Confirmed record saw none of it - only rows tied to their own login. Adds an optional providerServiceMapID(+villageID)-scoped query path on both endpoints, joined through the already-populated BenFlowStatus table (same pattern as StopTBDiagnosticsRepo), so any role at the same facility/village sees the same worklist. The old userId-based path is kept as the fallback when the new fields aren't sent, so already-deployed app builds are unaffected. * fix(stoptb): drop date filter from facility-scoped Suspected query visitDate isn't the right dimension for a facility worklist - an unresolved Suspected case from months ago is still actionable, and filtering it out by date would hide it from the Counsellor, working against the visibility fix in the previous commit. Also matches StopTBDiagnosticsRepo's facility-scoped query, which never date-filters. Old ashaId-based fallback path is untouched and still date-filters as before. * fix(stoptb): join facility-scoped query on beneficiaryID, not beneficiaryRegID TBSuspected.benId / TBConfirmedCase.benId store the person-level beneficiary_id (e.g. 907797933607), not beneficiaryRegID (e.g. 35137) - confirmed by querying i_ben_flow_outreach directly. The facility-scoped query added in the previous two commits joined against BenFlowStatus.beneficiaryRegID, so it never matched anything and always returned empty. Switched the join to BenFlowStatus.beneficiaryID, which is the correct corresponding column. * Add debug logging, RMNCH pinCode field, and GPS fallback pinCode mapping Co-Authored-By: Claude Sonnet 5 * Vb/counselling (#269) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder * Add optional villageId and providerServiceMapId filters to getCompletedBeneficiaries * Removing section f from seeder * Removing already existing check in /complete api * Add a CHECKBOX question type and a TB_COUNSELLING_V2 seeder with a GENERAL_INFO consent gate ahead of the counselling sections. * Seed single-checkbox questions for Sections A-D and point the Counselled lookup at TB_COUNSELLING_V2 instead of the retired V1 form * Mark form/section status REFUSED when TB2_GI_Q1=NO on /complete, split getCompletedBeneficiaries into completed/refused lists, and extract FormResponseStatus enum * Resolved conflicts * fix(stoptb): getBeneficiaryData reads anthropometry/vitals from standard tables - getBeneficiaryData now reads height/weight/bmi from t_phy_anthropometry and temperature/pulse/BP/RBS from t_phy_vitals (latest row per beneficiary) - Fallback to otherFields if exam not yet saved for the beneficiary - Stop TB specific fields (personFrom, caseFindingType etc.) still from otherFields - Add findByBeneficiaryRegIDOrderByCreatedDateDesc and findByBenVisitID to BenAnthropometryRepo and BenPhysicalVitalRepo - Add StopTB_Future_Roadmap.md for future HWC integration and edit support Co-Authored-By: Claude Sonnet 4.6 * fix(compile): rename variable 'a' to 'anthro' to avoid conflict with outer loop variable Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): set CreatedDate on t_benvisitdetail insert to prevent NOT NULL constraint violation Co-Authored-By: Claude Sonnet 4.6 * fix(anc-pnc): guard CreatedDate on BenVisitDetail insert for ANC and PNC flows If mobile does not send createdDate, ModelMapper leaves it null and MySQL rejects the insert with NOT NULL constraint. Set server timestamp as fallback. Co-Authored-By: Claude Sonnet 4.6 * fix(docker): set TZ=Asia/Kolkata to prevent UTC/IST date mismatch Without explicit timezone, Docker defaults to UTC. This causes LocalDate.now() in getOrCreateVisitForToday() to use UTC date, so evening IST registrations appear as next-day July 1 in DB and visit lookups fail after UTC midnight. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): handle ISO 8601 Z suffix in parseDob to fix beneficiary age display Timestamp.valueOf() throws on "yyyy-MM-dd HH:mm:ss.SSSZ" format because the trailing Z is not a valid nanosecond value. Strip Z before parsing so mobile DOB like "1987-07-01T00:00:00.000Z" is correctly stored in i_ben_flow_outreach.ben_dob. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): fallback to i_ben_flow_outreach.ben_dob when i_beneficiarydetails.dob is null Identity-API mapper (@Mapping source=dto.dob) is commented out, causing dob to be null for all mobile registrations. Fall back to ben_dob from i_ben_flow_outreach so getBeneficiaryData returns correct DOB and mobile shows correct age. Co-Authored-By: Claude Sonnet 4.6 * fix: use saveAndFlush to prevent FK violation in t_benchiefcomplaint save() leaves VisitCode UPDATE pending in JPA session — t_benchiefcomplaint INSERT runs before the UPDATE reaches DB, causing FK constraint failure and full transaction rollback. saveAndFlush forces the UPDATE to DB immediately. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): compute age from benDetailsRMNCH_OBJ.dob instead of benDetailsOBJ.dob benDetailsOBJ.dob (i_beneficiarydetails) is null for Stop TB mobile registrations, which is why c22b3fd2 added a fallback that fills benDetailsRMNCH_OBJ.dob from i_ben_flow_outreach. The age calculation block still read the original, still-null benDetailsOBJ.dob, so dob came back correct but age/ageFull stayed 0/"". Point it at the already-corrected benDetailsRMNCH_OBJ.dob instead. Co-Authored-By: Claude Sonnet 5 * fix(stoptb): scope Suspected/Confirmed getAll by facility+village instead of userId Nurse and Counsellor are different logins hitting the same /tb/suspected/getAll and /tb/confirmed/getAll endpoints, but both queries filtered by the calling user's own userId. So a Counsellor pulling data after a Nurse creates a Suspected/Confirmed record saw none of it - only rows tied to their own login. Adds an optional providerServiceMapID(+villageID)-scoped query path on both endpoints, joined through the already-populated BenFlowStatus table (same pattern as StopTBDiagnosticsRepo), so any role at the same facility/village sees the same worklist. The old userId-based path is kept as the fallback when the new fields aren't sent, so already-deployed app builds are unaffected. * fix(stoptb): drop date filter from facility-scoped Suspected query visitDate isn't the right dimension for a facility worklist - an unresolved Suspected case from months ago is still actionable, and filtering it out by date would hide it from the Counsellor, working against the visibility fix in the previous commit. Also matches StopTBDiagnosticsRepo's facility-scoped query, which never date-filters. Old ashaId-based fallback path is untouched and still date-filters as before. * fix(stoptb): join facility-scoped query on beneficiaryID, not beneficiaryRegID TBSuspected.benId / TBConfirmedCase.benId store the person-level beneficiary_id (e.g. 907797933607), not beneficiaryRegID (e.g. 35137) - confirmed by querying i_ben_flow_outreach directly. The facility-scoped query added in the previous two commits joined against BenFlowStatus.beneficiaryRegID, so it never matched anything and always returned empty. Switched the join to BenFlowStatus.beneficiaryID, which is the correct corresponding column. * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: vishwab1 * fix(counselling): remove duplicate findCounselledBenIds method and import left over from PR #269 merge The duplicate interface method was a compile error that cascaded into hundreds of unrelated Lombok symbol errors across the module. Co-Authored-By: Claude Sonnet 5 * Vb/counselling (#270) * Enforced mandatory validation for "Reason for Refusal in section e in file TbCounsellingFormSeeder * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Align `/complete` and `/submitBulk` form response editing behavior * Updated `/complete` to resolve `FormResponse` using `beneficiaryId` and `formUuid` from the request body, removing the dependency on `responseId` as a query parameter. * Updated `/submitBulk` section editing to match `/complete` behavior by performing in-place `SectionResponse` upserts and per-question delete-and-reinsert operations, instead of deleting and recreating the entire section. * Add van/sync tracking fields (vanID, parkingPlaceID, vanSerialNo, processed, syncedDate, syncedBy, syncFailureReason) to domain entities for offline mobile data collection support * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(dynamic-form): add Hindi localization fields and completed beneficiaries endpoint - Added `sectionName_hindi`, `questionText_hindi`, and `optionValue_hindi` fields to the FormSection, SectionQuestion, and QuestionOption entities to support Hindi localization. - Added `GET /dynamicForm/response/getCompletedBeneficiaries?formType=` endpoint to return beneficiary IDs with `COMPLETE` status for the specified form type. * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields # Conflicts: # src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java * Updated isMandatory field in Section C, so changed in TbCounsellingFormSeeder * Add optional villageId and providerServiceMapId filters to getCompletedBeneficiaries * Removing section f from seeder * Removing already existing check in /complete api * Add a CHECKBOX question type and a TB_COUNSELLING_V2 seeder with a GENERAL_INFO consent gate ahead of the counselling sections. * Seed single-checkbox questions for Sections A-D and point the Counselled lookup at TB_COUNSELLING_V2 instead of the retired V1 form * Mark form/section status REFUSED when TB2_GI_Q1=NO on /complete, split getCompletedBeneficiaries into completed/refused lists, and extract FormResponseStatus enum * Resolved conflicts * fix(stoptb): getBeneficiaryData reads anthropometry/vitals from standard tables - getBeneficiaryData now reads height/weight/bmi from t_phy_anthropometry and temperature/pulse/BP/RBS from t_phy_vitals (latest row per beneficiary) - Fallback to otherFields if exam not yet saved for the beneficiary - Stop TB specific fields (personFrom, caseFindingType etc.) still from otherFields - Add findByBeneficiaryRegIDOrderByCreatedDateDesc and findByBenVisitID to BenAnthropometryRepo and BenPhysicalVitalRepo - Add StopTB_Future_Roadmap.md for future HWC integration and edit support Co-Authored-By: Claude Sonnet 4.6 * fix(compile): rename variable 'a' to 'anthro' to avoid conflict with outer loop variable Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): set CreatedDate on t_benvisitdetail insert to prevent NOT NULL constraint violation Co-Authored-By: Claude Sonnet 4.6 * fix(anc-pnc): guard CreatedDate on BenVisitDetail insert for ANC and PNC flows If mobile does not send createdDate, ModelMapper leaves it null and MySQL rejects the insert with NOT NULL constraint. Set server timestamp as fallback. Co-Authored-By: Claude Sonnet 4.6 * fix(docker): set TZ=Asia/Kolkata to prevent UTC/IST date mismatch Without explicit timezone, Docker defaults to UTC. This causes LocalDate.now() in getOrCreateVisitForToday() to use UTC date, so evening IST registrations appear as next-day July 1 in DB and visit lookups fail after UTC midnight. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): handle ISO 8601 Z suffix in parseDob to fix beneficiary age display Timestamp.valueOf() throws on "yyyy-MM-dd HH:mm:ss.SSSZ" format because the trailing Z is not a valid nanosecond value. Strip Z before parsing so mobile DOB like "1987-07-01T00:00:00.000Z" is correctly stored in i_ben_flow_outreach.ben_dob. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): fallback to i_ben_flow_outreach.ben_dob when i_beneficiarydetails.dob is null Identity-API mapper (@Mapping source=dto.dob) is commented out, causing dob to be null for all mobile registrations. Fall back to ben_dob from i_ben_flow_outreach so getBeneficiaryData returns correct DOB and mobile shows correct age. Co-Authored-By: Claude Sonnet 4.6 * fix: use saveAndFlush to prevent FK violation in t_benchiefcomplaint save() leaves VisitCode UPDATE pending in JPA session — t_benchiefcomplaint INSERT runs before the UPDATE reaches DB, causing FK constraint failure and full transaction rollback. saveAndFlush forces the UPDATE to DB immediately. Co-Authored-By: Claude Sonnet 4.6 * fix(stoptb): compute age from benDetailsRMNCH_OBJ.dob instead of benDetailsOBJ.dob benDetailsOBJ.dob (i_beneficiarydetails) is null for Stop TB mobile registrations, which is why c22b3fd2 added a fallback that fills benDetailsRMNCH_OBJ.dob from i_ben_flow_outreach. The age calculation block still read the original, still-null benDetailsOBJ.dob, so dob came back correct but age/ageFull stayed 0/"". Point it at the already-corrected benDetailsRMNCH_OBJ.dob instead. Co-Authored-By: Claude Sonnet 5 * fix(stoptb): scope Suspected/Confirmed getAll by facility+village instead of userId Nurse and Counsellor are different logins hitting the same /tb/suspected/getAll and /tb/confirmed/getAll endpoints, but both queries filtered by the calling user's own userId. So a Counsellor pulling data after a Nurse creates a Suspected/Confirmed record saw none of it - only rows tied to their own login. Adds an optional providerServiceMapID(+villageID)-scoped query path on both endpoints, joined through the already-populated BenFlowStatus table (same pattern as StopTBDiagnosticsRepo), so any role at the same facility/village sees the same worklist. The old userId-based path is kept as the fallback when the new fields aren't sent, so already-deployed app builds are unaffected. * fix(stoptb): drop date filter from facility-scoped Suspected query visitDate isn't the right dimension for a facility worklist - an unresolved Suspected case from months ago is still actionable, and filtering it out by date would hide it from the Counsellor, working against the visibility fix in the previous commit. Also matches StopTBDiagnosticsRepo's facility-scoped query, which never date-filters. Old ashaId-based fallback path is untouched and still date-filters as before. * fix(stoptb): join facility-scoped query on beneficiaryID, not beneficiaryRegID TBSuspected.benId / TBConfirmedCase.benId store the person-level beneficiary_id (e.g. 907797933607), not beneficiaryRegID (e.g. 35137) - confirmed by querying i_ben_flow_outreach directly. The facility-scoped query added in the previous two commits joined against BenFlowStatus.beneficiaryRegID, so it never matched anything and always returned empty. Switched the join to BenFlowStatus.beneficiaryID, which is the correct corresponding column. * Added counselled flag to confirmed cases response, indicating whether a beneficiary has completed the TB Counselling form. Implemented using a single bulk query to avoid N+1 lookups against FormResponse. * Revert "Committed 82b00ccf with only the three files:" This reverts commit 3040a08077d82d27dfd86f29f0fbdd4dc094ec56. * Committed 82b00ccf with only the three files: - BeneficiaryServiceImpl.java — serializeNulls() + GPS fallback from address - RMNCHBeneficiaryDetailsRmnch.java — gpsLatitude, gpsLongitude, digipin, gpsTimestamp, isGpsUnavailable fields - RMNCHHouseHoldDetails.java — gpsLatitude, gpsLongitude fields * feat(beneficiary): expose GPS coordinates in getBeneficiaryData response Add gpsLatitude, gpsLongitude, digipin, gpsTimestamp, and isGpsUnavailable fields to RMNCHBeneficiaryDetailsRmnch and RMNCHHouseHoldDetails entities, mapping to the columns written by Identity-API's /syncDataToAmrit endpoint. Enable serializeNulls on the Gson builder in BeneficiaryServiceImpl so GPS keys are always present in householdDetails and beneficiaryDetails — null for web-registered records, real values for mobile-registered ones. Co-Authored-By: Claude Sonnet 4.6 * Changing working of checkbox as of radio button --------- Co-authored-by: Vishwanath Balkur <118195001+vishwab1@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: vishwab1 * Move Risk Factors and HIV Status from General Examination to TB Screening Adds a mandatory Risk Factors section (Key Population/Risk Factors multi-select + HIV Status) to nurse TB Screening, matching the new form requirement, and removes it from General Examination where it previously lived. Co-Authored-By: Claude Sonnet 5 * Keep Risk Factors and HIV Status on General Examination too Per updated requirement, these fields should be captured on both General Examination and TB Screening, not moved exclusively to TB Screening. Restores keyPopulationRiskFactorIds/Factors and hivStatusId/hivStatus on StopTBGeneralExamination (save + response map), on top of the earlier commit that added them to TBScreening. Co-Authored-By: Claude Sonnet 5 * Stop TB API responses were silently dropping null fields new Gson() excludes any key whose value is null by default, so fields like hivStatus/keyPopulationRiskFactor* that were saved as NULL never appeared in GET/GETALL responses at all. Switch to a shared Gson instance built with serializeNulls() across all 16 StopTBController response sites. Co-Authored-By: Claude Sonnet 5 * chore: remove stale StopTB planning docs Co-Authored-By: Claude Sonnet 5 * Revert "Vb/counselling (#270)" This reverts commit 0861661e490855109f03b3a9d8d71c9da983eb92. * Revert "Vb/counselling (#269)" This reverts commit 8bdc9dee65c9f4d46c20545caba217a2a66b1469. * Revert "Vb/counselling (#264)" This reverts commit 82286d26. * Move Risk Factors and HIV Status from General Examination to TB Screening Adds a mandatory Risk Factors section (Key Population/Risk Factors multi-select + HIV Status) to nurse TB Screening, matching the new form requirement, and removes it from General Examination where it previously lived. Co-Authored-By: Claude Sonnet 5 * Keep Risk Factors and HIV Status on General Examination too Per updated requirement, these fields should be captured on both General Examination and TB Screening, not moved exclusively to TB Screening. Restores keyPopulationRiskFactorIds/Factors and hivStatusId/hivStatus on StopTBGeneralExamination (save + response map), on top of the earlier commit that added them to TBScreening. Co-Authored-By: Claude Sonnet 5 * Changing in complete api accoridng to release 1.1 (#279) * fix: tolerate duplicate i_beneficiarymapping rows in Stop TB worklist benRegId has no unique constraint on i_beneficiarymapping, so findByBenRegIdFromMapping's single-result query threw IncorrectResultSizeDataAccessException whenever a beneficiary had more than one mapping row, crashing the Stop TB registrar worklist refresh. Return the list ordered by benMapId DESC and use the latest mapping instead of assuming uniqueness. * fix: remove PII-dumping debug println statements from BeneficiaryController getBeneficiaryData request/response System.out.println calls logged full beneficiary details (name, address, health ID) to stdout unconditionally. * fix: add try/catch to VillageLevelFormController save methods Without local exception handling, an unhandled error in saveVhndForm/ saveVhncForm/savePhcForm/saveAhdForm/saveDewormingForm now falls through to GlobalExceptionHandler's catch-all, which returns a different response shape (ApiResponse) than this controller's existing status/statusCode/ message convention, breaking existing clients. Wrap each in the same try/catch pattern already used by getVillageLevelFormData. * chore: remove confirmed-dead StopTB endpoints and backing code Verified against the actual mobile app source (STOP-TB-App release-1.1 AmritApiService.kt) and ADMIN-UI web client — none of these are called: - /stoptb/registration/save — mobile registers directly against TM-API's registrarBeneficaryRegistrationNew; TM-API creates BenFlowStatus itself via its own isMobile-flag branch when the request doesn't carry isMobile=true (confirmed in TM-API's RegistrarServiceImpl) - /stoptb/registrar/worklist, /stoptb/nurse/worklist — explicitly commented out in the app's network layer - /stoptb/nurse/submit — no reference at all - /stoptb/nurse/{generalExamination,tbScreening,generalOpd,diagnostics}/get (singular) — only the /getAll variants are used Also removes the now-fully-orphaned StopTBRegistration entity/DTO/repo (the registration table itself was already replaced by BenFlowStatus in an earlier commit) and StopTBServiceImpl helper methods that only existed to support the removed saveRegistration path. * fix: handle List<> return type change in AbhaBeneficiaryServiceImpl findByBenRegIdFromMapping's return type was changed from a single object to List by an earlier Stop TB commit (fixing an IncorrectResultSizeDataAccessException when a beneficiary has more than one mapping row), but this caller was never updated to match — a pre-existing oversight in the original commit, surfaced by the build check. * chore: remove local-dev SQL scripts from repo dynamic_form_schema.sql and alter_tb_screening_risk_factors_hiv_status.sql are dropped from the codebase — the underlying DB schema changes they describe are still required (documented in stoptb_schema_changes.sql), they will just be run directly against the DB instead of being tracked as files in this repo. --------- Co-authored-by: Zapper9982 Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Saurav Mishra Co-authored-by: Sehjot Singh Pannu --- .github/workflows/commit-lint.yml | 34 + .gitignore | 1 + .husky/commit-msg | 1 + .husky/pre-commit | 1 + Dockerfile | 2 + README.md | 43 + commitlint.config.js | 36 + package-lock.json | 3433 +++++++++++++++++ package.json | 30 + src/main/environment/common_ci.properties | 3 + src/main/environment/common_docker.properties | 3 + .../environment/common_example.properties | 8 +- .../environment/common_local.properties.bkp | 49 + .../flw/controller/DynamicFormController.java | 100 + .../DynamicFormResponseController.java | 110 + .../controller/GlobalExceptionHandler.java | 154 + .../iemr/flw/controller/StopTBController.java | 161 + .../com/iemr/flw/controller/TBController.java | 9 +- .../VillageLevelFormController.java | 160 +- .../RMNCHBeneficiaryDetailsRmnch.java | 52 + .../identity/RMNCHHouseHoldDetails.java | 8 + .../identity/RMNCHMBeneficiaryaddress.java | 18 + .../identity/RMNCHMBeneficiarydetail.java | 23 + .../domain/iemr/BenAnthropometryDetail.java | 70 + .../flw/domain/iemr/BenChiefComplaint.java | 73 + .../iemr/flw/domain/iemr/BenFlowStatus.java | 82 + .../domain/iemr/BenPhysicalVitalDetail.java | 76 + .../com/iemr/flw/domain/iemr/DynamicForm.java | 128 + .../iemr/flw/domain/iemr/FormResponse.java | 137 + .../com/iemr/flw/domain/iemr/FormSection.java | 118 + .../com/iemr/flw/domain/iemr/FormVersion.java | 115 + .../iemr/flw/domain/iemr/MalariaFollowUp.java | 9 + .../iemr/flw/domain/iemr/OptionCondition.java | 103 + .../domain/iemr/PhyGeneralExamination.java | 79 + .../flw/domain/iemr/PrescribedDrugDetail.java | 82 + .../flw/domain/iemr/PrescriptionDetail.java | 70 + .../iemr/flw/domain/iemr/QuestionOption.java | 109 + .../flw/domain/iemr/QuestionResponse.java | 103 + .../flw/domain/iemr/QuestionValidation.java | 101 + .../iemr/flw/domain/iemr/SectionQuestion.java | 135 + .../iemr/flw/domain/iemr/SectionResponse.java | 96 + .../flw/domain/iemr/StopTBDiagnostics.java | 140 + .../domain/iemr/StopTBGeneralExamination.java | 133 + .../flw/domain/iemr/StopTBGeneralOpd.java | 81 + .../iemr/flw/domain/iemr/TBConfirmedCase.java | 31 + .../flw/domain/iemr/TBConfirmedCaseDTO.java | 7 +- .../com/iemr/flw/domain/iemr/TBScreening.java | 115 + .../com/iemr/flw/domain/iemr/TBSuspected.java | 33 +- .../dto/identity/GetBenRequestHandler.java | 14 + .../com/iemr/flw/dto/iemr/DynamicFormDTO.java | 65 + .../iemr/flw/dto/iemr/FormResponseDTO.java | 57 + .../flw/dto/iemr/FormResponseRequest.java | 58 + .../com/iemr/flw/dto/iemr/FormSectionDTO.java | 64 + .../com/iemr/flw/dto/iemr/FormVersionDTO.java | 41 + .../flw/dto/iemr/MalariaFollowListUpDTO.java | 4 + .../iemr/flw/dto/iemr/OptionConditionDTO.java | 58 + .../flw/dto/iemr/QuestionAnswerRequest.java | 63 + .../iemr/flw/dto/iemr/QuestionOptionDTO.java | 59 + .../flw/dto/iemr/QuestionResponseDTO.java | 47 + .../flw/dto/iemr/QuestionValidationDTO.java | 49 + .../flw/dto/iemr/SectionAnswerRequest.java | 50 + .../iemr/flw/dto/iemr/SectionQuestionDTO.java | 76 + .../iemr/flw/dto/iemr/SectionResponseDTO.java | 48 + .../com/iemr/flw/dto/iemr/TBSuspectedDTO.java | 2 + .../iemr/flw/mapper/DynamicFormMapper.java | 105 + .../com/iemr/flw/masterEnum/FormType.java | 34 + .../com/iemr/flw/masterEnum/QuestionType.java | 43 + .../iemr/flw/masterEnum/ValidationType.java | 42 + .../flw/repo/identity/BeneficiaryRepo.java | 10 +- .../flw/repo/iemr/BenAnthropometryRepo.java | 15 + .../flw/repo/iemr/BenChiefComplaintRepo.java | 9 + .../iemr/flw/repo/iemr/BenFlowStatusRepo.java | 38 + .../flw/repo/iemr/BenPhysicalVitalRepo.java | 15 + .../flw/repo/iemr/BenVisitDetailsRepo.java | 18 +- .../iemr/flw/repo/iemr/DynamicFormRepo.java | 47 + .../iemr/flw/repo/iemr/FormResponseRepo.java | 72 + .../iemr/flw/repo/iemr/FormSectionRepo.java | 38 + .../iemr/flw/repo/iemr/FormVersionRepo.java | 46 + .../flw/repo/iemr/OptionConditionRepo.java | 55 + .../repo/iemr/PhyGeneralExaminationRepo.java | 9 + .../repo/iemr/PrescribedDrugDetailRepo.java | 9 + .../flw/repo/iemr/PrescriptionDetailRepo.java | 9 + .../flw/repo/iemr/QuestionOptionRepo.java | 48 + .../flw/repo/iemr/QuestionResponseRepo.java | 46 + .../flw/repo/iemr/QuestionValidationRepo.java | 48 + .../flw/repo/iemr/SectionQuestionRepo.java | 48 + .../flw/repo/iemr/SectionResponseRepo.java | 47 + .../flw/repo/iemr/StopTBDiagnosticsRepo.java | 31 + .../iemr/StopTBGeneralExaminationRepo.java | 44 + .../flw/repo/iemr/StopTBGeneralOpdRepo.java | 42 + .../iemr/TBConfirmedTreatmentRepository.java | 13 + .../iemr/flw/repo/iemr/TBScreeningRepo.java | 29 + .../iemr/flw/repo/iemr/TBSuspectedRepo.java | 15 + .../flw/repo/iemr/UserServiceRoleRepo.java | 5 + .../flw/seeder/TbCounsellingFormSeeder.java | 325 ++ .../iemr/flw/service/CampConfigService.java | 59 + .../service/DynamicFormDefinitionService.java | 59 + .../service/DynamicFormResponseService.java | 66 + .../com/iemr/flw/service/StopTBService.java | 22 + .../flw/service/TBConfirmedCaseService.java | 2 + .../iemr/flw/service/TBStopVisitService.java | 9 + .../impl/AbhaBeneficiaryServiceImpl.java | 6 +- .../service/impl/BeneficiaryServiceImpl.java | 173 +- .../DynamicFormDefinitionServiceImpl.java | 416 ++ .../impl/DynamicFormResponseServiceImpl.java | 504 +++ .../FormFollowUpNotificationScheduler.java | 110 + .../service/impl/FormResponseItemSaver.java | 420 ++ .../impl/MalariaFollowUpServiceImpl.java | 3 + .../impl/MaternalHealthServiceImpl.java | 4 + .../flw/service/impl/StopTBServiceImpl.java | 767 ++++ .../impl/TBConfirmedCaseServiceImpl.java | 86 +- .../service/impl/TBStopVisitServiceImpl.java | 61 + .../service/impl/TBSuspectedServiceImpl.java | 41 +- .../flw/service/impl/UserServiceImpl.java | 10 + src/main/resources/application.properties | 2 +- 115 files changed, 11488 insertions(+), 107 deletions(-) create mode 100644 .github/workflows/commit-lint.yml create mode 100644 .husky/commit-msg create mode 100644 .husky/pre-commit create mode 100644 commitlint.config.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/main/environment/common_local.properties.bkp create mode 100644 src/main/java/com/iemr/flw/controller/DynamicFormController.java create mode 100644 src/main/java/com/iemr/flw/controller/DynamicFormResponseController.java create mode 100644 src/main/java/com/iemr/flw/controller/GlobalExceptionHandler.java create mode 100644 src/main/java/com/iemr/flw/controller/StopTBController.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/BenAnthropometryDetail.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/BenChiefComplaint.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/BenFlowStatus.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/BenPhysicalVitalDetail.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/DynamicForm.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/FormResponse.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/FormSection.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/FormVersion.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/OptionCondition.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/PhyGeneralExamination.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/PrescribedDrugDetail.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/PrescriptionDetail.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/QuestionOption.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/QuestionResponse.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/QuestionValidation.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/SectionQuestion.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/SectionResponse.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/StopTBDiagnostics.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralExamination.java create mode 100644 src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralOpd.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/DynamicFormDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FormResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FormResponseRequest.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FormSectionDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/FormVersionDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/OptionConditionDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/QuestionAnswerRequest.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/QuestionOptionDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/QuestionResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/QuestionValidationDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/SectionAnswerRequest.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/SectionQuestionDTO.java create mode 100644 src/main/java/com/iemr/flw/dto/iemr/SectionResponseDTO.java create mode 100644 src/main/java/com/iemr/flw/mapper/DynamicFormMapper.java create mode 100644 src/main/java/com/iemr/flw/masterEnum/FormType.java create mode 100644 src/main/java/com/iemr/flw/masterEnum/QuestionType.java create mode 100644 src/main/java/com/iemr/flw/masterEnum/ValidationType.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/BenAnthropometryRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/BenChiefComplaintRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/BenFlowStatusRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/BenPhysicalVitalRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/DynamicFormRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/FormResponseRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/FormSectionRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/FormVersionRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/PhyGeneralExaminationRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/PrescribedDrugDetailRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/PrescriptionDetailRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/QuestionOptionRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/QuestionValidationRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/SectionQuestionRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/SectionResponseRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/StopTBDiagnosticsRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralExaminationRepo.java create mode 100644 src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralOpdRepo.java create mode 100644 src/main/java/com/iemr/flw/seeder/TbCounsellingFormSeeder.java create mode 100644 src/main/java/com/iemr/flw/service/CampConfigService.java create mode 100644 src/main/java/com/iemr/flw/service/DynamicFormDefinitionService.java create mode 100644 src/main/java/com/iemr/flw/service/DynamicFormResponseService.java create mode 100644 src/main/java/com/iemr/flw/service/StopTBService.java create mode 100644 src/main/java/com/iemr/flw/service/TBStopVisitService.java create mode 100644 src/main/java/com/iemr/flw/service/impl/DynamicFormDefinitionServiceImpl.java create mode 100644 src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java create mode 100644 src/main/java/com/iemr/flw/service/impl/FormFollowUpNotificationScheduler.java create mode 100644 src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java create mode 100644 src/main/java/com/iemr/flw/service/impl/StopTBServiceImpl.java create mode 100644 src/main/java/com/iemr/flw/service/impl/TBStopVisitServiceImpl.java diff --git a/.github/workflows/commit-lint.yml b/.github/workflows/commit-lint.yml new file mode 100644 index 000000000..f0ed48e47 --- /dev/null +++ b/.github/workflows/commit-lint.yml @@ -0,0 +1,34 @@ +name: Commit Compliance + +on: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + commitlint: + runs-on: ubuntu-latest + + steps: + - name: Checkout code with submodule + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + submodules: true + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 18 + + - name: Install dependencies + run: | + npm ci --legacy-peer-deps + npm i --legacy-peer-deps + + - name: Run commitlint on PR + run: | + npx commitlint --from ${{ github.event.pull_request.base.sha }} \ + --to ${{ github.event.pull_request.head.sha }} \ + --verbose diff --git a/.gitignore b/.gitignore index a4786a90b..5a1e6d24a 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ mvnw.cmd .mvn /logs/ src/main/environment/common_local.properties +node_modules diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100644 index 000000000..34eed8b28 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1 @@ +npx --no -- commitlint --edit $1 \ No newline at end of file diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..d0a778429 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index f99697fa4..417c00e12 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,6 +14,8 @@ FROM eclipse-temurin:17-jre WORKDIR /app +ENV TZ=Asia/Kolkata + # Copy the built WAR file from the build stage COPY --from=build /app/target/*.war app.war diff --git a/README.md b/README.md index 560f69a7e..5c992214d 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,49 @@ This repository comprises of all APIs related to FLW Mobile App. Flw-API is a microservice which is used for the creation and management of beneficiaries related data +## Setting Up Commit Hooks + +This project uses Git hooks to enforce consistent code quality and commit message standards. Even though this is a Java project, the hooks are powered by Node.js. Follow these steps to set up the hooks locally: + +### Prerequisites +- Node.js (v14 or later) +- npm (comes with Node.js) + +### Setup Steps + +1. **Install Node.js and npm** + - Download and install from [nodejs.org](https://nodejs.org/) + - Verify installation with: + ``` + node --version + npm --version + ``` +2. **Install dependencies** + - From the project root directory, run: + ``` + npm ci + ``` + - This will install all required dependencies including Husky and commitlint +3. **Verify hooks installation** + - The hooks should be automatically installed by Husky + - You can verify by checking if the `.husky` directory contains executable hooks +### Commit Message Convention +This project follows a specific commit message format: +- Format: `type(scope): subject` +- Example: `feat(login): add remember me functionality` +Types include: +- `feat`: A new feature +- `fix`: A bug fix +- `docs`: Documentation changes +- `style`: Code style changes (formatting, etc.) +- `refactor`: Code changes that neither fix bugs nor add features +- `perf`: Performance improvements +- `test`: Adding or fixing tests +- `build`: Changes to build process or tools +- `ci`: Changes to CI configuration +- `chore`: Other changes (e.g., maintenance tasks, dependencies) +Your commit messages will be automatically validated when you commit, ensuring project consistency. + ## Filing Issues If you encounter any issues, bugs, or have feature requests, please file them in the [main AMRIT repository](https://github.com/PSMRI/AMRIT/issues). Centralizing all feedback helps us streamline improvements and address concerns efficiently. diff --git a/commitlint.config.js b/commitlint.config.js new file mode 100644 index 000000000..e65d7e68e --- /dev/null +++ b/commitlint.config.js @@ -0,0 +1,36 @@ +module.exports = { + extends: ['@commitlint/config-conventional'], + rules: { + 'body-leading-blank': [1, 'always'], + 'body-max-line-length': [2, 'always', 100], + 'footer-leading-blank': [1, 'always'], + 'footer-max-line-length': [2, 'always', 100], + 'header-max-length': [2, 'always', 100], + 'subject-case': [ + 2, + 'never', + ['sentence-case', 'start-case', 'pascal-case', 'upper-case'], + ], + 'subject-empty': [2, 'never'], + 'subject-full-stop': [2, 'never', '.'], + 'type-case': [2, 'always', 'lower-case'], + 'type-empty': [2, 'never'], + 'type-enum': [ + 2, + 'always', + [ + 'build', + 'chore', + 'ci', + 'docs', + 'feat', + 'fix', + 'perf', + 'refactor', + 'revert', + 'style', + 'test', + ], + ], + } +}; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..d11ee7ecc --- /dev/null +++ b/package-lock.json @@ -0,0 +1,3433 @@ +{ + "name": "flw-api", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "flw-api", + "version": "1.0.0", + "devDependencies": { + "@commitlint/cli": "^19.8.0", + "@commitlint/config-conventional": "^19.8.0", + "commitizen": "^4.3.1", + "cz-conventional-changelog": "^3.3.0", + "husky": "^9.1.7", + "lint-staged": "^15.5.1" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", + "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz", + "integrity": "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@commitlint/cli": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/cli/-/cli-19.8.1.tgz", + "integrity": "sha512-LXUdNIkspyxrlV6VDHWBmCZRtkEVRpBKxi2Gtw3J54cGWhLCTouVD/Q6ZSaSvd2YaDObWK8mDjrz3TIKtaQMAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/format": "^19.8.1", + "@commitlint/lint": "^19.8.1", + "@commitlint/load": "^19.8.1", + "@commitlint/read": "^19.8.1", + "@commitlint/types": "^19.8.1", + "tinyexec": "^1.0.0", + "yargs": "^17.0.0" + }, + "bin": { + "commitlint": "cli.js" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/config-conventional": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/config-conventional/-/config-conventional-19.8.1.tgz", + "integrity": "sha512-/AZHJL6F6B/G959CsMAzrPKKZjeEiAVifRyEwXxcT6qtqbPwGw+iQxmNS+Bu+i09OCtdNRW6pNpBvgPrtMr9EQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "conventional-changelog-conventionalcommits": "^7.0.2" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/config-validator": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/config-validator/-/config-validator-19.8.1.tgz", + "integrity": "sha512-0jvJ4u+eqGPBIzzSdqKNX1rvdbSU1lPNYlfQQRIFnBgLy26BtC0cFnr7c/AyuzExMxWsMOte6MkTi9I3SQ3iGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "ajv": "^8.11.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/ensure": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/ensure/-/ensure-19.8.1.tgz", + "integrity": "sha512-mXDnlJdvDzSObafjYrOSvZBwkD01cqB4gbnnFuVyNpGUM5ijwU/r/6uqUmBXAAOKRfyEjpkGVZxaDsCVnHAgyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "lodash.camelcase": "^4.3.0", + "lodash.kebabcase": "^4.1.1", + "lodash.snakecase": "^4.1.1", + "lodash.startcase": "^4.4.0", + "lodash.upperfirst": "^4.3.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/execute-rule": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/execute-rule/-/execute-rule-19.8.1.tgz", + "integrity": "sha512-YfJyIqIKWI64Mgvn/sE7FXvVMQER/Cd+s3hZke6cI1xgNT/f6ZAz5heND0QtffH+KbcqAwXDEE1/5niYayYaQA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/format": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/format/-/format-19.8.1.tgz", + "integrity": "sha512-kSJj34Rp10ItP+Eh9oCItiuN/HwGQMXBnIRk69jdOwEW9llW9FlyqcWYbHPSGofmjsqeoxa38UaEA5tsbm2JWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "chalk": "^5.3.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/is-ignored": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/is-ignored/-/is-ignored-19.8.1.tgz", + "integrity": "sha512-AceOhEhekBUQ5dzrVhDDsbMaY5LqtN8s1mqSnT2Kz1ERvVZkNihrs3Sfk1Je/rxRNbXYFzKZSHaPsEJJDJV8dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "semver": "^7.6.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/lint": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/lint/-/lint-19.8.1.tgz", + "integrity": "sha512-52PFbsl+1EvMuokZXLRlOsdcLHf10isTPlWwoY1FQIidTsTvjKXVXYb7AvtpWkDzRO2ZsqIgPK7bI98x8LRUEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/is-ignored": "^19.8.1", + "@commitlint/parse": "^19.8.1", + "@commitlint/rules": "^19.8.1", + "@commitlint/types": "^19.8.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/load": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/load/-/load-19.8.1.tgz", + "integrity": "sha512-9V99EKG3u7z+FEoe4ikgq7YGRCSukAcvmKQuTtUyiYPnOd9a2/H9Ak1J9nJA1HChRQp9OA/sIKPugGS+FK/k1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/config-validator": "^19.8.1", + "@commitlint/execute-rule": "^19.8.1", + "@commitlint/resolve-extends": "^19.8.1", + "@commitlint/types": "^19.8.1", + "chalk": "^5.3.0", + "cosmiconfig": "^9.0.0", + "cosmiconfig-typescript-loader": "^6.1.0", + "lodash.isplainobject": "^4.0.6", + "lodash.merge": "^4.6.2", + "lodash.uniq": "^4.5.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/message": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/message/-/message-19.8.1.tgz", + "integrity": "sha512-+PMLQvjRXiU+Ae0Wc+p99EoGEutzSXFVwQfa3jRNUZLNW5odZAyseb92OSBTKCu+9gGZiJASt76Cj3dLTtcTdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/parse": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/parse/-/parse-19.8.1.tgz", + "integrity": "sha512-mmAHYcMBmAgJDKWdkjIGq50X4yB0pSGpxyOODwYmoexxxiUCy5JJT99t1+PEMK7KtsCtzuWYIAXYAiKR+k+/Jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/types": "^19.8.1", + "conventional-changelog-angular": "^7.0.0", + "conventional-commits-parser": "^5.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/read": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/read/-/read-19.8.1.tgz", + "integrity": "sha512-03Jbjb1MqluaVXKHKRuGhcKWtSgh3Jizqy2lJCRbRrnWpcM06MYm8th59Xcns8EqBYvo0Xqb+2DoZFlga97uXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/top-level": "^19.8.1", + "@commitlint/types": "^19.8.1", + "git-raw-commits": "^4.0.0", + "minimist": "^1.2.8", + "tinyexec": "^1.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/resolve-extends": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/resolve-extends/-/resolve-extends-19.8.1.tgz", + "integrity": "sha512-GM0mAhFk49I+T/5UCYns5ayGStkTt4XFFrjjf0L4S26xoMTSkdCf9ZRO8en1kuopC4isDFuEm7ZOm/WRVeElVg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/config-validator": "^19.8.1", + "@commitlint/types": "^19.8.1", + "global-directory": "^4.0.1", + "import-meta-resolve": "^4.0.0", + "lodash.mergewith": "^4.6.2", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/rules": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/rules/-/rules-19.8.1.tgz", + "integrity": "sha512-Hnlhd9DyvGiGwjfjfToMi1dsnw1EXKGJNLTcsuGORHz6SS9swRgkBsou33MQ2n51/boIDrbsg4tIBbRpEWK2kw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@commitlint/ensure": "^19.8.1", + "@commitlint/message": "^19.8.1", + "@commitlint/to-lines": "^19.8.1", + "@commitlint/types": "^19.8.1" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/to-lines": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/to-lines/-/to-lines-19.8.1.tgz", + "integrity": "sha512-98Mm5inzbWTKuZQr2aW4SReY6WUukdWXuZhrqf1QdKPZBCCsXuG87c+iP0bwtD6DBnmVVQjgp4whoHRVixyPBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/top-level": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/top-level/-/top-level-19.8.1.tgz", + "integrity": "sha512-Ph8IN1IOHPSDhURCSXBz44+CIu+60duFwRsg6HqaISFHQHbmBtxVw4ZrFNIYUzEP7WwrNPxa2/5qJ//NK1FGcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "find-up": "^7.0.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@commitlint/types": { + "version": "19.8.1", + "resolved": "https://registry.npmjs.org/@commitlint/types/-/types-19.8.1.tgz", + "integrity": "sha512-/yCrWGCoA1SVKOks25EGadP9Pnj0oAIHGpl2wH2M2Y46dPM2ueb8wyCVOD7O3WCTkaJ0IkKvzhl1JY7+uCT2Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/conventional-commits-parser": "^5.0.0", + "chalk": "^5.3.0" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@types/conventional-commits-parser": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@types/conventional-commits-parser/-/conventional-commits-parser-5.0.1.tgz", + "integrity": "sha512-7uz5EHdzz2TqoMfV7ee61Egf5y6NkcO4FB/1iCCQnbeiI1F3xzv3vK5dBCXUCLQgGYS+mUeigK1iKQzvED+QnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "24.5.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.5.2.tgz", + "integrity": "sha512-FYxk1I7wPv3K2XBaoyH2cTnocQEu8AOZ60hPbsyukMPLv5/5qr7V1i8PLHdl6Zf87I+xZXFvPCXYjiTFq+YSDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.12.0" + } + }, + "node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/array-ify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz", + "integrity": "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng==", + "dev": true, + "license": "MIT" + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/cachedir": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cachedir/-/cachedir-2.3.0.tgz", + "integrity": "sha512-A+Fezp4zxnit6FanDmv9EqXNAi3vt9DWp51/71UEhXukb7QUuvtv9344h91dyAxuTLoSYJFU299qzR3tzwPAhw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", + "dev": true, + "license": "MIT", + "dependencies": { + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/cli-width": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", + "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/commander": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", + "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/commitizen": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/commitizen/-/commitizen-4.3.1.tgz", + "integrity": "sha512-gwAPAVTy/j5YcOOebcCRIijn+mSjWJC+IYKivTu6aG8Ei/scoXgfsMRnuAk6b0GRste2J4NGxVdMN3ZpfNaVaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cachedir": "2.3.0", + "cz-conventional-changelog": "3.3.0", + "dedent": "0.7.0", + "detect-indent": "6.1.0", + "find-node-modules": "^2.1.2", + "find-root": "1.1.0", + "fs-extra": "9.1.0", + "glob": "7.2.3", + "inquirer": "8.2.5", + "is-utf8": "^0.2.1", + "lodash": "4.17.21", + "minimist": "1.2.7", + "strip-bom": "4.0.0", + "strip-json-comments": "3.1.1" + }, + "bin": { + "commitizen": "bin/commitizen", + "cz": "bin/git-cz", + "git-cz": "bin/git-cz" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/commitizen/node_modules/minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/compare-func": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/compare-func/-/compare-func-2.0.0.tgz", + "integrity": "sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-ify": "^1.0.0", + "dot-prop": "^5.1.0" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/conventional-changelog-angular": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/conventional-changelog-angular/-/conventional-changelog-angular-7.0.0.tgz", + "integrity": "sha512-ROjNchA9LgfNMTTFSIWPzebCwOGFdgkEq45EnvvrmSLvCtAw0HSmrCs7/ty+wAeYUZyNay0YMUNYFTRL72PkBQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "compare-func": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/conventional-changelog-conventionalcommits": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-7.0.2.tgz", + "integrity": "sha512-NKXYmMR/Hr1DevQegFB4MwfM5Vv0m4UIxKZTTYuD98lpTknaZlSRrDOG4X7wIXpGkfsYxZTghUN+Qq+T0YQI7w==", + "dev": true, + "license": "ISC", + "dependencies": { + "compare-func": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/conventional-commit-types": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/conventional-commit-types/-/conventional-commit-types-3.0.0.tgz", + "integrity": "sha512-SmmCYnOniSsAa9GqWOeLqc179lfr5TRu5b4QFDkbsrJ5TZjPJx85wtOr3zn+1dbeNiXDKGPbZ72IKbPhLXh/Lg==", + "dev": true, + "license": "ISC" + }, + "node_modules/conventional-commits-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz", + "integrity": "sha512-ZPMl0ZJbw74iS9LuX9YIAiW8pfM5p3yh2o/NbXHbkFuZzY5jvdi5jFycEOkmBW5H5I7nA+D6f3UcsCLP2vvSEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-text-path": "^2.0.0", + "JSONStream": "^1.3.5", + "meow": "^12.0.1", + "split2": "^4.0.0" + }, + "bin": { + "conventional-commits-parser": "cli.mjs" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/cosmiconfig": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", + "integrity": "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.1", + "import-fresh": "^3.3.0", + "js-yaml": "^4.1.0", + "parse-json": "^5.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + }, + "peerDependencies": { + "typescript": ">=4.9.5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/cosmiconfig-typescript-loader": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-6.1.0.tgz", + "integrity": "sha512-tJ1w35ZRUiM5FeTzT7DtYWAFFv37ZLqSRkGi2oeCK1gPhvaWjkAtfXvLmvE1pRfxxp9aQo6ba/Pvg1dKj05D4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "jiti": "^2.4.1" + }, + "engines": { + "node": ">=v18" + }, + "peerDependencies": { + "@types/node": "*", + "cosmiconfig": ">=9", + "typescript": ">=5" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cz-conventional-changelog": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/cz-conventional-changelog/-/cz-conventional-changelog-3.3.0.tgz", + "integrity": "sha512-U466fIzU5U22eES5lTNiNbZ+d8dfcHcssH4o7QsdWaCcRs/feIPCxKYSWkYBNs5mny7MvEfwpTLWjvbm94hecw==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^2.4.1", + "commitizen": "^4.0.3", + "conventional-commit-types": "^3.0.0", + "lodash.map": "^4.5.1", + "longest": "^2.0.1", + "word-wrap": "^1.0.3" + }, + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@commitlint/load": ">6.1.1" + } + }, + "node_modules/cz-conventional-changelog/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/cz-conventional-changelog/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/dargs": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/dargs/-/dargs-8.1.0.tgz", + "integrity": "sha512-wAV9QHOsNbwnWdNW2FYvE1P56wtgSbM+3SZcdGiWQILwVjACCXDCI3Ai8QlCjMDB8YK5zySiXZYBiwGmNY3lnw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==", + "dev": true, + "license": "MIT" + }, + "node_modules/defaults": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", + "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "clone": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-indent": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-6.1.0.tgz", + "integrity": "sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/dot-prop": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-5.3.0.tgz", + "integrity": "sha512-QM8q3zDe58hqUqjraQOmzZ1LIH9SWQJTlEKCH4kJ2oQvLZk7RbQXvtDM2XEq3fwkV9CCvvH4LA0AV+ogFsBM2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-obj": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/env-paths": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", + "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/error-ex": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "dev": true, + "license": "MIT" + }, + "node_modules/execa": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", + "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^8.0.1", + "human-signals": "^5.0.0", + "is-stream": "^3.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^5.1.0", + "onetime": "^6.0.0", + "signal-exit": "^4.1.0", + "strip-final-newline": "^3.0.0" + }, + "engines": { + "node": ">=16.17" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "homedir-polyfill": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/figures": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", + "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^1.0.5" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-node-modules": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/find-node-modules/-/find-node-modules-2.1.3.tgz", + "integrity": "sha512-UC2I2+nx1ZuOBclWVNdcnbDR5dlrOdVb7xNjmT/lHE+LsgztWks3dG7boJ37yTS/venXw84B/mAW9uHVoC5QRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "findup-sync": "^4.0.0", + "merge": "^2.1.1" + } + }, + "node_modules/find-root": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", + "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", + "dev": true, + "license": "MIT" + }, + "node_modules/find-up": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-7.0.0.tgz", + "integrity": "sha512-YyZM99iHrqLKjmt4LJDj58KI+fYyufRLBSYcqycxf//KpBk9FoewoGX0450m9nB44qrZnovzC2oeP5hUibxc/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^7.2.0", + "path-exists": "^5.0.0", + "unicorn-magic": "^0.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/findup-sync": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-4.0.0.tgz", + "integrity": "sha512-6jvvn/12IC4quLBL1KNokxC7wWTvYncaVUYSoxWw7YykPLuRrnv4qdHcSOywOI5RpkOVGeQRtWM8/q+G6W6qfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "detect-file": "^1.0.0", + "is-glob": "^4.0.0", + "micromatch": "^4.0.2", + "resolve-dir": "^1.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true, + "license": "ISC" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", + "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-stream": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", + "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/git-raw-commits": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-4.0.0.tgz", + "integrity": "sha512-ICsMM1Wk8xSGMowkOmPrzo2Fgmfo4bMHLNX6ytHjajRJUqvHOw/TFapQ+QG75c3X/tTDDhOSRPGC52dDbNM8FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dargs": "^8.0.0", + "meow": "^12.0.1", + "split2": "^4.0.0" + }, + "bin": { + "git-raw-commits": "cli.mjs" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "dev": true, + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/global-directory": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/global-directory/-/global-directory-4.0.1.tgz", + "integrity": "sha512-wHTUcDUoZ1H5/0iVqEudYW4/kAlN5cZ3j/bXn0Dpbizl9iaUVeWSHqiOjsgk6OW2bkLclbBjzewBz6weQ1zA2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ini": "4.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dev": true, + "license": "MIT", + "dependencies": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/global-prefix/node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC" + }, + "node_modules/global-prefix/node_modules/which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse-passwd": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/human-signals": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", + "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=16.17.0" + } + }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "license": "MIT", + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/import-fresh/node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/import-meta-resolve": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", + "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", + "dev": true, + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ini": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ini/-/ini-4.1.1.tgz", + "integrity": "sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/inquirer": { + "version": "8.2.5", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.5.tgz", + "integrity": "sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.2.1", + "chalk": "^4.1.1", + "cli-cursor": "^3.1.0", + "cli-width": "^3.0.0", + "external-editor": "^3.0.3", + "figures": "^3.0.0", + "lodash": "^4.17.21", + "mute-stream": "0.0.8", + "ora": "^5.4.1", + "run-async": "^2.4.0", + "rxjs": "^7.5.5", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0", + "through": "^2.3.6", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/inquirer/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/inquirer/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/inquirer/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/inquirer/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/inquirer/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-obj": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-2.0.0.tgz", + "integrity": "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", + "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-text-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-text-path/-/is-text-path-2.0.0.tgz", + "integrity": "sha512-+oDTluR6WEjdXEJMnC2z6A4FRwFoYuvShVVEGsS7ewc0UTi2QtAKMDJuL4BDEVt+5T7MjFo12RP8ghOM75oKJw==", + "dev": true, + "license": "MIT", + "dependencies": { + "text-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha512-rMYPYvCzsXywIsldgLaSoPlw5PfoB/ssr7hY4pLfcodrA5M/eArza1a9VmTiNIBNMjOGr1Ow9mTyU2o69U6U9Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/jiti": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.0.tgz", + "integrity": "sha512-VXe6RjJkBPj0ohtqaO8vSWP3ZhAKo66fKrFNCll4BTcwljPLz03pCbaNKfzGP5MbrCYcbJ7v0nOYYwUzTEIdXQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsonfile": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", + "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonparse": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", + "integrity": "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==", + "dev": true, + "engines": [ + "node >= 0.2.0" + ], + "license": "MIT" + }, + "node_modules/JSONStream": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/JSONStream/-/JSONStream-1.3.5.tgz", + "integrity": "sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==", + "dev": true, + "license": "(MIT OR Apache-2.0)", + "dependencies": { + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" + }, + "bin": { + "JSONStream": "bin.js" + }, + "engines": { + "node": "*" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lint-staged": { + "version": "15.5.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.5.2.tgz", + "integrity": "sha512-YUSOLq9VeRNAo/CTaVmhGDKG+LBtA8KF1X4K5+ykMSwWST1vDxJRB2kv2COgLb1fvpCo+A/y9A0G0znNVmdx4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^5.4.1", + "commander": "^13.1.0", + "debug": "^4.4.0", + "execa": "^8.0.1", + "lilconfig": "^3.1.3", + "listr2": "^8.2.5", + "micromatch": "^4.0.8", + "pidtree": "^0.6.0", + "string-argv": "^0.3.2", + "yaml": "^2.7.0" + }, + "bin": { + "lint-staged": "bin/lint-staged.js" + }, + "engines": { + "node": ">=18.12.0" + }, + "funding": { + "url": "https://opencollective.com/lint-staged" + } + }, + "node_modules/listr2": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.3.3.tgz", + "integrity": "sha512-LWzX2KsqcB1wqQ4AHgYb4RsDXauQiqhjLk+6hjbaeHG4zpjjVAB6wC/gz6X0l+Du1cN3pUB5ZlrvTbhGSNnUQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "cli-truncate": "^4.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.1.0", + "rfdc": "^1.4.1", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/listr2/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/locate-path": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-7.2.0.tgz", + "integrity": "sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^6.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.kebabcase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz", + "integrity": "sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.map": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.map/-/lodash.map-4.6.0.tgz", + "integrity": "sha512-worNHGKLDetmcEYDvh2stPCrrQRkP20E4l0iIS7F8EvzMqBBi7ltvFN5m1HvTf1P7Jk1txKhvFcmYsCr8O2F1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.mergewith": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz", + "integrity": "sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.startcase": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/lodash.startcase/-/lodash.startcase-4.4.0.tgz", + "integrity": "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/lodash.upperfirst": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz", + "integrity": "sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/log-symbols/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/log-symbols/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-symbols/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/log-symbols/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-escapes": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.1.1.tgz", + "integrity": "sha512-Zhl0ErHcSRUaVfGUeUdDuLgpkEo8KIFjB4Y9uAc46ScOpdDiU1Dbyplh7qWJeJ/ZHpbyMSM26+X3BySgnIz40Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/log-update/node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.5.0.tgz", + "integrity": "sha512-lb49vf1Xzfx080OKA0o6l8DQQpV+6Vg95zyCJX9VB/BqKYlhG7N4wgROUUHRA+ZPUefLnteQOad7z1kT2bV7bg==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-update/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/longest": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/longest/-/longest-2.0.1.tgz", + "integrity": "sha512-Ajzxb8CM6WAnFjgiloPsI3bF+WCxcvhdIG3KNA2KN962+tdBsHcuQ4k4qX/EcS/2CRkcc0iAkR956Nib6aXU/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/meow": { + "version": "12.1.1", + "resolved": "https://registry.npmjs.org/meow/-/meow-12.1.1.tgz", + "integrity": "sha512-BhXM0Au22RwUneMPwSCnyhTOizdWoIEPU9sp0Aqa1PnDMR5Wv2FGXYDjuzJEIX+Eo2Rb8xuYe5jrnm5QowQFkw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=16.10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/merge/-/merge-2.1.1.tgz", + "integrity": "sha512-jz+Cfrg9GWOZbQAnDQ4hlVnQky+341Yk5ru8bZSe6sIDTCIg8n9i/u7hSQGSVOF3C7lH6mGtqjkiT9G4wFLL0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "dev": true, + "license": "ISC" + }, + "node_modules/npm-run-path": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", + "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm-run-path/node_modules/path-key": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", + "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", + "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ora/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ora/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/ora/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ora/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ora/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/p-limit": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-4.0.0.tgz", + "integrity": "sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^1.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-6.0.0.tgz", + "integrity": "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-exists": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-5.0.0.tgz", + "integrity": "sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pidtree": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.6.0.tgz", + "integrity": "sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==", + "dev": true, + "license": "MIT", + "bin": { + "pidtree": "bin/pidtree.js" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/restore-cursor/node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/restore-cursor/node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "dev": true, + "license": "MIT" + }, + "node_modules/run-async": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", + "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.6.19" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", + "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/text-extensions": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/text-extensions/-/text-extensions-2.4.0.tgz", + "integrity": "sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.1.tgz", + "integrity": "sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD" + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.12.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.12.0.tgz", + "integrity": "sha512-goOacqME2GYyOZZfb5Lgtu+1IDmAlAEu5xnD3+xTzS10hT0vzpf0SPjkXwAw9Jm+4n/mQGDP3LO8CPbYROeBfQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicorn-magic": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", + "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, + "node_modules/wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", + "dev": true, + "license": "MIT", + "dependencies": { + "defaults": "^1.0.3" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/wrap-ansi/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.2.1.tgz", + "integrity": "sha512-AyeEbWOu/TAXdxlV9wmGcR0+yh2j3vYPGOECcIj2S7MkrLyC7ne+oye2BKTItt0ii2PHk4cDy+95+LshzbXnGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..bf8bff9d4 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "flw-api", + "version": "1.0.0", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "prepare": "husky", + "commit": "cz" + }, + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } + }, + "lint-staged": { + "src/**/*.{ts,js}": [ + "eslint --fix" + ], + "*.xml": [ + "xmllint --noout {{files}}" + ] + }, + "devDependencies": { + "@commitlint/cli": "^19.8.0", + "@commitlint/config-conventional": "^19.8.0", + "commitizen": "^4.3.1", + "cz-conventional-changelog": "^3.3.0", + "husky": "^9.1.7", + "lint-staged": "^15.5.1" + } +} \ No newline at end of file diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties index 238d5f926..8d24ebe9a 100644 --- a/src/main/environment/common_ci.properties +++ b/src/main/environment/common_ci.properties @@ -27,6 +27,9 @@ jwt.secret=@env.JWT_SECRET_KEY@ # Redis Config spring.redis.host=@env.REDIS_HOST@ +# Stop TB: when true, saves fail with an error if camp (vanID) is not configured +stoptb.enforce.vanid=@env.STOPTB_ENFORCE_VANID@ + cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@ #### SMS Configuration diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties index 073091334..c021fc52c 100644 --- a/src/main/environment/common_docker.properties +++ b/src/main/environment/common_docker.properties @@ -27,6 +27,9 @@ jwt.secret=${JWT_SECRET_KEY} # Redis Config spring.redis.host=${REDIS_HOST} +# Stop TB: when true, saves fail with an error if camp (vanID) is not configured +stoptb.enforce.vanid=${STOPTB_ENFORCE_VANID} + #### SMS Configuration send-sms=${SEND_SMS} source-address=${SMS_CONSENT_SOURCE_ADDRESS} diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties index 3c679d09c..7e8d43b09 100644 --- a/src/main/environment/common_example.properties +++ b/src/main/environment/common_example.properties @@ -24,11 +24,17 @@ 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 + +jwt.secret=eefa40497bb9b2a8491b85069aff62e7596521c6816e471c464181b52eac7670ff91394a + # Redis Config spring.redis.host=localhost +# Stop TB: when true, saves fail with an error if camp (vanID) is not configured +# instead of silently storing vanID=NULL (which then never gets synced to central) +stoptb.enforce.vanid=false + cors.allowed-origins=http://localhost:* source-address= diff --git a/src/main/environment/common_local.properties.bkp b/src/main/environment/common_local.properties.bkp new file mode 100644 index 000000000..b6463a03e --- /dev/null +++ b/src/main/environment/common_local.properties.bkp @@ -0,0 +1,49 @@ +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 + +# TM API URL +tm-url=https://amritdemo.piramalswasthya.org/tm-api +jwt.secret=eefa40497bb9b2a8491b85069aff62e7596521c6816e471c464181b52eac7670ff91394a diff --git a/src/main/java/com/iemr/flw/controller/DynamicFormController.java b/src/main/java/com/iemr/flw/controller/DynamicFormController.java new file mode 100644 index 000000000..59295cbf7 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/DynamicFormController.java @@ -0,0 +1,100 @@ +/* + * 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; + +import com.iemr.flw.dto.iemr.DynamicFormDTO; +import com.iemr.flw.service.DynamicFormDefinitionService; +import com.iemr.flw.utils.ApiResponse; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +/** + * REST controller for dynamic form definition management. + * All write operations use POST; all read operations use GET. + * Exceptions propagate to GlobalExceptionHandler — no local try-catch. + * + * @author Piramal Swasthya + */ +@Slf4j +@RequiredArgsConstructor +@RestController +@RequestMapping(value = "/dynamicForm", headers = "Authorization") +public class DynamicFormController { + + private final DynamicFormDefinitionService formService; + + @Operation(summary = "Create a full dynamic form definition with sections, questions, options and validations") + @RequestMapping(value = "/createForm", method = RequestMethod.POST) + public ResponseEntity createForm(@RequestBody @Valid DynamicFormDTO dto) { + return ResponseEntity.ok(new ApiResponse(true, null, formService.createForm(dto))); + } + + @Operation(summary = "Replace form structure and bump version (unchanged sections reused)") + @RequestMapping(value = "/updateForm", method = RequestMethod.POST) + public ResponseEntity updateForm( + @RequestParam Long formId, + @RequestBody @Valid DynamicFormDTO dto) { + return ResponseEntity.ok(new ApiResponse(true, null, formService.updateForm(formId, dto))); + } + + @Operation(summary = "Get form definition — latest version or specific version if ?version= provided") + @RequestMapping(value = "/getDefinition", method = RequestMethod.GET) + public ResponseEntity getFormDefinition( + @RequestParam Long formId, + @RequestParam(required = false) Integer version) { + Object result = version != null + ? formService.getFormDefinitionByVersion(formId, version) + : formService.getFormDefinition(formId); + return ResponseEntity.ok(new ApiResponse(true, null, result)); + } + + @Operation(summary = "Get metadata list of all active forms") + @RequestMapping(value = "/getAllForms", method = RequestMethod.GET) + public ResponseEntity getAllForms() { + return ResponseEntity.ok(new ApiResponse(true, null, formService.getAllForms())); + } + + @Operation(summary = "Activate a form (isActive = true)") + @RequestMapping(value = "/activateForm", method = RequestMethod.POST) + public ResponseEntity activateForm( + @RequestParam Long formId) { + formService.activateForm(formId); + return ResponseEntity.ok(new ApiResponse(true, "Form activated", null)); + } + + @Operation(summary = "Deactivate a form (isActive = false)") + @RequestMapping(value = "/deactivateForm", method = RequestMethod.POST) + public ResponseEntity deactivateForm( + @RequestParam Long formId) { + formService.deactivateForm(formId); + return ResponseEntity.ok(new ApiResponse(true, "Form deactivated", null)); + } + +} diff --git a/src/main/java/com/iemr/flw/controller/DynamicFormResponseController.java b/src/main/java/com/iemr/flw/controller/DynamicFormResponseController.java new file mode 100644 index 000000000..49d8e5479 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/DynamicFormResponseController.java @@ -0,0 +1,110 @@ +/* + * 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; + +import com.iemr.flw.dto.iemr.FormResponseDTO; +import com.iemr.flw.dto.iemr.FormResponseRequest; +import com.iemr.flw.masterEnum.FormType; +import com.iemr.flw.service.DynamicFormResponseService; +import com.iemr.flw.utils.ApiResponse; +import com.iemr.flw.utils.exception.IEMRException; +import io.swagger.v3.oas.annotations.Operation; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +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.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * REST controller for saving and retrieving dynamic form responses (beneficiary answers). + * All exceptions propagate to GlobalExceptionHandler — no local try-catch. + * + * @author Piramal Swasthya + */ +@RequiredArgsConstructor +@RestController +@RequestMapping(value = "/dynamicForm/response", headers = "Authorization") +public class DynamicFormResponseController { + + private final DynamicFormResponseService responseService; + + @Operation(summary = "Submit PRE_SUBMIT section answers, status → SUBMITTED. " + + "Pass responseId in body to re-submit an existing SUBMITTED response.") + @RequestMapping(value = "/submit", method = RequestMethod.POST) + public ResponseEntity submitForm( + @Valid @RequestBody FormResponseRequest request) { + FormResponseDTO dto = responseService.submitForm(request); + return ResponseEntity.ok(new ApiResponse(true, "Form submitted successfully", dto)); + } + + @Operation(summary = "Save POST_SUBMIT section answers, status → COMPLETE") + @RequestMapping(value = "/complete", method = RequestMethod.POST) + public ResponseEntity completeForm( + @Valid @RequestBody FormResponseRequest request, + @RequestHeader("JwtToken") String jwtToken) throws IEMRException { + FormResponseDTO dto = responseService.completeForm(request, jwtToken); + return ResponseEntity.ok(new ApiResponse(true, "Form completed successfully", dto)); + } + + @Operation(summary = "Submit multiple form responses in one bulk transaction. " + + "All-or-nothing: any failure rolls back all. responseId is populated for every saved item.") + @RequestMapping(value = "/submitBulk", method = RequestMethod.POST) + public ResponseEntity submitBulk( + @Valid @RequestBody List requests, + @RequestHeader("JwtToken") String jwtToken) { + List saved = responseService.submitBulk(requests, jwtToken); + return ResponseEntity.ok( + new ApiResponse(true, "Bulk submit complete: " + saved.size() + " saved", saved)); + } + + @Operation(summary = "Get all form responses for a beneficiary filtered by form UUID") + @RequestMapping(value = "/getByBeneficiary", method = RequestMethod.GET) + public ResponseEntity getByBeneficiary( + @RequestParam Long beneficiaryId, + @RequestParam String formUuid) { + List dtos = + responseService.getResponsesByBeneficiary(beneficiaryId, formUuid); + return ResponseEntity.ok(new ApiResponse(true, "Responses fetched successfully", dtos)); + } + + @Operation(summary = "Get a single form response with all nested answers") + @RequestMapping(value = "/getById", method = RequestMethod.GET) + public ResponseEntity getById(@RequestParam Long responseId) { + FormResponseDTO dto = responseService.getResponseById(responseId); + return ResponseEntity.ok(new ApiResponse(true, "Response fetched successfully", dto)); + } + @Operation(summary = "Get beneficiary IDs that have a COMPLETE form response for the given form type, optionally filtered by village and/or provider service map") + @RequestMapping(value = "/getCompletedBeneficiaries", method = RequestMethod.GET) + public ResponseEntity getCompletedBeneficiaries( + @RequestParam FormType formType, + @RequestParam(required = false) Integer villageId, + @RequestParam(required = false) Integer providerServiceMapId) { + List beneficiaryIds = responseService.getCompletedBeneficiaries(formType, villageId, providerServiceMapId); + return ResponseEntity.ok(new ApiResponse(true, "Completed beneficiaries fetched successfully", beneficiaryIds)); + } +} diff --git a/src/main/java/com/iemr/flw/controller/GlobalExceptionHandler.java b/src/main/java/com/iemr/flw/controller/GlobalExceptionHandler.java new file mode 100644 index 000000000..8470b97f5 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/GlobalExceptionHandler.java @@ -0,0 +1,154 @@ +/* + * 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; + +import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; +import com.iemr.flw.utils.ApiResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingRequestHeaderException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.NoSuchElementException; +import java.util.stream.Collectors; + +/** + * Converts all Spring MVC and application exceptions into a consistent ApiResponse envelope. + * + * @author Piramal Swasthya + */ +@RestControllerAdvice +public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** @Valid / @Validated failures — collect every field error into one readable message. */ + @Override + protected ResponseEntity handleMethodArgumentNotValid( + MethodArgumentNotValidException ex, + HttpHeaders headers, + HttpStatusCode status, + WebRequest request) { + + String message = ex.getBindingResult().getFieldErrors().stream() + .map(fe -> fe.getField() + ": " + fe.getDefaultMessage()) + .collect(Collectors.joining(", ")); + + log.warn("Validation failed: {}", message); + return ResponseEntity.badRequest() + .body(new ApiResponse(false, "Validation failed — " + message, null)); + } + + /** Malformed JSON body, including unrecognized field names. */ + @Override + protected ResponseEntity handleHttpMessageNotReadable( + HttpMessageNotReadableException ex, + HttpHeaders headers, + HttpStatusCode status, + WebRequest request) { + + String message = "Malformed JSON request body"; + if (ex.getCause() instanceof UnrecognizedPropertyException upe) { + message = "Unrecognized field '" + upe.getPropertyName() + + "' — use camelCase field names (e.g. sectionUuid, questionUuid)"; + } + log.warn("Unreadable request body: {}", ex.getMessage()); + return ResponseEntity.badRequest().body(new ApiResponse(false, message, null)); + } + + /** Invalid argument (e.g. null UUID field when wrong field name was sent). */ + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgument(IllegalArgumentException ex) { + log.warn("Illegal argument: {}", ex.getMessage()); + return ResponseEntity.badRequest() + .body(new ApiResponse(false, ex.getMessage(), null)); + } + + /** Required @RequestParam missing from the request. */ + @Override + protected ResponseEntity handleMissingServletRequestParameter( + MissingServletRequestParameterException ex, + HttpHeaders headers, + HttpStatusCode status, + WebRequest request) { + + log.warn("Missing request parameter: {}", ex.getParameterName()); + return ResponseEntity.badRequest() + .body(new ApiResponse(false, + "Missing required parameter: '" + ex.getParameterName() + "'", null)); + } + + /** Required @RequestHeader missing from the request. */ + @ExceptionHandler(MissingRequestHeaderException.class) + public ResponseEntity handleMissingHeader(MissingRequestHeaderException ex) { + log.warn("Missing required header: {}", ex.getHeaderName()); + return ResponseEntity.badRequest() + .body(new ApiResponse(false, + "Missing required header: '" + ex.getHeaderName() + "'", null)); + } + + /** Wrong type for a @RequestParam or @PathVariable (e.g. "abc" passed for a Long). */ + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity handleTypeMismatch(MethodArgumentTypeMismatchException ex) { + String expected = ex.getRequiredType() != null ? ex.getRequiredType().getSimpleName() : "unknown"; + String message = "Invalid value '" + ex.getValue() + + "' for parameter '" + ex.getName() + + "' — expected type: " + expected; + log.warn("Type mismatch: {}", message); + return ResponseEntity.badRequest().body(new ApiResponse(false, message, null)); + } + + /** Entity not found (thrown by service layer orElseThrow). */ + @ExceptionHandler(NoSuchElementException.class) + public ResponseEntity handleNotFound(NoSuchElementException ex) { + log.warn("Resource not found: {}", ex.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(new ApiResponse(false, ex.getMessage(), null)); + } + + /** Invalid lifecycle transition (e.g. completing a non-SUBMITTED response). */ + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalState(IllegalStateException ex) { + log.warn("Illegal state: {}", ex.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT) + .body(new ApiResponse(false, ex.getMessage(), null)); + } + + /** Catch-all for anything not handled above. */ + @ExceptionHandler(Exception.class) + public ResponseEntity handleGeneric(Exception ex) { + log.error("Unhandled exception: {}", ex.getMessage(), ex); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ApiResponse(false, ex.getMessage(), null)); + } +} diff --git a/src/main/java/com/iemr/flw/controller/StopTBController.java b/src/main/java/com/iemr/flw/controller/StopTBController.java new file mode 100644 index 000000000..7f73d29e2 --- /dev/null +++ b/src/main/java/com/iemr/flw/controller/StopTBController.java @@ -0,0 +1,161 @@ +package com.iemr.flw.controller; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.iemr.flw.service.StopTBService; +import com.iemr.flw.utils.response.OutputResponse; +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.web.bind.annotation.*; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/stoptb") +public class StopTBController { + + private final Logger logger = LoggerFactory.getLogger(StopTBController.class); + + // serializeNulls() so fields with no value (e.g. hivStatus, keyPopulationRiskFactor*) + // still appear in the response as null instead of being silently dropped + private final Gson gson = new GsonBuilder().serializeNulls().create(); + + @Autowired + private StopTBService stopTBService; + + // ── Nurse: General Examination ──────────────────────────────────────────── + + @PostMapping("/nurse/generalExamination/save") + @Operation(summary = "Save general examination for Stop TB beneficiary (array of objects)") + public String saveGeneralExamination(@RequestBody List> dataList) { + OutputResponse response = new OutputResponse(); + try { + List> result = stopTBService.saveGeneralExamination(dataList); + response.setResponse(gson.toJson(result)); + } catch (Exception e) { + logger.error("Error in saveGeneralExamination: " + e); + response.setError(5000, "Error saving general examination: " + e.getMessage()); + } + return response.toString(); + } + + @PostMapping("/nurse/generalExamination/getAll") + @Operation(summary = "Get all general examinations for a camp") + public String getAllGeneralExaminations(@RequestBody Map body) { + OutputResponse response = new OutputResponse(); + try { + Object raw = body.get("providerServiceMapID"); + if (raw == null) throw new Exception("providerServiceMapID is required"); + Integer villageID = body.get("villageID") != null ? Integer.parseInt(body.get("villageID").toString()) : null; + Map data = stopTBService.getAllGeneralExaminations(Integer.parseInt(raw.toString()), villageID); + response.setResponse(gson.toJson(data)); + } catch (Exception e) { + logger.error("Error in getAllGeneralExaminations: " + e); + response.setError(5000, "Error fetching general examinations: " + e.getMessage()); + } + return response.toString(); + } + + // ── Nurse: TB Screening ─────────────────────────────────────────────────── + + @PostMapping("/nurse/tbScreening/save") + @Operation(summary = "Save TB screening for Stop TB beneficiary (array of objects)") + public String saveNurseTBScreening(@RequestBody List> dataList) { + OutputResponse response = new OutputResponse(); + try { + List> result = stopTBService.saveNurseTBScreening(dataList); + response.setResponse(gson.toJson(result)); + } catch (Exception e) { + logger.error("Error in saveNurseTBScreening: " + e); + response.setError(5000, "Error saving TB screening: " + e.getMessage()); + } + return response.toString(); + } + + @PostMapping("/nurse/tbScreening/getAll") + @Operation(summary = "Get all TB screenings for a camp") + public String getAllNurseTBScreenings(@RequestBody Map body) { + OutputResponse response = new OutputResponse(); + try { + Object raw = body.get("providerServiceMapID"); + if (raw == null) throw new Exception("providerServiceMapID is required"); + Integer villageID = body.get("villageID") != null ? Integer.parseInt(body.get("villageID").toString()) : null; + Map data = stopTBService.getAllNurseTBScreenings(Integer.parseInt(raw.toString()), villageID); + response.setResponse(gson.toJson(data)); + } catch (Exception e) { + logger.error("Error in getAllNurseTBScreenings: " + e); + response.setError(5000, "Error fetching TB screenings: " + e.getMessage()); + } + return response.toString(); + } + + // ── Nurse: General OPD ──────────────────────────────────────────────────── + + @PostMapping("/nurse/generalOpd/save") + @Operation(summary = "Save general OPD record for Stop TB beneficiary (array of objects)") + public String saveGeneralOpd(@RequestBody List> dataList) { + OutputResponse response = new OutputResponse(); + try { + List> result = stopTBService.saveGeneralOpd(dataList); + response.setResponse(gson.toJson(result)); + } catch (Exception e) { + logger.error("Error in saveGeneralOpd: " + e); + response.setError(5000, "Error saving general OPD: " + e.getMessage()); + } + return response.toString(); + } + + @PostMapping("/nurse/generalOpd/getAll") + @Operation(summary = "Get all general OPD records for a camp") + public String getAllGeneralOpd(@RequestBody Map body) { + OutputResponse response = new OutputResponse(); + try { + Object raw = body.get("providerServiceMapID"); + if (raw == null) throw new Exception("providerServiceMapID is required"); + Integer villageID = body.get("villageID") != null ? Integer.parseInt(body.get("villageID").toString()) : null; + Map data = stopTBService.getAllGeneralOpd(Integer.parseInt(raw.toString()), villageID); + response.setResponse(gson.toJson(data)); + } catch (Exception e) { + logger.error("Error in getAllGeneralOpd: " + e); + response.setError(5000, "Error fetching general OPD records: " + e.getMessage()); + } + return response.toString(); + } + + // ── Nurse: Diagnostics ─────────────────────────────────────────────────── + + @PostMapping("/nurse/diagnostics/save") + @Operation(summary = "Save diagnostics for Stop TB beneficiary (array of objects)") + public String saveDiagnostics(@RequestBody List> dataList) { + OutputResponse response = new OutputResponse(); + try { + List> result = stopTBService.saveDiagnostics(dataList); + response.setResponse(gson.toJson(result)); + } catch (Exception e) { + logger.error("Error in saveDiagnostics: " + e); + response.setError(5000, "Error saving diagnostics: " + e.getMessage()); + } + return response.toString(); + } + + @PostMapping("/nurse/diagnostics/getAll") + @Operation(summary = "Get all diagnostics records for a camp") + public String getAllDiagnostics(@RequestBody Map body) { + OutputResponse response = new OutputResponse(); + try { + Object raw = body.get("providerServiceMapID"); + if (raw == null) throw new Exception("providerServiceMapID is required"); + Integer villageID = body.get("villageID") != null ? Integer.parseInt(body.get("villageID").toString()) : null; + Map data = stopTBService.getAllDiagnostics(Integer.parseInt(raw.toString()), villageID); + response.setResponse(gson.toJson(data)); + } catch (Exception e) { + logger.error("Error in getAllDiagnostics: " + e); + response.setError(5000, "Error fetching diagnostics records: " + e.getMessage()); + } + return response.toString(); + } + +} diff --git a/src/main/java/com/iemr/flw/controller/TBController.java b/src/main/java/com/iemr/flw/controller/TBController.java index e95c3ab4c..becc387a9 100644 --- a/src/main/java/com/iemr/flw/controller/TBController.java +++ b/src/main/java/com/iemr/flw/controller/TBController.java @@ -168,13 +168,16 @@ public String saveConfirmedCase( @Operation(summary = "get tb confirmed case by beneficiary id") @RequestMapping(value = { "/confirmed/getAll" }, method = { RequestMethod.GET }) public String getConfirmedByBenId( - @RequestHeader(value = "jwtToken") String token) { + @RequestHeader(value = "jwtToken") String token, + @RequestParam(required = false) Integer providerServiceMapID, + @RequestParam(required = false) Integer villageID) { OutputResponse response = new OutputResponse(); try { - String result = - tbConfirmedCaseService.getByUserId(token); + String result = providerServiceMapID != null + ? tbConfirmedCaseService.getByProviderServiceMapId(providerServiceMapID, villageID) + : tbConfirmedCaseService.getByUserId(token); if (result != null) response.setResponse(result); diff --git a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java index 884f794d1..8eb5eb412 100644 --- a/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java +++ b/src/main/java/com/iemr/flw/controller/VillageLevelFormController.java @@ -45,108 +45,132 @@ public class VillageLevelFormController { @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 { + try { + 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); + + } + } catch (Exception e) { response.put("status", "Fail"); - response.put("statusCode", 400); - response.put("message", "Invalid Request Object"); - return ResponseEntity.ok(response); - + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - } @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 { + try { + 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); + } + } catch (Exception e) { response.put("status", "Fail"); - response.put("statusCode", 400); - response.put("message", "Invalid Request Object"); - return ResponseEntity.ok(response); - - + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - } @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 { + try { + 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); + } + } catch (Exception e) { response.put("status", "Fail"); - response.put("statusCode", 400); - response.put("message", "Invalid Request Object"); - return ResponseEntity.ok(response); - + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - - } @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 { + try { + 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); + } + } catch (Exception e) { response.put("status", "Fail"); - response.put("statusCode", 400); - response.put("message", "Invalid Request Object"); - return ResponseEntity.ok(response); + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - } @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 { + try { + 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); + } + } catch (Exception e) { response.put("status", "Fail"); - response.put("statusCode", 400); - response.put("message", "Invalid Request Object"); - return ResponseEntity.ok(response); + response.put("statusCode", 500); + response.put("errorMessage", e.getMessage()); + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); } - } 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 297694b7c..e227776cf 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHBeneficiaryDetailsRmnch.java @@ -102,6 +102,28 @@ public class RMNCHBeneficiaryDetailsRmnch { @Column(name = "longitude") private BigDecimal longitude; + @Column(name = "gpsLatitude") + private Double gpsLatitude; + + @Column(name = "gpsLongitude") + private Double gpsLongitude; + + @Expose + @Column(name = "digipin") + private String digipin; + + @Expose + @Column(name = "gpsTimestamp") + private Timestamp gpsTimestamp; + + @Expose + @Column(name = "isGpsUnavailable", nullable = false, columnDefinition = "TINYINT(1) DEFAULT 0") + private Boolean isGpsUnavailable = false; + + @Expose + @Column(name = "gpsUnavailableReason") + private String gpsUnavailableReason; + @Expose @Column(name = "menstrualBFDId") private Integer menstrualBFDId; @@ -412,6 +434,9 @@ public class RMNCHBeneficiaryDetailsRmnch { @Expose @Transient private String addressLine3; + @Expose + @Transient + private String pinCode; // ---------------------------------------------- @@ -521,4 +546,31 @@ public class RMNCHBeneficiaryDetailsRmnch { @Column(name = "noOfDaysForDelivery") private Integer noOfDaysForDelivery; + @Expose + @Transient + private String occupation; + @Expose + @Transient + private String economicStatus; + @Expose + @Transient + private Integer economicStatusId; + @Expose + @Transient + private String residentialArea; + @Expose + @Transient + private Integer residentialAreaId; + + public String getOccupation() { return occupation; } + public void setOccupation(String occupation) { this.occupation = occupation; } + public String getEconomicStatus() { return economicStatus; } + public void setEconomicStatus(String economicStatus) { this.economicStatus = economicStatus; } + public Integer getEconomicStatusId() { return economicStatusId; } + public void setEconomicStatusId(Integer economicStatusId) { this.economicStatusId = economicStatusId; } + public String getResidentialArea() { return residentialArea; } + public void setResidentialArea(String residentialArea) { this.residentialArea = residentialArea; } + public Integer getResidentialAreaId() { return residentialAreaId; } + public void setResidentialAreaId(Integer residentialAreaId) { this.residentialAreaId = residentialAreaId; } + } 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 3a3ccec86..a0a0adf15 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHHouseHoldDetails.java @@ -329,4 +329,12 @@ public class RMNCHHouseHoldDetails { @Column(name = "isDeactivate") private Boolean isDeactivate; + @Expose + @Column(name = "gpsLatitude") + private Double gpsLatitude; + + @Expose + @Column(name = "gpsLongitude") + private Double gpsLongitude; + } diff --git a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java index c94686888..a589ec7ac 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiaryaddress.java @@ -247,4 +247,22 @@ public class RMNCHMBeneficiaryaddress implements Serializable { @Expose @Column(name = "SyncedDate") private Timestamp SyncedDate; + + @Column(name = "gpsLatitude") + private Double gpsLatitude; + + @Column(name = "gpsLongitude") + private Double gpsLongitude; + + @Column(name = "digipin") + private String digipin; + + @Column(name = "gpsTimestamp") + private Timestamp gpsTimestamp; + + @Column(name = "isGpsUnavailable", nullable = false, columnDefinition = "TINYINT(1) DEFAULT 0") + private Boolean isGpsUnavailable = false; + + @Column(name = "gpsUnavailableReason") + private String gpsUnavailableReason; } 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 779a09da4..1a4cec51d 100644 --- a/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java +++ b/src/main/java/com/iemr/flw/domain/identity/RMNCHMBeneficiarydetail.java @@ -190,4 +190,27 @@ public class RMNCHMBeneficiarydetail { @Column(name = "familyid") private String familyId; + @Column(name = "ExtraFields") + private String otherFields; + + @Expose + @Column(name = "economicStatus") + private String economicStatus; + + @Expose + @Column(name = "economicStatusId") + private Integer economicStatusId; + + @Expose + @Column(name = "residentialArea") + private String residentialArea; + + @Expose + @Column(name = "residentialAreaId") + private Integer residentialAreaId; + + @Expose + @Column(name = "address") + private String address; + } diff --git a/src/main/java/com/iemr/flw/domain/iemr/BenAnthropometryDetail.java b/src/main/java/com/iemr/flw/domain/iemr/BenAnthropometryDetail.java new file mode 100644 index 000000000..777e80118 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/BenAnthropometryDetail.java @@ -0,0 +1,70 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_phy_anthropometry", schema = "db_iemr") +@Data +public class BenAnthropometryDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Long id; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "Weight_Kg") + private Double weightKg; + + @Column(name = "Height_cm") + private Double heightCm; + + @Column(name = "BMI") + private Double bmi; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "VanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/BenChiefComplaint.java b/src/main/java/com/iemr/flw/domain/iemr/BenChiefComplaint.java new file mode 100644 index 000000000..3b016c5fc --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/BenChiefComplaint.java @@ -0,0 +1,73 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_benchiefcomplaint", schema = "db_iemr") +@Data +public class BenChiefComplaint { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Long id; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "ChiefComplaint") + private String chiefComplaint; + + @Column(name = "Duration") + private Integer duration; + + @Column(name = "UnitOfDuration") + private String unitOfDuration; + + @Column(name = "Description") + private String description; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "VanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/BenFlowStatus.java b/src/main/java/com/iemr/flw/domain/iemr/BenFlowStatus.java new file mode 100644 index 000000000..b4600e265 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/BenFlowStatus.java @@ -0,0 +1,82 @@ +package com.iemr.flw.domain.iemr; + +import lombok.Data; +import jakarta.persistence.*; +import java.sql.Timestamp; + +@Entity +@Table(name = "i_ben_flow_outreach") +@Data +public class BenFlowStatus { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ben_flow_id") + private Long benFlowID; + + @Column(name = "beneficiary_reg_id") + private Long beneficiaryRegID; + + @Column(name = "beneficiary_id") + private Long beneficiaryID; + + @Column(name = "visit_category") + private String visitCategory; + + @Column(name = "nurse_flag") + private Short nurseFlag; + + @Column(name = "doctor_flag") + private Short doctorFlag; + + @Column(name = "pharmacist_flag") + private Short pharmacistFlag; + + @Column(name = "providerServiceMapID") + private Integer providerServiceMapId; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "ben_name") + private String benName; + + @Column(name = "ben_age_val") + private Integer benAgeVal; + + @Column(name = "ben_dob") + private Timestamp dob; + + @Column(name = "ben_gender_val") + private Short genderID; + + @Column(name = "ben_gender") + private String genderName; + + @Column(name = "ben_phone_no") + private String preferredPhoneNum; + + @Column(name = "districtID") + private Integer districtID; + + @Column(name = "district") + private String districtName; + + @Column(name = "villageID") + private Integer villageID; + + @Column(name = "village") + private String villageName; + + @Column(name = "registrationDate") + private Timestamp registrationDate; + + @Column(name = "created_by") + private String agentId; + + @Column(name = "created_date", insertable = false, updatable = false) + private Timestamp visitDate; + + @Column(name = "deleted", insertable = false) + private Boolean deleted; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/BenPhysicalVitalDetail.java b/src/main/java/com/iemr/flw/domain/iemr/BenPhysicalVitalDetail.java new file mode 100644 index 000000000..15b03aee4 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/BenPhysicalVitalDetail.java @@ -0,0 +1,76 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_phy_vitals", schema = "db_iemr") +@Data +public class BenPhysicalVitalDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Long id; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "Temperature") + private Double temperature; + + @Column(name = "PulseRate") + private Short pulseRate; + + @Column(name = "SystolicBP_1stReading") + private Short systolicBP; + + @Column(name = "DiastolicBP_1stReading") + private Short diastolicBP; + + @Column(name = "BloodGlucose_Random") + private Short bloodGlucoseRandom; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "VanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/DynamicForm.java b/src/main/java/com/iemr/flw/domain/iemr/DynamicForm.java new file mode 100644 index 000000000..af183d66c --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/DynamicForm.java @@ -0,0 +1,128 @@ +/* + * 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 com.iemr.flw.masterEnum.FormType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Table; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +/** + * Root entity for a dynamic form definition (e.g. TB Counselling Form). + */ +@Entity +@Table(name = "t_dynamic_form", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DynamicForm { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "formId") + private Long formId; + + @Column(name = "formUuid", unique = true, nullable = false, length = 100) + private String formUuid; + + @Column(name = "formName", nullable = false, length = 255) + private String formName; + + @Enumerated(EnumType.STRING) + @Column(name = "formType", nullable = false, length = 50) + private FormType formType; + + @Column(name = "isActive", nullable = false) + private Boolean isActive = true; + + /** Days after the most-recently-completed section before the next follow-up notification fires. + * Null means no follow-up notifications for this form. */ + @Column(name = "follow_up_delay_days") + private Integer followUpDelayDays; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "createdAt", nullable = false, updatable = false) + private Timestamp createdAt; + + @Column(name = "updatedAt", nullable = false) + private Timestamp updatedAt; + + @OneToMany(mappedBy = "dynamicForm", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List versions = new ArrayList<>(); + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; + + @PrePersist + protected void onCreate() { + createdAt = new Timestamp(System.currentTimeMillis()); + updatedAt = new Timestamp(System.currentTimeMillis()); + } + + @PreUpdate + protected void onUpdate() { + updatedAt = new Timestamp(System.currentTimeMillis()); + } +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/FormResponse.java b/src/main/java/com/iemr/flw/domain/iemr/FormResponse.java new file mode 100644 index 000000000..8b338ee54 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/FormResponse.java @@ -0,0 +1,137 @@ +/* + * 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 jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.PrePersist; +import jakarta.persistence.PreUpdate; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; + +/** + * Root entity for a beneficiary's response to a dynamic form. + * Tracks the exact form version used and the status lifecycle (DRAFT → SUBMITTED → COMPLETE). + * + * @author Piramal Swasthya + */ +@Entity +@Table(name = "t_form_response", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class FormResponse { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "responseId") + private Long responseId; + + @Column(name = "beneficiaryId", nullable = false) + private Long beneficiaryId; + + /** Denormalized from versionId for fast form-level queries. */ + @Column(name = "formId", nullable = false) + private Long formId; + + /** Exact FormVersion active at submission time — resolved server-side from isLatest=true. */ + @Column(name = "versionId", nullable = false) + private Long versionId; + + /** Logged-in ASHA/officer ID from the request body. */ + @Column(name = "officerId", nullable = false) + private Long officerId; + + /** DRAFT | SUBMITTED | COMPLETE */ + @Column(name = "status", nullable = false, length = 20) + private String status; + + /** Set when PRE_SUBMIT sections are saved via /submit. */ + @Column(name = "submittedAt") + private Timestamp submittedAt; + + /** Set when POST_SUBMIT sections are saved via /complete. */ + @Column(name = "completedAt") + private Timestamp completedAt; + + /** Updated to now() each time the most-recently-completed section is saved (PRE_SUBMIT or any + * POST_SUBMIT section). The follow-up notification scheduler uses this as its reference date. */ + @Column(name = "last_follow_up_at") + private Timestamp lastFollowUpAt; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "createdAt", nullable = false, updatable = false) + private Timestamp createdAt; + + @Column(name = "updatedAt", nullable = false) + private Timestamp updatedAt; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + @Builder.Default + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; + + @PrePersist + protected void onCreate() { + createdAt = new Timestamp(System.currentTimeMillis()); + updatedAt = new Timestamp(System.currentTimeMillis()); + if (status == null) { + status = "DRAFT"; + } + } + + @PreUpdate + protected void onUpdate() { + updatedAt = new Timestamp(System.currentTimeMillis()); + } +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/FormSection.java b/src/main/java/com/iemr/flw/domain/iemr/FormSection.java new file mode 100644 index 000000000..b84547166 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/FormSection.java @@ -0,0 +1,118 @@ +/* + * 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 jakarta.persistence.CascadeType; +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.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +/** + * A section within a dynamic form version (e.g. "Section A: Disease Awareness"). + * Each section belongs to exactly one FormVersion via the version_id FK. + */ +@Entity +@Table(name = "t_form_section", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FormSection { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "sectionId") + private Long sectionId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "version_id", nullable = false) + @ToString.Exclude + private FormVersion formVersion; + + @Column(name = "sectionUuid", nullable = false, length = 100) + private String sectionUuid; + + @Column(name = "sectionName", nullable = false, length = 255) + private String sectionName; + + @Column(name = "sectionName_hindi", length = 255) + private String sectionNameHindi; + + /** PRE_SUBMIT sections are shown before the form's main submit. POST_SUBMIT after. */ + @Column(name = "sectionPhase", nullable = false, length = 20) + private String sectionPhase; + + @Column(name = "isRequired", nullable = false) + private Boolean isRequired = true; + + @Column(name = "displayOrder", nullable = false) + private Integer displayOrder; + + /** True only on the last PRE_SUBMIT section — renders the Submit button. */ + @Column(name = "hasSubmitButton", nullable = false) + private Boolean hasSubmitButton = false; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @OneToMany(mappedBy = "formSection", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List questions = new ArrayList<>(); + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/FormVersion.java b/src/main/java/com/iemr/flw/domain/iemr/FormVersion.java new file mode 100644 index 000000000..5902aa218 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/FormVersion.java @@ -0,0 +1,115 @@ +/* + * 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 jakarta.persistence.CascadeType; +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.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.PrePersist; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +/** + * A versioned snapshot of a dynamic form's section structure. + * Every structural change creates a new FormVersion; only one version has isLatest=true per form. + * + * @author Piramal Swasthya + */ +@Entity +@Table(name = "t_form_version", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FormVersion { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "versionId") + private Long versionId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "formId", nullable = false) + @ToString.Exclude + private DynamicForm dynamicForm; + + @Column(name = "versionNumber", nullable = false) + private Integer versionNumber; + + @Column(name = "isLatest", nullable = false) + private Boolean isLatest = true; + + @Column(name = "createdAt", nullable = false, updatable = false) + private Timestamp createdAt; + + @Column(name = "createdBy", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "notes", columnDefinition = "TEXT") + private String notes; + + @OneToMany(mappedBy = "formVersion", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List sections = new ArrayList<>(); + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; + + @PrePersist + protected void onCreate() { + createdAt = new Timestamp(System.currentTimeMillis()); + } +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java b/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java index cd7384e15..bc30e7dd4 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java +++ b/src/main/java/com/iemr/flw/domain/iemr/MalariaFollowUp.java @@ -2,7 +2,9 @@ import jakarta.persistence.*; import lombok.Data; +import org.hibernate.annotations.UpdateTimestamp; +import java.sql.Timestamp; import java.util.Date; @Entity @@ -47,4 +49,11 @@ public class MalariaFollowUp { @Column(name = "referral_date") @Temporal(TemporalType.DATE) private Date referralDate; + + @Column(name = "modified_by") + private String modifiedBy; + + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/OptionCondition.java b/src/main/java/com/iemr/flw/domain/iemr/OptionCondition.java new file mode 100644 index 000000000..50af2b382 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/OptionCondition.java @@ -0,0 +1,103 @@ +/* + * 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 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.ManyToOne; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; + +/** + * Conditional action triggered when a specific option is selected. + * actionType: SHOW_QUESTION | DISABLE_SECTION_VALIDATION | LOCK_FORM + * Exactly one of targetQuestion / targetSection is non-null per row. + */ +@Entity +@Table(name = "t_option_condition", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OptionCondition { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "conditionId") + private Long conditionId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "optionId", nullable = false) + @ToString.Exclude + private QuestionOption questionOption; + + @Column(name = "actionType", nullable = false, length = 40) + private String actionType; + + /** Set when actionType = SHOW_QUESTION. */ + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "targetQuestionId", nullable = true) + @ToString.Exclude + private SectionQuestion targetQuestion; + + /** Set when actionType = DISABLE_SECTION_VALIDATION. */ + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "targetSectionId", nullable = true) + @ToString.Exclude + private FormSection targetSection; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/PhyGeneralExamination.java b/src/main/java/com/iemr/flw/domain/iemr/PhyGeneralExamination.java new file mode 100644 index 000000000..b99fd804b --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PhyGeneralExamination.java @@ -0,0 +1,79 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_Phy_GeneralExam", schema = "db_iemr") +@Data +public class PhyGeneralExamination { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Long id; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "Pallor") + private String pallor; + + @Column(name = "Jaundice") + private String jaundice; + + @Column(name = "Cyanosis") + private String cyanosis; + + @Column(name = "Clubbing") + private String clubbing; + + @Column(name = "Lymphadenopathy") + private String lymphadenopathy; + + @Column(name = "Edema") + private String edema; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/PrescribedDrugDetail.java b/src/main/java/com/iemr/flw/domain/iemr/PrescribedDrugDetail.java new file mode 100644 index 000000000..9a0a1502c --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PrescribedDrugDetail.java @@ -0,0 +1,82 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_prescribeddrug", schema = "db_iemr") +@Data +public class PrescribedDrugDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "PrescribedDrugID", insertable = false, updatable = false) + private Long id; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "PrescriptionID") + private Long prescriptionID; + + @Column(name = "GenericDrugName") + private String drugName; + + @Column(name = "Dose") + private String dose; + + @Column(name = "Frequency") + private String frequency; + + @Column(name = "Duration") + private String duration; + + @Column(name = "DuartionUnit") + private String durationUnit; + + @Column(name = "SpecialInstruction") + private String specialInstruction; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "VanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/PrescriptionDetail.java b/src/main/java/com/iemr/flw/domain/iemr/PrescriptionDetail.java new file mode 100644 index 000000000..5bc5295d6 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/PrescriptionDetail.java @@ -0,0 +1,70 @@ +package com.iemr.flw.domain.iemr; + +import jakarta.persistence.*; +import lombok.Data; +import java.sql.Timestamp; + +@Entity +@Table(name = "t_prescription", schema = "db_iemr") +@Data +public class PrescriptionDetail { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "PrescriptionID", insertable = false, updatable = false) + private Long prescriptionID; + + @Column(name = "BeneficiaryRegID") + private Long beneficiaryRegID; + + @Column(name = "BenVisitID") + private Long benVisitID; + + @Column(name = "ProviderServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "VisitCode") + private Long visitCode; + + @Column(name = "DiagnosisProvided") + private String diagnosisProvided; + + @Column(name = "Instruction") + private String instruction; + + @Column(name = "Remarks") + private String remarks; + + @Column(name = "Deleted", insertable = false, updatable = true) + private Boolean deleted; + + @Column(name = "Processed", insertable = false, updatable = true) + private String processed; + + @Column(name = "CreatedBy") + private String createdBy; + + @Column(name = "CreatedDate", insertable = false, updatable = false) + private Timestamp createdDate; + + @Column(name = "ModifiedBy") + private String modifiedBy; + + @Column(name = "LastModDate", insertable = false, updatable = false) + private Timestamp lastModDate; + + @Column(name = "VanSerialNo") + private Long vanSerialNo; + + @Column(name = "VanID") + private Integer vanID; + + @Column(name = "ParkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "SyncedBy") + private String syncedBy; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/QuestionOption.java b/src/main/java/com/iemr/flw/domain/iemr/QuestionOption.java new file mode 100644 index 000000000..2bc02cbdc --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/QuestionOption.java @@ -0,0 +1,109 @@ +/* + * 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 jakarta.persistence.CascadeType; +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.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +/** + * A selectable option for a RADIO or MCQ question. + */ +@Entity +@Table(name = "t_question_option", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QuestionOption { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "optionId") + private Long optionId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "questionId", nullable = false) + @ToString.Exclude + private SectionQuestion sectionQuestion; + + @Column(name = "optionLabel", nullable = false, length = 255) + private String optionLabel; + + @Column(name = "optionLabel_hindi", length = 100) + private String optionLabelHindi; + + @Column(name = "optionValue", nullable = false, length = 100) + private String optionValue; + + @Column(name = "optionValue_hindi", length = 100) + private String optionValueHindi; + + @Column(name = "displayOrder", nullable = false) + private Integer displayOrder; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @OneToMany(mappedBy = "questionOption", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List conditions = new ArrayList<>(); + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/QuestionResponse.java b/src/main/java/com/iemr/flw/domain/iemr/QuestionResponse.java new file mode 100644 index 000000000..aabfc8778 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/QuestionResponse.java @@ -0,0 +1,103 @@ +/* + * 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 jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Lob; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; + +/** + * Stores one answer to a single question within a section response. + * MCQ questions produce multiple rows (one per selected option) — no unique constraint on (sectionResponseId, questionId). + * RADIO: optionId set, answerText null. + * MCQ: optionId set per selection, answerText null. + * TEXT/DATE/AUTO_FILL: answerText set, optionId null. + * DISPLAY: no row stored (read-only question type). + * + * @author Piramal Swasthya + */ +@Entity +@Table(name = "t_question_response", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class QuestionResponse { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "questionResponseId") + private Long questionResponseId; + + @Column(name = "sectionResponseId", nullable = false) + private Long sectionResponseId; + + @Column(name = "questionId", nullable = false) + private Long questionId; + + /** Set for RADIO (one row) and MCQ (one row per selected option). */ + @Column(name = "optionId") + private Long optionId; + + /** Set for TEXT, DATE, AUTO_FILL answers. */ + @Lob + @Column(name = "answerText") + private String answerText; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + @Builder.Default + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/QuestionValidation.java b/src/main/java/com/iemr/flw/domain/iemr/QuestionValidation.java new file mode 100644 index 000000000..b7d41dc16 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/QuestionValidation.java @@ -0,0 +1,101 @@ +/* + * 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 com.iemr.flw.masterEnum.ValidationType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; + +/** + * Server-side validation rule for a question. + * validationType: MAX_LENGTH | MIN_DATE | MAX_DATE | REGEX | MANDATORY_IF + */ +@Entity +@Table(name = "t_question_validation", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QuestionValidation { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "validationId") + private Long validationId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "questionId", nullable = false) + @ToString.Exclude + private SectionQuestion sectionQuestion; + + @Enumerated(EnumType.STRING) + @Column(name = "validationType", nullable = false, length = 30) + private ValidationType validationType; + + /** e.g. "500" for MAX_LENGTH, "TODAY" for MAX_DATE, a regex pattern for REGEX. */ + @Column(name = "validationParam", length = 255) + private String validationParam; + + @Column(name = "errorMessage", nullable = false, length = 500) + private String errorMessage; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SectionQuestion.java b/src/main/java/com/iemr/flw/domain/iemr/SectionQuestion.java new file mode 100644 index 000000000..1bd7991bc --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SectionQuestion.java @@ -0,0 +1,135 @@ +/* + * 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 com.iemr.flw.masterEnum.QuestionType; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.Lob; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; + +/** + * A question within a form section. + * questionType: RADIO | MCQ | TEXT | DATE | DISPLAY | AUTO_FILL + */ +@Entity +@Table(name = "t_section_question", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SectionQuestion { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "questionId") + private Long questionId; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "sectionId", nullable = false) + @ToString.Exclude + private FormSection formSection; + + @Column(name = "questionUuid", nullable = false, length = 100) + private String questionUuid; + + @Lob + @Column(name = "questionText", nullable = false) + private String questionText; + + @Column(name = "questionText_hindi", columnDefinition = "TEXT") + private String questionTextHindi; + + @Enumerated(EnumType.STRING) + @Column(name = "questionType", nullable = false, length = 20) + private QuestionType questionType; + + @Column(name = "isMandatory", nullable = false) + private Boolean isMandatory = true; + + @Column(name = "displayOrder", nullable = false) + private Integer displayOrder; + + /** Convenience shortcut — enforced by FormValidationEngine for TEXT questions. */ + @Column(name = "maxLength") + private Integer maxLength; + + /** e.g. "TODAY" for date fields with a default. */ + @Column(name = "defaultValue", length = 500) + private String defaultValue; + + /** If true, answerText is encrypted via CryptoUtil before persistence. */ + @Column(name = "containsPii", nullable = false) + private Boolean containsPii = false; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @OneToMany(mappedBy = "sectionQuestion", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List options = new ArrayList<>(); + + @OneToMany(mappedBy = "sectionQuestion", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @ToString.Exclude + private List validations = new ArrayList<>(); + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/SectionResponse.java b/src/main/java/com/iemr/flw/domain/iemr/SectionResponse.java new file mode 100644 index 000000000..d8877a50c --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/SectionResponse.java @@ -0,0 +1,96 @@ +/* + * 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 jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; + +/** + * Tracks completion state of one section within a form response. + * sectionId FK to t_form_section already implies the form version via its version_id FK. + * + * @author Piramal Swasthya + */ +@Entity +@Table(name = "t_section_response", schema = "db_iemr") +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class SectionResponse { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "sectionResponseId") + private Long sectionResponseId; + + @Column(name = "responseId", nullable = false) + private Long responseId; + + @Column(name = "sectionId", nullable = false) + private Long sectionId; + + /** PENDING | IN_PROGRESS | DONE | SKIPPED */ + @Column(name = "status", nullable = false, length = 20) + private String status; + + @Column(name = "savedAt") + private Timestamp savedAt; + + @Column(name = "created_by", length = 100) + private String createdBy; + + @Column(name = "updated_by", length = 100) + private String updatedBy; + + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + @Builder.Default + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "SyncedDate") + private Timestamp syncedDate; + + @Column(name = "Syncedby", length = 50) + private String syncedBy; + + @Column(name = "SyncFailureReason") + private String syncFailureReason; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/StopTBDiagnostics.java b/src/main/java/com/iemr/flw/domain/iemr/StopTBDiagnostics.java new file mode 100644 index 000000000..f9abde570 --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/StopTBDiagnostics.java @@ -0,0 +1,140 @@ +package com.iemr.flw.domain.iemr; + +import lombok.Data; +import jakarta.persistence.*; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.sql.Timestamp; + +@Entity +@Table(name = "tb_stoptb_diagnostics", schema = "db_iemr") +@Data +public class StopTBDiagnostics { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "ben_reg_id") + private Long benRegID; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapID; + + // PRD: user-provided date, not editable once submitted + @Column(name = "visit_date") + private Timestamp visitDate; + + @Column(name = "nikshay_id", length = 50) + private String nikshayId; + + // Digital Chest X-ray + @Column(name = "is_referred_for_digital_chest_xray") + private Boolean isReferredForDigitalChestXray; + + @Column(name = "reason_for_denial_chest_xray", length = 255) + private String reasonForDenialChestXray; + + @Column(name = "reason_for_denial_chest_xray_other", length = 255) + private String reasonForDenialChestXrayOther; + + @Column(name = "is_digital_chest_xray_conducted_id") + private Integer isDigitalChestXrayConductedId; + + @Column(name = "is_digital_chest_xray_conducted") + private Boolean isDigitalChestXrayConducted; + + @Column(name = "reason_not_conducted_chest_xray", length = 255) + private String reasonNotConductedChestXray; + + @Column(name = "reason_not_conducted_chest_xray_other", length = 255) + private String reasonNotConductedChestXrayOther; + + // Positive | Negative + @Column(name = "digital_chest_xray_result_id") + private Integer digitalChestXrayResultId; + + @Column(name = "digital_chest_xray_result", length = 20) + private String digitalChestXrayResult; + + // Sputum Collection + @Column(name = "is_referred_for_sputum_collection") + private Boolean isReferredForSputumCollection; + + @Column(name = "reason_for_denial_sputum", length = 500) + private String reasonForDenialSputum; + + @Column(name = "reason_for_denial_sputum_other", length = 255) + private String reasonForDenialSputumOther; + + @Column(name = "sputum_submitted_at", length = 255) + private String sputumSubmittedAt; + + // Truenat / NAAT + @Column(name = "is_truenat_conducted_id") + private Integer isTruenatConductedId; + + @Column(name = "is_truenat_conducted") + private Boolean isTruenatConducted; + + @Column(name = "reason_not_conducted_naat", length = 255) + private String reasonNotConductedNaat; + + @Column(name = "reason_not_conducted_naat_other", length = 255) + private String reasonNotConductedNaatOther; + + // Positive | Negative + @Column(name = "truenat_result_id") + private Integer truenatResultId; + + @Column(name = "truenat_result", length = 20) + private String truenatResult; + + // Liquid Culture — enabled if History of TB = Yes AND Anti-TB drugs = Yes + @Column(name = "recommended_for_liquid_culture_id") + private Integer recommendedForLiquidCultureId; + + @Column(name = "recommended_for_liquid_culture") + private Boolean recommendedForLiquidCulture; + + // Positive | Negative — editable after submission (results come after 40-45 days) + @Column(name = "liquid_culture_result_id") + private Integer liquidCultureResultId; + + @Column(name = "liquid_culture_result", length = 20) + private String liquidCultureResult; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "modified_by") + private String modifiedBy; + + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + @Column(name = "deleted") + private Boolean deleted = false; + + // Sync fields + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "visitCode") + private Long visitCode; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralExamination.java b/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralExamination.java new file mode 100644 index 000000000..9972d916d --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralExamination.java @@ -0,0 +1,133 @@ +package com.iemr.flw.domain.iemr; + +import lombok.Data; +import jakarta.persistence.*; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.sql.Timestamp; + +@Entity +@Table(name = "tb_stoptb_general_examination", schema = "db_iemr") +@Data +public class StopTBGeneralExamination { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "beneficiary_reg_id") + private Long beneficiaryRegID; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapID; + + // Vitals + @Column(name = "pulse_rate") + private Integer pulseRate; + + @Column(name = "systolic_bp") + private Integer systolicBP; + + @Column(name = "diastolic_bp") + private Integer diastolicBP; + + @Column(name = "random_blood_sugar") + private Double randomBloodSugar; + + // Clinical signs — ID + label ("PRESENT" / "ABSENT") + @Column(name = "pallor_id") + private Integer pallorId; + + @Column(name = "pallor") + private String pallor; + + @Column(name = "icterus_id") + private Integer icterusId; + + @Column(name = "icterus") + private String icterus; + + @Column(name = "lymphadenopathy_id") + private Integer lymphadenopathyId; + + @Column(name = "lymphadenopathy") + private String lymphadenopathy; + + @Column(name = "oedema_id") + private Integer oedemaId; + + @Column(name = "oedema") + private String oedema; + + @Column(name = "cyanosis_id") + private Integer cyanosisId; + + @Column(name = "cyanosis") + private String cyanosis; + + @Column(name = "clubbing_id") + private Integer clubbingId; + + @Column(name = "clubbing") + private String clubbing; + + // JSON arrays serialised from mobile + @Column(name = "key_population_risk_factor_ids", columnDefinition = "TEXT") + private String keyPopulationRiskFactorIds; + + @Column(name = "key_population_risk_factors", columnDefinition = "TEXT") + private String keyPopulationRiskFactors; + + @Column(name = "hiv_status_id") + private Integer hivStatusId; + + // "Positive" | "Reactive" | "Negative" | "Unknown" + @Column(name = "hiv_status") + private String hivStatus; + + @Column(name = "referral_to_hwc_needed_id") + private Integer referralToHWCNeededId; + + @Column(name = "referral_to_hwc_needed") + private Boolean referralToHWCNeeded; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "modified_by") + private String modifiedBy; + + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + @Column(name = "deleted") + private Boolean deleted = false; + + // Sync fields + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "visitCode") + private Long visitCode; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "benVisitID") + private Long benVisitID; + + @Column(name = "ben_id") + private Long benId; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralOpd.java b/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralOpd.java new file mode 100644 index 000000000..4cfbb912a --- /dev/null +++ b/src/main/java/com/iemr/flw/domain/iemr/StopTBGeneralOpd.java @@ -0,0 +1,81 @@ +package com.iemr.flw.domain.iemr; + +import lombok.Data; +import jakarta.persistence.*; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.sql.Timestamp; + +@Entity +@Table(name = "tb_stoptb_general_opd", schema = "db_iemr") +@Data +public class StopTBGeneralOpd { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "ben_reg_id") + private Long benRegID; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapID; + + @Column(name = "chief_complaint", columnDefinition = "TEXT") + private String chiefComplaint; + + // JSON array of selected drug names + @Column(name = "medication", columnDefinition = "TEXT") + private String medication; + + @Column(name = "dosage") + private String dosage; + + // Once daily | Twice daily | Thrice daily | SoS + @Column(name = "frequency") + private String frequency; + + // 1 day | 2 days | 3 days | 5 days | 7 days + @Column(name = "duration") + private String duration; + + @Column(name = "notes", columnDefinition = "TEXT") + private String notes; + + @Column(name = "created_by") + private String createdBy; + + @CreationTimestamp + @Column(name = "created_date", updatable = false) + private Timestamp createdDate; + + @Column(name = "modified_by") + private String modifiedBy; + + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + @Column(name = "deleted") + private Boolean deleted = false; + + // Sync fields + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "visitCode") + private Long visitCode; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "benVisitID") + private Long benVisitID; +} diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java index 8310eb65a..c2c51a6fb 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCase.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.Data; +import org.hibernate.annotations.UpdateTimestamp; import java.sql.Timestamp; import java.time.LocalDate; @@ -70,5 +71,35 @@ public class TBConfirmedCase { @Column(name = "updated_at") private LocalDate updatedAt; + @Column(name = "modified_by") + private String modifiedBy; + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + // Sync fields + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "benRegID") + private Long benRegID; + + @Column(name = "providerServiceMapID") + private Integer providerServiceMapID; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "visitCode") + private Long visitCode; } diff --git a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java index 180c3bbed..7a5211779 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBConfirmedCaseDTO.java @@ -3,12 +3,16 @@ import jakarta.persistence.*; import lombok.Data; +import java.sql.Timestamp; import java.time.LocalDate; @Data public class TBConfirmedCaseDTO { - + + private Integer id; private Long benId; + private Timestamp updateDate; + private String updatedBy; private Integer userId; private Integer suspectedTbId; private String regimenType; @@ -25,5 +29,6 @@ public class TBConfirmedCaseDTO { private String placeOfDeath; private String reasonForDeath ; private String reasonForNotCompleting; + private Boolean counselled; } 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 6789f9bf7..06e36309c 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBScreening.java @@ -1,6 +1,7 @@ package com.iemr.flw.domain.iemr; import lombok.Data; +import org.hibernate.annotations.UpdateTimestamp; import jakarta.persistence.*; import java.sql.Timestamp; @@ -23,36 +24,80 @@ public class TBScreening { @Column(name = "visit_date") private Timestamp visitDate; + @Column(name = "cough_check_id") + private Integer coughMoreThan2WeeksId; + @Column(name = "cough_check") private Boolean coughMoreThan2Weeks; + @Column(name = "blood_check_id") + private Integer bloodInSputumId; + @Column(name = "blood_check") private Boolean bloodInSputum; + @Column(name = "fever_check_id") + private Integer feverMoreThan2WeeksId; + @Column(name = "fever_check") private Boolean feverMoreThan2Weeks; + @Column(name = "weight_check_id") + private Integer lossOfWeightId; + @Column(name = "weight_check") private Boolean lossOfWeight; + @Column(name = "sweats_check_id") + private Integer nightSweatsId; + @Column(name = "sweats_check") private Boolean nightSweats; + @Column(name = "history_check_id") + private Integer historyOfTbId; + @Column(name = "history_check") private Boolean historyOfTb; + @Column(name = "drugs_check_id") + private Integer takingAntiTBDrugsId; + @Column(name = "drugs_check") private Boolean takingAntiTBDrugs; + @Column(name = "family_check_id") + private Integer familySufferingFromTBId; + @Column(name = "family_check") private Boolean familySufferingFromTB; + @Column(name = "rise_of_fever_id") + private Integer riseOfFeverId; + @Column(name = "rise_of_fever") private Boolean riseOfFever; + @Column(name = "loss_of_appetite_id") + private Integer lossOfAppetiteId; + @Column(name = "loss_of_appetite") private Boolean lossOfAppetite; + // Risk Factors section — JSON arrays serialised from mobile + @Column(name = "key_population_risk_factor_ids", columnDefinition = "TEXT") + private String keyPopulationRiskFactorIds; + + @Column(name = "key_population_risk_factors", columnDefinition = "TEXT") + private String keyPopulationRiskFactors; + + @Column(name = "hiv_status_id") + private Integer hivStatusId; + + // "Positive" | "Reactive" | "Negative" | "Unknown" + @Column(name = "hiv_status") + private String hivStatus; + @Column(name = "age") private Boolean age; @@ -79,4 +124,74 @@ public class TBScreening { @Column(name = "recommandate_test") private String recommandateTest; + + // Added for Stop TB nurse flow — nullable, not used by ASHA flow + @Column(name = "ben_reg_id") + private Long benRegID; + + @Column(name = "provider_service_map_id") + private Integer providerServiceMapID; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "modified_by") + private String modifiedBy; + + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + @Column(name = "deleted", insertable = false) + private Boolean deleted; + + // Diagnostics / referrals — Stop TB nurse flow only + @Column(name = "referred_for_digital_chest_xray_id") + private Integer referredForDigitalChestXrayId; + + @Column(name = "referred_for_digital_chest_xray") + private Boolean referredForDigitalChestXray; + + @Column(name = "referred_for_sputum_collection_id") + private Integer referredForSputumCollectionId; + + @Column(name = "referred_for_sputum_collection") + private Boolean referredForSputumCollection; + + @Column(name = "sputum_sample_submitted_at", length = 50) + private String sputumSampleSubmittedAt; + + @Column(name = "recommended_for_truenat_id") + private Integer recommendedForTruenatId; + + @Column(name = "recommended_for_truenat") + private Boolean recommendedForTruenat; + + @Column(name = "recommended_for_liquid_culture_id") + private Integer recommendedForLiquidCultureId; + + @Column(name = "recommended_for_liquid_culture") + private Boolean recommendedForLiquidCulture; + + @Column(name = "test_denial_reasons", columnDefinition = "TEXT") + private String testDenialReasons; + + // Sync fields — stamped by local laptop on save, used by MMU DataSync for local→central push + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "visitCode") + private Long visitCode; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "createdDate") + private java.sql.Timestamp createdDate; } 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 2de2baf82..0c8d2fc40 100644 --- a/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java +++ b/src/main/java/com/iemr/flw/domain/iemr/TBSuspected.java @@ -1,6 +1,7 @@ package com.iemr.flw.domain.iemr; import lombok.Data; +import org.hibernate.annotations.UpdateTimestamp; import jakarta.persistence.*; import java.sql.Timestamp; @@ -73,7 +74,37 @@ public class TBSuspected { private Integer providerServiceMapId; @Column(name = "is_confirmed") - private Boolean isConfirmed; + private Boolean isConfirmed; + @Column(name = "modified_by") + private String modifiedBy; + @UpdateTimestamp + @Column(name = "last_mod_date") + private Timestamp lastModDate; + + // Sync fields + @Column(name = "vanID") + private Integer vanID; + + @Column(name = "parkingPlaceID") + private Integer parkingPlaceID; + + @Column(name = "processed") + private String processed = "N"; + + @Column(name = "vanSerialNo") + private Long vanSerialNo; + + @Column(name = "benRegID") + private Long benRegID; + + @Column(name = "created_by") + private String createdBy; + + @Column(name = "created_date") + private Timestamp createdDate; + + @Column(name = "visitCode") + private Long visitCode; } 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 d1a654ec6..94bfed1c1 100644 --- a/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java +++ b/src/main/java/com/iemr/flw/dto/identity/GetBenRequestHandler.java @@ -12,6 +12,16 @@ public class GetBenRequestHandler { private Integer ashaId; + private Integer providerServiceMapID; + + public Integer getProviderServiceMapID() { + return providerServiceMapID; + } + + public void setProviderServiceMapID(Integer providerServiceMapID) { + this.providerServiceMapID = providerServiceMapID; + } + private Long activityId; private Integer month; @@ -82,6 +92,10 @@ public void setVillageID(Integer villageID) { this.villageID = villageID; } + public void setVillageId(Integer villageId) { + this.villageID = villageId; + } + public Timestamp getFromDate() { return fromDate; } diff --git a/src/main/java/com/iemr/flw/dto/iemr/DynamicFormDTO.java b/src/main/java/com/iemr/flw/dto/iemr/DynamicFormDTO.java new file mode 100644 index 000000000..c9ecb63c4 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/DynamicFormDTO.java @@ -0,0 +1,65 @@ +/* + * 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.dto.iemr; + +import com.iemr.flw.masterEnum.FormType; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Transfer object for a full dynamic form definition. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DynamicFormDTO { + + private Long formId; + + @NotBlank(message = "formUuid is required") + private String formUuid; + + @NotBlank(message = "formName is required") + private String formName; + + @NotNull(message = "formType is required") + private FormType formType; + + private Boolean isActive = true; + + /** Days after the most-recently-completed section before the next follow-up notification fires. + * Null means no follow-up notifications. */ + private Integer followUpDelayDays; + + /** Current version number — populated by service on read, ignored on write. */ + private Integer versionNumber; + + @Valid + private List sections = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FormResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FormResponseDTO.java new file mode 100644 index 000000000..d53a5823a --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FormResponseDTO.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/. + */ +package com.iemr.flw.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; +import java.util.List; + +/** + * Outbound representation of a saved form response including all section and question answers. + * + * @author Piramal Swasthya + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class FormResponseDTO { + + private Long responseId; + private Long beneficiaryId; + private Long formId; + private Long versionId; + private Long officerId; + private String status; + private String createdBy; + private String updatedBy; + private Timestamp submittedAt; + private Timestamp completedAt; + private Timestamp lastFollowUpAt; + private Timestamp createdAt; + private Timestamp updatedAt; + private List sections; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FormResponseRequest.java b/src/main/java/com/iemr/flw/dto/iemr/FormResponseRequest.java new file mode 100644 index 000000000..a90cb84be --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FormResponseRequest.java @@ -0,0 +1,58 @@ +/* + * 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.dto.iemr; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Inbound request to save or submit a dynamic form response. + * + * @author Piramal Swasthya + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FormResponseRequest { + + /** Present on re-submit: update an existing SUBMITTED response's sections instead of creating new. */ + private Long responseId; + + @NotBlank(message = "formUuid is required") + private String formUuid; + + @NotNull(message = "beneficiaryId is required") + private Long beneficiaryId; + + @NotNull(message = "officerId is required") + private Long officerId; + + @Valid + private List sections = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FormSectionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FormSectionDTO.java new file mode 100644 index 000000000..2db1f8c71 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FormSectionDTO.java @@ -0,0 +1,64 @@ +/* + * 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.dto.iemr; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Transfer object for a form section definition. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FormSectionDTO { + + private Long sectionId; + + @NotBlank(message = "sectionUuid is required") + private String sectionUuid; + + @NotBlank(message = "sectionName is required") + private String sectionName; + + private String sectionNameHindi; + + @NotBlank(message = "sectionPhase is required (PRE_SUBMIT or POST_SUBMIT)") + private String sectionPhase; + + private Boolean isRequired = true; + + @NotNull(message = "displayOrder is required") + private Integer displayOrder; + + private Boolean hasSubmitButton = false; + + @Valid + private List questions = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/FormVersionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/FormVersionDTO.java new file mode 100644 index 000000000..742b0f7b1 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/FormVersionDTO.java @@ -0,0 +1,41 @@ +/* + * 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.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Transfer object for form version metadata. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class FormVersionDTO { + + private Long versionId; + private Integer versionNumber; + private Boolean isLatest; + private String createdBy; + private String notes; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java index 1a8b8e6ee..56dff1969 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/MalariaFollowListUpDTO.java @@ -25,11 +25,15 @@ package com.iemr.flw.dto.iemr; import lombok.Data; + +import java.sql.Timestamp; import java.util.Date; @Data public class MalariaFollowListUpDTO { private Long id; + private Timestamp updateDate; + private String updatedBy; private Long benId; private Long houseHoldDetailsId; private Integer userId ; diff --git a/src/main/java/com/iemr/flw/dto/iemr/OptionConditionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/OptionConditionDTO.java new file mode 100644 index 000000000..d43167a78 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/OptionConditionDTO.java @@ -0,0 +1,58 @@ +/* + * 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.dto.iemr; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Transfer object for a conditional action triggered when an option is selected. + * Exactly one of targetQuestionId / targetSectionId should be non-null. + * + * On create/update: use targetQuestionUuid or targetSectionUuid to reference target. + * On read: targetQuestionId + targetQuestionUuid (or targetSectionId + targetSectionUuid) are + * returned as flat references — the full target object appears in the form's questions/sections list. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OptionConditionDTO { + + private Long conditionId; + + @NotBlank(message = "actionType is required") + private String actionType; + + /** DB ID of the target question. */ + private Long targetQuestionId; + + /** DB ID of the target section. */ + private Long targetSectionId; + + /** UUID of the target question. */ + private String targetQuestionUuid; + + /** UUID of the target section. */ + private String targetSectionUuid; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/QuestionAnswerRequest.java b/src/main/java/com/iemr/flw/dto/iemr/QuestionAnswerRequest.java new file mode 100644 index 000000000..8ee08c455 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/QuestionAnswerRequest.java @@ -0,0 +1,63 @@ +/* + * 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.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +/** + * A single question's answer within a section answer request. + * Exactly one of optionValue, optionValues, answerText, or answerDate should be set per question type: + * RADIO → optionValue (single string) + * MCQ → optionValues (list of strings, one row saved per element) + * TEXT/AUTO_FILL → answerText + * DATE → answerDate (ISO date string) or answerText + * DISPLAY → omit entirely (ignored by service) + * + * @author Piramal Swasthya + */ +@JsonIgnoreProperties(ignoreUnknown = false) +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QuestionAnswerRequest { + + @NotBlank(message = "questionUuid is required") + private String questionUuid; + + /** RADIO — single selected option value. */ + private String optionValue; + + /** MCQ — list of selected option values. */ + private List optionValues; + + /** TEXT / AUTO_FILL — free-text answer. */ + private String answerText; + + /** DATE — ISO date string answer. */ + private String answerDate; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/QuestionOptionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/QuestionOptionDTO.java new file mode 100644 index 000000000..0328263ce --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/QuestionOptionDTO.java @@ -0,0 +1,59 @@ +/* + * 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.dto.iemr; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Transfer object for a selectable option on a RADIO or MCQ question. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QuestionOptionDTO { + + private Long optionId; + + @NotBlank(message = "optionLabel is required") + private String optionLabel; + + private String optionLabelHindi; + + @NotBlank(message = "optionValue is required") + private String optionValue; + + private String optionValueHindi; + + @NotNull(message = "displayOrder is required") + private Integer displayOrder; + + @Valid + private List conditions = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/QuestionResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/QuestionResponseDTO.java new file mode 100644 index 000000000..f5f76d639 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/QuestionResponseDTO.java @@ -0,0 +1,47 @@ +/* + * 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.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Outbound representation of a single question's stored answer. + * For MCQ questions, multiple QuestionResponseDTO entries share the same questionId. + * + * @author Piramal Swasthya + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class QuestionResponseDTO { + + private Long questionResponseId; + private Long questionId; + /** Populated for RADIO and MCQ answers. */ + private Long optionId; + /** Populated for TEXT, DATE, AUTO_FILL answers. */ + private String answerText; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/QuestionValidationDTO.java b/src/main/java/com/iemr/flw/dto/iemr/QuestionValidationDTO.java new file mode 100644 index 000000000..72c144c53 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/QuestionValidationDTO.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.dto.iemr; + +import com.iemr.flw.masterEnum.ValidationType; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Transfer object for a server-side validation rule on a question. + * validationType: MAX_LENGTH | MIN_DATE | MAX_DATE | REGEX | MANDATORY_IF + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class QuestionValidationDTO { + + private Long validationId; + + @NotNull(message = "validationType is required") + private ValidationType validationType; + + private String validationParam; + + @NotBlank(message = "errorMessage is required") + private String errorMessage; +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SectionAnswerRequest.java b/src/main/java/com/iemr/flw/dto/iemr/SectionAnswerRequest.java new file mode 100644 index 000000000..b63d7a0ce --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SectionAnswerRequest.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/. + */ +package com.iemr.flw.dto.iemr; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Answers for one section within a form response request. + * + * @author Piramal Swasthya + */ +@JsonIgnoreProperties(ignoreUnknown = false) +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SectionAnswerRequest { + + @NotBlank(message = "sectionUuid is required") + private String sectionUuid; + + @Valid + private List answers = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SectionQuestionDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SectionQuestionDTO.java new file mode 100644 index 000000000..11a814303 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SectionQuestionDTO.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/. + */ +package com.iemr.flw.dto.iemr; + +import com.iemr.flw.masterEnum.QuestionType; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; +import java.util.List; + +/** + * Transfer object for a question within a section. + * visibleByDefault is computed by the service — not stored in DB. + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class SectionQuestionDTO { + + private Long questionId; + + @NotBlank(message = "questionUuid is required") + private String questionUuid; + + @NotBlank(message = "questionText is required") + private String questionText; + + private String questionTextHindi; + + @NotNull(message = "questionType is required") + private QuestionType questionType; + + private Boolean isMandatory = true; + + @NotNull(message = "displayOrder is required") + private Integer displayOrder; + + private Integer maxLength; + + private String defaultValue; + + private Boolean containsPii = false; + + /** Computed at read time: false if this question is a target of any OptionCondition. */ + private Boolean visibleByDefault = true; + + @Valid + private List options = new ArrayList<>(); + + @Valid + private List validations = new ArrayList<>(); +} diff --git a/src/main/java/com/iemr/flw/dto/iemr/SectionResponseDTO.java b/src/main/java/com/iemr/flw/dto/iemr/SectionResponseDTO.java new file mode 100644 index 000000000..dac289a70 --- /dev/null +++ b/src/main/java/com/iemr/flw/dto/iemr/SectionResponseDTO.java @@ -0,0 +1,48 @@ +/* + * 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.dto.iemr; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.sql.Timestamp; +import java.util.List; + +/** + * Outbound representation of one section's response data. + * + * @author Piramal Swasthya + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class SectionResponseDTO { + + private Long sectionResponseId; + private Long sectionId; + private String status; + private Timestamp savedAt; + private List answers; +} 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 29fb25f6e..72b731d01 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/TBSuspectedDTO.java @@ -8,6 +8,8 @@ public class TBSuspectedDTO { private Long id; + private Timestamp updateDate; + private String updatedBy; private Long benId; private String visitLabel; diff --git a/src/main/java/com/iemr/flw/mapper/DynamicFormMapper.java b/src/main/java/com/iemr/flw/mapper/DynamicFormMapper.java new file mode 100644 index 000000000..551e93a6d --- /dev/null +++ b/src/main/java/com/iemr/flw/mapper/DynamicFormMapper.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/. + */ +package com.iemr.flw.mapper; + +import com.iemr.flw.domain.iemr.DynamicForm; +import com.iemr.flw.domain.iemr.FormSection; +import com.iemr.flw.domain.iemr.FormVersion; +import com.iemr.flw.domain.iemr.OptionCondition; +import com.iemr.flw.domain.iemr.QuestionOption; +import com.iemr.flw.domain.iemr.QuestionValidation; +import com.iemr.flw.domain.iemr.SectionQuestion; +import com.iemr.flw.dto.iemr.DynamicFormDTO; +import com.iemr.flw.dto.iemr.FormSectionDTO; +import com.iemr.flw.dto.iemr.FormVersionDTO; +import com.iemr.flw.dto.iemr.OptionConditionDTO; +import com.iemr.flw.dto.iemr.QuestionOptionDTO; +import com.iemr.flw.dto.iemr.QuestionValidationDTO; +import com.iemr.flw.dto.iemr.SectionQuestionDTO; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +/** + * MapStruct mapper for dynamic form definition — entity ↔ DTO conversion. + */ +@Mapper(componentModel = "spring") +public interface DynamicFormMapper { + + // ── Entity → DTO ────────────────────────────────────────────────────────── + + @Mapping(target = "sections", ignore = true) + @Mapping(target = "versionNumber", ignore = true) + DynamicFormDTO toDto(DynamicForm entity); + + FormVersionDTO toDto(FormVersion entity); + + @Mapping(target = "questions", ignore = true) + FormSectionDTO toDto(FormSection entity); + + @Mapping(target = "visibleByDefault", ignore = true) + @Mapping(target = "options", ignore = true) + @Mapping(target = "validations", ignore = true) + SectionQuestionDTO toDto(SectionQuestion entity); + + @Mapping(target = "conditions", ignore = true) + QuestionOptionDTO toDto(QuestionOption entity); + + @Mapping(source = "targetQuestion.questionId", target = "targetQuestionId") + @Mapping(source = "targetQuestion.questionUuid", target = "targetQuestionUuid") + @Mapping(source = "targetSection.sectionId", target = "targetSectionId") + @Mapping(source = "targetSection.sectionUuid", target = "targetSectionUuid") + OptionConditionDTO toDto(OptionCondition entity); + + QuestionValidationDTO toDto(QuestionValidation entity); + + // ── DTO → Entity ────────────────────────────────────────────────────────── + + @Mapping(target = "versions", ignore = true) + @Mapping(target = "createdAt", ignore = true) + @Mapping(target = "updatedAt", ignore = true) + DynamicForm toEntity(DynamicFormDTO dto); + + @Mapping(target = "dynamicForm", ignore = true) + @Mapping(target = "sections", ignore = true) + @Mapping(target = "createdAt", ignore = true) + FormVersion toEntity(FormVersionDTO dto); + + @Mapping(target = "questions", ignore = true) + FormSection toEntity(FormSectionDTO dto); + + @Mapping(target = "formSection", ignore = true) + @Mapping(target = "options", ignore = true) + @Mapping(target = "validations", ignore = true) + SectionQuestion toEntity(SectionQuestionDTO dto); + + @Mapping(target = "sectionQuestion", ignore = true) + @Mapping(target = "conditions", ignore = true) + QuestionOption toEntity(QuestionOptionDTO dto); + + @Mapping(target = "questionOption", ignore = true) + @Mapping(target = "targetQuestion", ignore = true) + @Mapping(target = "targetSection", ignore = true) + OptionCondition toEntity(OptionConditionDTO dto); + + @Mapping(target = "sectionQuestion", ignore = true) + QuestionValidation toEntity(QuestionValidationDTO dto); +} diff --git a/src/main/java/com/iemr/flw/masterEnum/FormType.java b/src/main/java/com/iemr/flw/masterEnum/FormType.java new file mode 100644 index 000000000..779fce19d --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/FormType.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/. + */ +package com.iemr.flw.masterEnum; + +/** + * Allowed types for a dynamic form definition. + * + * @author Piramal Swasthya + */ +public enum FormType { + COUNSELLING_MODULE, + SCREENING, + COUNSELLING, + TB_COUNSELLING +} diff --git a/src/main/java/com/iemr/flw/masterEnum/QuestionType.java b/src/main/java/com/iemr/flw/masterEnum/QuestionType.java new file mode 100644 index 000000000..ae4b91e13 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/QuestionType.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/. + */ +package com.iemr.flw.masterEnum; + +/** + * Exhaustive set of question input types for dynamic form questions. + * No other values may be stored in t_section_question.questionType. + * + * @author Piramal Swasthya + */ +public enum QuestionType { + /** Single-select from a predefined list of options. */ + RADIO, + /** Multi-select from a predefined list of options. */ + MCQ, + /** Free-text input. */ + TEXT, + /** Date picker input. */ + DATE, + /** Read-only display text — carries no answer data. */ + DISPLAY, + /** Value auto-filled from context (e.g. ASHA worker ID). */ + AUTO_FILL +} diff --git a/src/main/java/com/iemr/flw/masterEnum/ValidationType.java b/src/main/java/com/iemr/flw/masterEnum/ValidationType.java new file mode 100644 index 000000000..931e24699 --- /dev/null +++ b/src/main/java/com/iemr/flw/masterEnum/ValidationType.java @@ -0,0 +1,42 @@ +/* + * 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.masterEnum; + +/** + * Exhaustive set of validation rule types for dynamic form questions. + * No other values may be stored in t_question_validation.validationType. + * + * @author Piramal Swasthya + */ +public enum ValidationType { + /** Maximum character length for text inputs. validationParam = integer string e.g. "100". */ + MAX_LENGTH, + /** Minimum allowed date. validationParam = ISO date string or "TODAY". */ + MIN_DATE, + /** Maximum allowed date. validationParam = ISO date string or "TODAY". */ + MAX_DATE, + /** Java-compatible regular expression the answer must match. validationParam = regex pattern. */ + REGEX, + /** Field becomes mandatory when another field equals a specific value. + * validationParam format: "QUESTION_UUID=OPTION_VALUE" e.g. "Q-GENDER=FEMALE". */ + MANDATORY_IF +} \ No newline at end of file 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 e4ce22f04..c9d00c72b 100644 --- a/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java +++ b/src/main/java/com/iemr/flw/repo/identity/BeneficiaryRepo.java @@ -90,12 +90,18 @@ Page getBenDataWithinDates( @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); + // benRegId has no unique constraint on i_beneficiarymapping — a beneficiary can have + // more than one mapping row, so this must return a list, not assume a single result. + @Query("SELECT b FROM RMNCHMBeneficiarymapping b WHERE b.benRegId = :benRegId ORDER BY b.benMapId DESC") + List findByBenRegIdFromMapping(@Param("benRegId") BigInteger benRegId); + @Query("SELECT d FROM RMNCHMBeneficiarydetail d WHERE d.beneficiaryDetailsId = :beneficiaryDetailsId") RMNCHMBeneficiarydetail findByBeneficiaryDetailsId(@Param("beneficiaryDetailsId") BigInteger beneficiaryDetailsId); + @Query("SELECT d FROM RMNCHMBeneficiarydetail d WHERE d.BenRegId = :benRegID") + RMNCHMBeneficiarydetail getDetailByBenRegID(@Param("benRegID") BigInteger benRegID); + // BeneficiaryRepo — replaces 3 separate queries per beneficiary @Query(value = """ diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenAnthropometryRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenAnthropometryRepo.java new file mode 100644 index 000000000..1856eb062 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BenAnthropometryRepo.java @@ -0,0 +1,15 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.BenAnthropometryDetail; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface BenAnthropometryRepo extends JpaRepository { + + List findByBeneficiaryRegIDOrderByCreatedDateDesc(Long beneficiaryRegID); + + BenAnthropometryDetail findByBenVisitID(Long benVisitID); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenChiefComplaintRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenChiefComplaintRepo.java new file mode 100644 index 000000000..47a73f98f --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BenChiefComplaintRepo.java @@ -0,0 +1,9 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.BenChiefComplaint; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BenChiefComplaintRepo extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenFlowStatusRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenFlowStatusRepo.java new file mode 100644 index 000000000..4658f7cc2 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BenFlowStatusRepo.java @@ -0,0 +1,38 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.BenFlowStatus; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.List; + +@Repository +public interface BenFlowStatusRepo extends JpaRepository { + + @Query("SELECT b FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId AND b.nurseFlag = 1 AND b.deleted = false ORDER BY b.registrationDate DESC") + List getNurseWorklist(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Query("SELECT b FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId AND b.deleted = false ORDER BY b.registrationDate DESC") + List getRegistrarWorklist(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Query("SELECT b FROM BenFlowStatus b WHERE b.beneficiaryRegID = :benRegID AND b.deleted = false ORDER BY b.registrationDate DESC") + List findByBeneficiaryRegID(@Param("benRegID") Long benRegID); + + @Modifying + @Query("UPDATE BenFlowStatus b SET b.nurseFlag = 9, b.pharmacistFlag = 1 WHERE b.benFlowID = :benFlowID") + int updateAfterNurseSubmit(@Param("benFlowID") Long benFlowID); + + // Stop TB: nurse done, counsellor pending when diagnostic is positive (set by device push) + @Modifying + @Query("UPDATE BenFlowStatus b SET b.nurseFlag = 9 WHERE b.benFlowID = :benFlowID") + int updateStopTBAfterNurseSubmit(@Param("benFlowID") Long benFlowID); + + // Stop TB: device operator pushes positive diagnostic → route to counsellor + @Modifying + @Query("UPDATE BenFlowStatus b SET b.doctorFlag = 1 WHERE b.beneficiaryRegID = :benRegID AND b.visitCategory = 'Stop TB' AND b.deleted = false") + int routeToStopTBCounsellor(@Param("benRegID") Long benRegID); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/BenPhysicalVitalRepo.java b/src/main/java/com/iemr/flw/repo/iemr/BenPhysicalVitalRepo.java new file mode 100644 index 000000000..7e474935b --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/BenPhysicalVitalRepo.java @@ -0,0 +1,15 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.BenPhysicalVitalDetail; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface BenPhysicalVitalRepo extends JpaRepository { + + List findByBeneficiaryRegIDOrderByCreatedDateDesc(Long beneficiaryRegID); + + BenPhysicalVitalDetail findByBenVisitID(Long benVisitID); +} 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 dfd605ef7..47aacb2b8 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/BenVisitDetailsRepo.java @@ -2,10 +2,26 @@ import com.iemr.flw.domain.iemr.BenVisitDetail; 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.sql.Timestamp; import java.util.List; @Repository public interface BenVisitDetailsRepo extends JpaRepository { - public List findByBeneficiaryRegId(Long benRegID);} + + List findByBeneficiaryRegId(Long benRegID); + + @Query("SELECT v FROM BenVisitDetail v WHERE v.beneficiaryRegId = :benRegID " + + "AND v.visitCategory = 'Stop TB' " + + "AND v.visitDateTime >= :dayStart AND v.visitDateTime < :dayEnd") + BenVisitDetail findStopTBVisitForToday(@Param("benRegID") Long benRegID, + @Param("dayStart") Timestamp dayStart, + @Param("dayEnd") Timestamp dayEnd); + + @Query("SELECT COUNT(v) FROM BenVisitDetail v WHERE v.beneficiaryRegId = :benRegID " + + "AND v.visitCategory = 'Stop TB'") + Integer countStopTBVisits(@Param("benRegID") Long benRegID); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/DynamicFormRepo.java b/src/main/java/com/iemr/flw/repo/iemr/DynamicFormRepo.java new file mode 100644 index 000000000..69260ea1d --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/DynamicFormRepo.java @@ -0,0 +1,47 @@ +/* + * 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.DynamicForm; +import com.iemr.flw.masterEnum.FormType; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Repository for dynamic form definitions. + */ +@Repository +public interface DynamicFormRepo extends JpaRepository { + + Optional findByFormUuid(String formUuid); + + Optional findByFormUuidAndIsActive(String formUuid, Boolean isActive); + + List findByIsActiveOrderByFormIdAsc(Boolean isActive); + + Optional findByFormTypeAndIsActive(FormType formType, Boolean isActive); + + List findByIsActiveTrueAndFollowUpDelayDaysIsNotNull(); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/FormResponseRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FormResponseRepo.java new file mode 100644 index 000000000..66672c16d --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/FormResponseRepo.java @@ -0,0 +1,72 @@ +/* + * 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.FormResponse; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.sql.Timestamp; +import java.util.List; + +/** + * Repository for form-level responses. + * + * @author Piramal Swasthya + */ +@Repository +public interface FormResponseRepo extends JpaRepository { + + List findByBeneficiaryIdAndFormId(Long beneficiaryId, Long formId); + + @Query("SELECT r.beneficiaryId FROM FormResponse r WHERE r.formId = :formId AND r.status = :status") + List findBeneficiaryIdsByFormIdAndStatus(@Param("formId") Long formId, @Param("status") String status); + + @Query("SELECT r.beneficiaryId FROM FormResponse r WHERE r.formId = :formId AND r.status = :status " + + "AND r.beneficiaryId IN (SELECT b.beneficiaryID FROM BenFlowStatus b WHERE b.deleted = false " + + "AND (:villageId IS NULL OR b.villageID = :villageId) " + + "AND (:providerServiceMapId IS NULL OR b.providerServiceMapId = :providerServiceMapId))") + List findBeneficiaryIdsByFormIdAndStatusFiltered(@Param("formId") Long formId, + @Param("status") String status, + @Param("villageId") Integer villageId, + @Param("providerServiceMapId") Integer providerServiceMapId); + + @Query("SELECT r.beneficiaryId FROM FormResponse r " + + "WHERE r.beneficiaryId IN :benIds " + + "AND r.formId = :formId " + + "AND r.status = :status") + List findCounselledBenIds(@Param("benIds") List benIds, + @Param("formId") Long formId, + @Param("status") String status); + + @Query("SELECT r FROM FormResponse r " + + "WHERE r.formId IN :formIds " + + "AND r.status = 'SUBMITTED' " + + "AND r.lastFollowUpAt >= :windowStart " + + "AND r.lastFollowUpAt < :windowEnd") + List findPendingFollowUps( + @Param("formIds") List formIds, + @Param("windowStart") Timestamp windowStart, + @Param("windowEnd") Timestamp windowEnd); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/FormSectionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FormSectionRepo.java new file mode 100644 index 000000000..b40643954 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/FormSectionRepo.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/. + */ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.FormSection; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * Repository for form sections. + * Each section belongs to one FormVersion via the version_id FK. + */ +@Repository +public interface FormSectionRepo extends JpaRepository { + + List findByFormVersion_VersionIdOrderByDisplayOrderAsc(Long versionId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/FormVersionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/FormVersionRepo.java new file mode 100644 index 000000000..1d8583aea --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/FormVersionRepo.java @@ -0,0 +1,46 @@ +/* + * 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.FormVersion; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Repository for form versions. + */ +@Repository +public interface FormVersionRepo extends JpaRepository { + + Optional findByDynamicForm_FormIdAndIsLatest(Long formId, Boolean isLatest); + + Optional findByDynamicForm_FormIdAndVersionNumber(Long formId, Integer versionNumber); + + Optional findTopByDynamicForm_FormIdOrderByVersionNumberDesc(Long formId); + + List findByDynamicForm_FormIdOrderByVersionNumberAsc(Long formId); + + Optional findByDynamicForm_FormUuidAndIsLatest(String formUuid, boolean b); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java new file mode 100644 index 000000000..633418894 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/OptionConditionRepo.java @@ -0,0 +1,55 @@ +/* + * 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.OptionCondition; +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.Collection; +import java.util.List; + +/** + * Repository for option conditions. + */ +@Repository +public interface OptionConditionRepo extends JpaRepository { + + List findByQuestionOption_OptionId(Long optionId); + + @Query("SELECT oc.targetQuestion.questionId FROM OptionCondition oc " + + "WHERE oc.questionOption.sectionQuestion.formSection.formVersion.versionId = :versionId " + + "AND oc.targetQuestion IS NOT NULL") + List findTargetQuestionIdsByVersionId(@Param("versionId") Long versionId); + + /** + * Loads all conditions for a set of options in one query. + * JOIN FETCH ensures questionOption, targetQuestion, and targetSection are hydrated + * so callers can group and resolve references without extra queries. + */ + @Query("SELECT c FROM OptionCondition c JOIN FETCH c.questionOption " + + "LEFT JOIN FETCH c.targetQuestion LEFT JOIN FETCH c.targetSection " + + "WHERE c.questionOption.optionId IN :optionIds") + List findByOptionIds(@Param("optionIds") Collection optionIds); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/PhyGeneralExaminationRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PhyGeneralExaminationRepo.java new file mode 100644 index 000000000..abd73b0b8 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/PhyGeneralExaminationRepo.java @@ -0,0 +1,9 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.PhyGeneralExamination; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PhyGeneralExaminationRepo extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/PrescribedDrugDetailRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PrescribedDrugDetailRepo.java new file mode 100644 index 000000000..bcdd8ab50 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/PrescribedDrugDetailRepo.java @@ -0,0 +1,9 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.PrescribedDrugDetail; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PrescribedDrugDetailRepo extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/PrescriptionDetailRepo.java b/src/main/java/com/iemr/flw/repo/iemr/PrescriptionDetailRepo.java new file mode 100644 index 000000000..c0d425ec0 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/PrescriptionDetailRepo.java @@ -0,0 +1,9 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.PrescriptionDetail; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PrescriptionDetailRepo extends JpaRepository { +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/QuestionOptionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/QuestionOptionRepo.java new file mode 100644 index 000000000..f75120551 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/QuestionOptionRepo.java @@ -0,0 +1,48 @@ +/* + * 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.QuestionOption; +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.Collection; +import java.util.List; + +/** + * Repository for question options. + */ +@Repository +public interface QuestionOptionRepo extends JpaRepository { + + List findBySectionQuestion_QuestionIdOrderByDisplayOrderAsc(Long questionId); + + /** + * Loads all options for a set of questions in one query. + * JOIN FETCH ensures sectionQuestion is hydrated so callers can group by questionId without extra queries. + */ + @Query("SELECT o FROM QuestionOption o JOIN FETCH o.sectionQuestion " + + "WHERE o.sectionQuestion.questionId IN :questionIds ORDER BY o.displayOrder ASC") + List findByQuestionIdsOrderByDisplayOrderAsc(@Param("questionIds") Collection questionIds); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java b/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java new file mode 100644 index 000000000..7dee97954 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/QuestionResponseRepo.java @@ -0,0 +1,46 @@ +/* + * 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.QuestionResponse; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Repository for question-level answers. + * + * @author Piramal Swasthya + */ +@Repository +public interface QuestionResponseRepo extends JpaRepository { + + List findBySectionResponseId(Long sectionResponseId); + + List findBySectionResponseIdIn(Collection sectionResponseIds); + + void deleteByQuestionIdAndSectionResponseId(Long questionId, Long sectionResponseId); + + void deleteBySectionResponseIdIn(Collection sectionResponseIds); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/QuestionValidationRepo.java b/src/main/java/com/iemr/flw/repo/iemr/QuestionValidationRepo.java new file mode 100644 index 000000000..d1cf41876 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/QuestionValidationRepo.java @@ -0,0 +1,48 @@ +/* + * 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.QuestionValidation; +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.Collection; +import java.util.List; + +/** + * Repository for question validation rules. + */ +@Repository +public interface QuestionValidationRepo extends JpaRepository { + + List findBySectionQuestion_QuestionId(Long questionId); + + /** + * Loads all validations for a set of questions in one query. + * JOIN FETCH ensures sectionQuestion is hydrated so callers can group by questionId without extra queries. + */ + @Query("SELECT v FROM QuestionValidation v JOIN FETCH v.sectionQuestion " + + "WHERE v.sectionQuestion.questionId IN :questionIds") + List findByQuestionIds(@Param("questionIds") Collection questionIds); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SectionQuestionRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SectionQuestionRepo.java new file mode 100644 index 000000000..6a117e968 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SectionQuestionRepo.java @@ -0,0 +1,48 @@ +/* + * 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.SectionQuestion; +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.Collection; +import java.util.List; + +/** + * Repository for section questions. + */ +@Repository +public interface SectionQuestionRepo extends JpaRepository { + + List findByFormSection_SectionIdOrderByDisplayOrderAsc(Long sectionId); + + /** + * Loads all questions for a set of sections in one query. + * JOIN FETCH ensures formSection is hydrated so callers can group by sectionId without extra queries. + */ + @Query("SELECT q FROM SectionQuestion q JOIN FETCH q.formSection " + + "WHERE q.formSection.sectionId IN :sectionIds ORDER BY q.displayOrder ASC") + List findBySectionIdsOrderByDisplayOrderAsc(@Param("sectionIds") Collection sectionIds); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/SectionResponseRepo.java b/src/main/java/com/iemr/flw/repo/iemr/SectionResponseRepo.java new file mode 100644 index 000000000..b83ad8e94 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/SectionResponseRepo.java @@ -0,0 +1,47 @@ +/* + * 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.SectionResponse; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +/** + * Repository for section-level responses. + * + * @author Piramal Swasthya + */ +@Repository +public interface SectionResponseRepo extends JpaRepository { + + List findByResponseId(Long responseId); + + Optional findByResponseIdAndSectionId(Long responseId, Long sectionId); + + List findByResponseIdIn(Collection responseIds); + + void deleteByResponseId(Long responseId); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/StopTBDiagnosticsRepo.java b/src/main/java/com/iemr/flw/repo/iemr/StopTBDiagnosticsRepo.java new file mode 100644 index 000000000..de3fa9096 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/StopTBDiagnosticsRepo.java @@ -0,0 +1,31 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.StopTBDiagnostics; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Repository +public interface StopTBDiagnosticsRepo extends JpaRepository { + + @Query("SELECT d FROM StopTBDiagnostics d WHERE d.benRegID = :benRegID AND d.deleted = false") + StopTBDiagnostics findByBenRegID(@Param("benRegID") Long benRegID); + + @Query("SELECT d FROM StopTBDiagnostics d WHERE d.providerServiceMapID = :psmId AND d.deleted = false ORDER BY d.visitDate DESC") + List findAllByProviderServiceMapID(@Param("psmId") Integer psmId); + + @Query("SELECT d FROM StopTBDiagnostics d WHERE d.benRegID IN " + + "(SELECT b.beneficiaryRegID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId) " + + "AND d.deleted = false ORDER BY d.visitDate DESC") + List findAllByProviderServiceMapIDAndVillageID(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE StopTBDiagnostics t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Long id); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralExaminationRepo.java b/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralExaminationRepo.java new file mode 100644 index 000000000..944e99a65 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralExaminationRepo.java @@ -0,0 +1,44 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.StopTBGeneralExamination; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Repository +public interface StopTBGeneralExaminationRepo extends JpaRepository { + + @Query("SELECT e FROM StopTBGeneralExamination e WHERE e.beneficiaryRegID = :beneficiaryRegID AND e.deleted = false") + StopTBGeneralExamination findByBeneficiaryRegID(@Param("beneficiaryRegID") Long beneficiaryRegID); + + // Read-side fix: a beneficiary can now have one row per visit, so the old single-result + // finder above throws NonUniqueResultException once a 2nd visit exists. Used by read/worklist + // endpoints that want "current" status — pass PageRequest.of(0, 1) to get just the latest. + @Query("SELECT e FROM StopTBGeneralExamination e WHERE e.beneficiaryRegID = :beneficiaryRegID " + + "AND e.deleted = false ORDER BY e.createdDate DESC") + List findLatestByBeneficiaryRegID(@Param("beneficiaryRegID") Long beneficiaryRegID, Pageable pageable); + + @Query("SELECT e FROM StopTBGeneralExamination e WHERE e.beneficiaryRegID = :beneficiaryRegID " + + "AND e.visitCode = :visitCode AND e.deleted = false") + StopTBGeneralExamination findByBeneficiaryRegIDAndVisitCode(@Param("beneficiaryRegID") Long beneficiaryRegID, + @Param("visitCode") Long visitCode); + + @Query("SELECT e FROM StopTBGeneralExamination e WHERE e.providerServiceMapID = :psmId AND e.deleted = false ORDER BY e.createdDate DESC") + List findAllByProviderServiceMapID(@Param("psmId") Integer psmId); + + @Query("SELECT e FROM StopTBGeneralExamination e WHERE e.beneficiaryRegID IN " + + "(SELECT b.beneficiaryRegID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId) " + + "AND e.deleted = false ORDER BY e.createdDate DESC") + List findAllByProviderServiceMapIDAndVillageID(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE StopTBGeneralExamination t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Long id); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralOpdRepo.java b/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralOpdRepo.java new file mode 100644 index 000000000..3cb8868f8 --- /dev/null +++ b/src/main/java/com/iemr/flw/repo/iemr/StopTBGeneralOpdRepo.java @@ -0,0 +1,42 @@ +package com.iemr.flw.repo.iemr; + +import com.iemr.flw.domain.iemr.StopTBGeneralOpd; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Repository +public interface StopTBGeneralOpdRepo extends JpaRepository { + + @Query("SELECT o FROM StopTBGeneralOpd o WHERE o.benRegID = :benRegID AND o.deleted = false") + StopTBGeneralOpd findByBenRegID(@Param("benRegID") Long benRegID); + + // Read-side fix: same NonUniqueResultException risk once a beneficiary has more than one + // visit. Pass PageRequest.of(0, 1) for the latest only. + @Query("SELECT o FROM StopTBGeneralOpd o WHERE o.benRegID = :benRegID " + + "AND o.deleted = false ORDER BY o.createdDate DESC") + List findLatestByBenRegID(@Param("benRegID") Long benRegID, Pageable pageable); + + @Query("SELECT o FROM StopTBGeneralOpd o WHERE o.benRegID = :benRegID " + + "AND o.visitCode = :visitCode AND o.deleted = false") + StopTBGeneralOpd findByBenRegIDAndVisitCode(@Param("benRegID") Long benRegID, @Param("visitCode") Long visitCode); + + @Query("SELECT o FROM StopTBGeneralOpd o WHERE o.providerServiceMapID = :psmId AND o.deleted = false ORDER BY o.createdDate DESC") + List findAllByProviderServiceMapID(@Param("psmId") Integer psmId); + + @Query("SELECT o FROM StopTBGeneralOpd o WHERE o.benRegID IN " + + "(SELECT b.beneficiaryRegID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId) " + + "AND o.deleted = false ORDER BY o.createdDate DESC") + List findAllByProviderServiceMapIDAndVillageID(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE StopTBGeneralOpd t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Long id); +} diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java index 31345dd40..122890e33 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBConfirmedTreatmentRepository.java @@ -2,7 +2,11 @@ import com.iemr.flw.domain.iemr.TBConfirmedCase; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @@ -13,5 +17,14 @@ public interface TBConfirmedTreatmentRepository List findByBenId(Long benId); List findByUserId(Integer benId); + List findByBenIdAndVisitCode(Long benId, Long visitCode); + @Query("SELECT tc FROM TBConfirmedCase tc WHERE tc.benId IN " + + "(SELECT b.beneficiaryID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId)") + List getByProviderServiceMapIdAndVillageId(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE TBConfirmedCase t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Integer id); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java b/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java index 61be2a57e..f656dc91d 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBScreeningRepo.java @@ -1,10 +1,13 @@ package com.iemr.flw.repo.iemr; import com.iemr.flw.domain.iemr.TBScreening; +import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.List; @@ -17,4 +20,30 @@ public interface TBScreeningRepo extends JpaRepository { @Query(value = "SELECT tbs FROM TBScreening tbs WHERE tbs.userId = :userId") List getByUserId(@Param("userId") Integer userId); + + @Query("SELECT tbs FROM TBScreening tbs WHERE tbs.benRegID = :benRegID AND tbs.deleted = false") + TBScreening findByBenRegID(@Param("benRegID") Long benRegID); + + // Read-side fix: same NonUniqueResultException risk as StopTBGeneralExaminationRepo once a + // beneficiary has more than one visit. Pass PageRequest.of(0, 1) for the latest only. + @Query("SELECT tbs FROM TBScreening tbs WHERE tbs.benRegID = :benRegID " + + "AND tbs.deleted = false ORDER BY tbs.visitDate DESC") + List findLatestByBenRegID(@Param("benRegID") Long benRegID, Pageable pageable); + + @Query("SELECT tbs FROM TBScreening tbs WHERE tbs.benRegID = :benRegID " + + "AND tbs.visitCode = :visitCode AND tbs.deleted = false") + TBScreening findByBenRegIDAndVisitCode(@Param("benRegID") Long benRegID, @Param("visitCode") Long visitCode); + + @Query("SELECT tbs FROM TBScreening tbs WHERE tbs.providerServiceMapID = :psmId AND tbs.deleted = false ORDER BY tbs.visitDate DESC") + List findAllByProviderServiceMapID(@Param("psmId") Integer psmId); + + @Query("SELECT tbs FROM TBScreening tbs WHERE tbs.benRegID IN " + + "(SELECT b.beneficiaryRegID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId) " + + "AND tbs.deleted = false ORDER BY tbs.visitDate DESC") + List findAllByProviderServiceMapIDAndVillageID(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE TBScreening t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Long id); } diff --git a/src/main/java/com/iemr/flw/repo/iemr/TBSuspectedRepo.java b/src/main/java/com/iemr/flw/repo/iemr/TBSuspectedRepo.java index 995ca7602..e559bdfbf 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/TBSuspectedRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/TBSuspectedRepo.java @@ -2,9 +2,11 @@ import com.iemr.flw.domain.iemr.TBSuspected; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.List; @@ -18,6 +20,19 @@ public interface TBSuspectedRepo extends JpaRepository { @Query("SELECT tbs FROM TBSuspected tbs WHERE tbs.benId = :benId and tbs.userId = :userId") TBSuspected getByUserIdAndBenId(@Param("benId") Long benId, @Param("userId") Integer userId); + @Query("SELECT tbs FROM TBSuspected tbs WHERE tbs.benId = :benId and tbs.userId = :userId and tbs.visitCode = :visitCode") + TBSuspected getByUserIdAndBenIdAndVisitCode(@Param("benId") Long benId, @Param("userId") Integer userId, + @Param("visitCode") Long visitCode); + @Query("SELECT tbs FROM TBSuspected tbs WHERE tbs.userId = :userId and tbs.visitDate >= :fromDate and tbs.visitDate <= :toDate") List getByUserId(@Param("userId") Integer userId, @Param("fromDate") Timestamp fromDate, @Param("toDate") Timestamp toDate); + + @Query("SELECT tbs FROM TBSuspected tbs WHERE tbs.benId IN " + + "(SELECT b.beneficiaryID FROM BenFlowStatus b WHERE b.providerServiceMapId = :psmId AND b.villageID = :villageId)") + List getByProviderServiceMapIdAndVillageId(@Param("psmId") Integer psmId, @Param("villageId") Integer villageId); + + @Transactional + @Modifying + @Query("UPDATE TBSuspected t SET t.vanSerialNo = t.id WHERE t.id = :id") + void updateVanSerialNo(@Param("id") Long id); } 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 2b78b68f7..f09602491 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -36,4 +36,9 @@ public interface UserServiceRoleRepo extends JpaRepository getDistrictByBlockId(@Param("blockId") Integer blockId); + } diff --git a/src/main/java/com/iemr/flw/seeder/TbCounsellingFormSeeder.java b/src/main/java/com/iemr/flw/seeder/TbCounsellingFormSeeder.java new file mode 100644 index 000000000..4fdd3a2d0 --- /dev/null +++ b/src/main/java/com/iemr/flw/seeder/TbCounsellingFormSeeder.java @@ -0,0 +1,325 @@ +/* + * 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.seeder; + +import com.iemr.flw.dto.iemr.DynamicFormDTO; +import com.iemr.flw.dto.iemr.FormSectionDTO; +import com.iemr.flw.dto.iemr.OptionConditionDTO; +import com.iemr.flw.dto.iemr.QuestionOptionDTO; +import com.iemr.flw.dto.iemr.QuestionValidationDTO; +import com.iemr.flw.dto.iemr.SectionQuestionDTO; +import com.iemr.flw.masterEnum.FormType; +import com.iemr.flw.masterEnum.QuestionType; +import com.iemr.flw.masterEnum.ValidationType; +import com.iemr.flw.repo.iemr.DynamicFormRepo; +import com.iemr.flw.service.DynamicFormDefinitionService; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +/** + * Seeds the TB Counselling form definition on application startup if it does not already exist. + * Idempotent: skips creation if the form UUID is already present in the database. + * + * @author Piramal Swasthya + */ +@Component +@RequiredArgsConstructor +public class TbCounsellingFormSeeder { + + private static final Logger log = LoggerFactory.getLogger(TbCounsellingFormSeeder.class); + + public static final String FORM_UUID = "TB_COUNSELLING"; + + private final DynamicFormDefinitionService formService; + private final DynamicFormRepo formRepo; + + @PostConstruct + public void seed() { + if (formRepo.findByFormUuid(FORM_UUID).isPresent()) { + log.info("TbCounsellingFormSeeder: form '{}' already exists — skipping seed.", FORM_UUID); + return; + } + log.info("TbCounsellingFormSeeder: seeding TB Counselling form..."); + formService.createForm(buildFormDto()); + log.info("TbCounsellingFormSeeder: seed complete."); + } + + // ── Form Definition ────────────────────────────────────────────────────────── + + private DynamicFormDTO buildFormDto() { + DynamicFormDTO dto = new DynamicFormDTO(); + dto.setFormUuid(FORM_UUID); + dto.setFormName("TB Counselling"); + dto.setFormType(FormType.TB_COUNSELLING); + dto.setIsActive(true); + dto.setFollowUpDelayDays(15); + + List sections = new ArrayList<>(); + sections.add(buildSectionA()); + sections.add(buildSectionB()); + sections.add(buildSectionC()); + sections.add(buildSectionD()); + sections.add(buildSectionE()); +// sections.add(buildSectionF()); + dto.setSections(sections); + return dto; + } + + // ── Section A: Disease Awareness ───────────────────────────────────────────── + + private FormSectionDTO buildSectionA() { + FormSectionDTO s = section("TB_SEC_A", "Disease Awareness", "बीमारी के बारे में जागरूकता", "PRE_SUBMIT", 1, true, false); + List qs = new ArrayList<>(); + qs.add(yesNoRadio("TB_A_Q1", "TB disease explained to patient", "मरीज़ को टीबी बीमारी के बारे में समझाया गया।", 1, true)); + qs.add(yesNoRadio("TB_A_Q2", "Transmission route explained", "ट्रांसमिशन के तरीके के बारे में जानकारी", 2, true)); + qs.add(yesNoRadio("TB_A_Q3", "Symptoms explained", "लक्षणों की जानकारी", 3, true)); + qs.add(yesNoRadio("TB_A_Q4", "Treatment duration explained", "इलाज की अवधि के बारे में जानकारी", 4, true)); + qs.add(textQuestion("TB_A_REMARKS", "Disease awareness notes", "बीमारी के बारे में जानकारी देने वाले नोट्स", 5, false, 500, true)); + s.setQuestions(qs); + return s; + } + + // ── Section B: Do's and Don'ts ─────────────────────────────────────────────── + + private FormSectionDTO buildSectionB() { + FormSectionDTO s = section("TB_SEC_B", "Do's and Don'ts", "करो और ना करो", "PRE_SUBMIT", 2, true, false); + List qs = new ArrayList<>(); + qs.add(yesNoRadio("TB_B_Q1", "Cover mouth while coughing — advised", "खांसते समय मुंह ढकने की सलाह दी जाती है।", 1, true)); + qs.add(yesNoRadio("TB_B_Q2", "Complete full treatment course — advised", "इलाज का पूरा कोर्स पूरा करने की सलाह दी जाती है।", 2, true)); + qs.add(yesNoRadio("TB_B_Q3", "Regular follow-up attendance — advised", "इलाज का पूरा कोर्स पूरा करने की सलाह दी जाती है।", 3, true)); + qs.add(yesNoRadio("TB_B_Q4", "Nutritional guidance provided", "पोषण संबंधी मार्गदर्शन प्रदान किया गया", 4, true)); + qs.add(yesNoRadio("TB_B_Q5", "No smoking / alcohol — advised", "धूम्रपान / शराब न लेने की सलाह दी जाती है।", 5, true)); + qs.add(yesNoRadio("TB_B_Q6", "Isolation precautions explained", "अलगाव सावधानियों के बारे में बताया गया", 6, true)); + qs.add(textQuestion("TB_B_REMARKS", "Do's & Don'ts notes", "क्या करें और क्या न करें - नोट्स", 7, false, 500, true)); + s.setQuestions(qs); + return s; + } + + // ── Section C: Government Schemes ──────────────────────────────────────────── + + private FormSectionDTO buildSectionC() { + FormSectionDTO s = section("TB_SEC_C", "Government Schemes", "सरकारी योजनाएं", "PRE_SUBMIT", 3, false, false); + List qs = new ArrayList<>(); + qs.add(yesNoRadio("TB_C_Q1", "Nikshay Poshan Yojana (NPY) eligibility explained", "निक्षय पोषण योजना (एनपीवाई) पात्रता के बारे में बताया गया", 1, true)); + qs.add(yesNoRadio("TB_C_Q2", "DOTS free treatment explained", "DOTS मुफ़्त इलाज के बारे में जानकारी", 2, true)); + qs.add(textQuestion("TB_C_REMARKS", "Schemes notes", "योजनाओं के नोट्स", 3, false, 300, true)); + s.setQuestions(qs); + return s; + } + + // ── Section D: Treatment Regimen ───────────────────────────────────────────── + + private FormSectionDTO buildSectionD() { + FormSectionDTO s = section("TB_SEC_D", "Treatment Regimen", "इलाज का तरीका", "PRE_SUBMIT", 4, true, false); + List qs = new ArrayList<>(); + qs.add(yesNoRadio("TB_D_Q1", "Regimen explained to patient", "मरीज़ को इलाज का तरीका समझाया गया।", 1, true)); + qs.add(yesNoRadio("TB_D_Q2", "Medication names explained", "दवाओं के नामों की जानकारी", 2, true)); + qs.add(yesNoRadio("TB_D_Q3", "Side effects explained", "साइड इफ़ेक्ट्स के बारे में जानकारी", 3, true)); + qs.add(yesNoRadio("TB_D_Q4", "Importance of adherence explained", "निर्देशों का पालन करने का महत्व समझाया गया", 4, true)); + qs.add(textQuestion("TB_D_REMARKS", "Treatment regimen notes", "इलाज के तरीके से जुड़े नोट्स", 5, false, 300, true)); + s.setQuestions(qs); + return s; + } + + // ── Section E: Counselling Completion ──────────────────────────────────────── + + private FormSectionDTO buildSectionE() { + FormSectionDTO s = section("TB_SEC_E", "Counselling Completion", "काउंसलिंग पूरी होना", "PRE_SUBMIT", 5, true, true); + List qs = new ArrayList<>(); + + // Counselling completion status — RADIO: Complete | Refused + SectionQuestionDTO statusQ = new SectionQuestionDTO(); + statusQ.setQuestionUuid("TB_E_Q1"); + statusQ.setQuestionText("Counselling completion status"); + statusQ.setQuestionTextHindi("काउंसलिंग पूरी होने की स्थिति"); + statusQ.setQuestionType(QuestionType.RADIO); + statusQ.setIsMandatory(true); + statusQ.setDisplayOrder(1); + statusQ.setVisibleByDefault(true); + + // "Complete" option — no conditions + QuestionOptionDTO completeOpt = option("Complete", "सम्पूर्ण","COMPLETE", "सम्पूर्ण", 1, List.of()); + + // "Refused" option — 5 conditions: disable sections A-D + show refusal text box + List refusedConditions = new ArrayList<>(); + refusedConditions.add(disableSectionValidation("TB_SEC_A")); + refusedConditions.add(disableSectionValidation("TB_SEC_B")); + refusedConditions.add(disableSectionValidation("TB_SEC_C")); + refusedConditions.add(disableSectionValidation("TB_SEC_D")); + refusedConditions.add(showQuestion("TB_E_REFUSAL")); + QuestionOptionDTO refusedOpt = option("Refused", "अस्वीकार करना", "REFUSED", "अस्वीकार करना", 2, refusedConditions); + + List statusOptions = new ArrayList<>(); + statusOptions.add(completeOpt); + statusOptions.add(refusedOpt); + statusQ.setOptions(statusOptions); + statusQ.setValidations(List.of()); + qs.add(statusQ); + + // Reason for refusal — hidden by default, max 300 chars + qs.add(textQuestion("TB_E_REFUSAL", "Reason for refusal", "इनकार का कारण",2, true, 300, false)); + + // Counsellor remarks — optional, max 500 chars + qs.add(textQuestion("TB_E_REMARKS", "Counsellor remarks", "काउंसलर की टिप्पणी", 3, false, 500, true)); + + s.setQuestions(qs); + return s; + } + + // ── Section F: Follow Up to TU ─────────────────────────────────────────────── + + private FormSectionDTO buildSectionF() { + FormSectionDTO s = section("TB_SEC_F", "Follow Up to TU", "TU के बाद की कार्रवाई", "POST_SUBMIT", 6, true, true); + List qs = new ArrayList<>(); + + // "Has the patient started TB treatment?" — RADIO: Yes | No + SectionQuestionDTO startedQ = new SectionQuestionDTO(); + startedQ.setQuestionUuid("TB_F_Q1"); + startedQ.setQuestionText("Has the patient started the prescribed TB treatment regimen?"); + startedQ.setQuestionTextHindi("क्या मरीज़ ने टीबी के लिए बताया गया इलाज शुरू कर दिया है?"); + startedQ.setQuestionType(QuestionType.RADIO); + startedQ.setIsMandatory(true); + startedQ.setDisplayOrder(1); + startedQ.setVisibleByDefault(true); + + QuestionOptionDTO yesOpt = option("Yes", "हाँ", "YES", "हाँ", 1, List.of()); + + List noConditions = new ArrayList<>(); + noConditions.add(showQuestion("TB_F_NO_REASON")); + QuestionOptionDTO noOpt = option("No", "नहीं", "NO", "नहीं", 2, noConditions); + + List startedOptions = new ArrayList<>(); + startedOptions.add(yesOpt); + startedOptions.add(noOpt); + startedQ.setOptions(startedOptions); + startedQ.setValidations(List.of()); + qs.add(startedQ); + + // Reason for not starting — hidden by default, max 500 chars + qs.add(textQuestion("TB_F_NO_REASON", + "Reason for not starting the prescribed TB treatment regimen", + "टीबी के लिए तय इलाज का तरीका शुरू न करने का कारण", + 2, false, 500, false)); + + // DOTS centre visit + qs.add(yesNoRadio("TB_F_Q2", + "Has the patient visited the DOTS centre / referred health facility for treatment collection?", + "क्या मरीज़ इलाज लेने के लिए DOTS सेंटर या रेफर किए गए स्वास्थ्य केंद्र गया है?", + 3, true)); + + // Side effects reported + qs.add(yesNoRadio("TB_F_Q3", + "Has the patient reported side effects to the treating doctor or DOTS centre?", + "क्या मरीज़ ने इलाज करने वाले डॉक्टर या DOTS सेंटर को साइड इफ़ेक्ट्स के बारे में बताया है?", + 4, true)); + + s.setQuestions(qs); + return s; + } + + // ── Builder Helpers ─────────────────────────────────────────────────────────── + + private FormSectionDTO section(String uuid, String name, String nameHindi, String phase, + int order, boolean required, boolean hasSubmitButton) { + FormSectionDTO s = new FormSectionDTO(); + s.setSectionUuid(uuid); + s.setSectionName(name); + s.setSectionNameHindi(nameHindi); + s.setSectionPhase(phase); + s.setDisplayOrder(order); + s.setIsRequired(required); + s.setHasSubmitButton(hasSubmitButton); + s.setQuestions(new ArrayList<>()); + return s; + } + + private SectionQuestionDTO yesNoRadio(String uuid, String text, String textHindi, int order, boolean mandatory) { + SectionQuestionDTO q = new SectionQuestionDTO(); + q.setQuestionUuid(uuid); + q.setQuestionText(text); + q.setQuestionTextHindi(textHindi); + q.setQuestionType(QuestionType.RADIO); + q.setIsMandatory(mandatory); + q.setDisplayOrder(order); + q.setVisibleByDefault(true); + + List opts = new ArrayList<>(); + opts.add(option("Yes", "हाँ","YES","हाँ", 1, List.of())); + opts.add(option("No", "नहीं","NO", "नहीं", 2, List.of())); + q.setOptions(opts); + q.setValidations(List.of()); + return q; + } + + private SectionQuestionDTO textQuestion(String uuid, String text, String textHindi, int order, + boolean mandatory, int maxLength, boolean visible) { + SectionQuestionDTO q = new SectionQuestionDTO(); + q.setQuestionUuid(uuid); + q.setQuestionText(text); + q.setQuestionTextHindi(textHindi); + q.setQuestionType(QuestionType.TEXT); + q.setIsMandatory(mandatory); + q.setDisplayOrder(order); + q.setMaxLength(maxLength); + q.setVisibleByDefault(visible); + q.setOptions(List.of()); + + QuestionValidationDTO v = new QuestionValidationDTO(); + v.setValidationType(ValidationType.MAX_LENGTH); + v.setValidationParam(String.valueOf(maxLength)); + v.setErrorMessage("Must be " + maxLength + " characters or fewer"); + q.setValidations(List.of(v)); + return q; + } + + private QuestionOptionDTO option(String label, String labelHindi, String value, String valueHindi, int order, + List conditions) { + QuestionOptionDTO o = new QuestionOptionDTO(); + o.setOptionLabel(label); + o.setOptionLabelHindi(labelHindi); + o.setOptionValue(value); + o.setOptionValueHindi(valueHindi); + o.setDisplayOrder(order); + o.setConditions(conditions); + return o; + } + + private OptionConditionDTO showQuestion(String targetQuestionUuid) { + OptionConditionDTO c = new OptionConditionDTO(); + c.setActionType("SHOW_QUESTION"); + c.setTargetQuestionUuid(targetQuestionUuid); + return c; + } + + private OptionConditionDTO disableSectionValidation(String targetSectionUuid) { + OptionConditionDTO c = new OptionConditionDTO(); + c.setActionType("DISABLE_SECTION_VALIDATION"); + c.setTargetSectionUuid(targetSectionUuid); + return c; + } +} diff --git a/src/main/java/com/iemr/flw/service/CampConfigService.java b/src/main/java/com/iemr/flw/service/CampConfigService.java new file mode 100644 index 000000000..a8c8ad350 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/CampConfigService.java @@ -0,0 +1,59 @@ +package com.iemr.flw.service; + +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.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.stereotype.Service; + +@Service +public class CampConfigService { + + private static final Logger logger = LoggerFactory.getLogger(CampConfigService.class); + private static final String VAN_ID_KEY = "camp:vanID"; + private static final String PARKING_PLACE_ID_KEY = "camp:parkingPlaceID"; + + @Autowired + private LettuceConnectionFactory connectionFactory; + + // When true, saves fail loudly if camp is not configured instead of silently storing vanID=NULL + @Value("${stoptb.enforce.vanid:false}") + private boolean enforceVanID; + + public Integer getVanID() { + String val = read(VAN_ID_KEY); + if (val == null || val.isBlank()) { + if (enforceVanID) { + throw new IllegalStateException( + "Camp not configured: vanID missing. Please select van/service point in MMU before saving Stop TB data."); + } + return null; + } + return Integer.parseInt(val); + } + + public Integer getParkingPlaceID() { + String val = read(PARKING_PLACE_ID_KEY); + if (val == null || val.isBlank()) return 0; + return Integer.parseInt(val); + } + + public boolean isCampConfigured() { + String val = read(VAN_ID_KEY); + return val != null && !val.isBlank(); + } + + private String read(String key) { + try { + RedisConnection conn = connectionFactory.getConnection(); + byte[] data = conn.get(key.getBytes()); + conn.close(); + return data != null ? new String(data) : null; + } catch (Exception e) { + logger.error("Redis read error for key {}: {}", key, e.getMessage()); + return null; + } + } +} diff --git a/src/main/java/com/iemr/flw/service/DynamicFormDefinitionService.java b/src/main/java/com/iemr/flw/service/DynamicFormDefinitionService.java new file mode 100644 index 000000000..c7aae24df --- /dev/null +++ b/src/main/java/com/iemr/flw/service/DynamicFormDefinitionService.java @@ -0,0 +1,59 @@ +/* + * 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; + +import com.iemr.flw.dto.iemr.DynamicFormDTO; +import com.iemr.flw.dto.iemr.FormSectionDTO; +import com.iemr.flw.dto.iemr.OptionConditionDTO; +import com.iemr.flw.dto.iemr.QuestionOptionDTO; +import com.iemr.flw.dto.iemr.QuestionValidationDTO; +import com.iemr.flw.dto.iemr.SectionQuestionDTO; + +import java.util.List; + +/** + * Service for managing dynamic form definitions (structure only — not responses). + */ +public interface DynamicFormDefinitionService { + + /** Creates a full form definition (form + v1 + sections + questions + options + validations). */ + DynamicFormDTO createForm(DynamicFormDTO formDTO); + + /** Replaces the form structure with a new version, bumping versionNumber. */ + DynamicFormDTO updateForm(Long formId, DynamicFormDTO formDTO); + + /** Returns the latest version's full definition tree, Redis-cached by formId. */ + DynamicFormDTO getFormDefinition(Long formId); + + /** Returns a specific version's full definition tree (no cache). */ + DynamicFormDTO getFormDefinitionByVersion(Long formId, Integer versionNumber); + + /** Returns metadata for all active forms (without full tree). */ + List getAllForms(); + + /** Sets the form's isActive flag to true. */ + void activateForm(Long formId); + + /** Sets the form's isActive flag to false and invalidates cache. */ + void deactivateForm(Long formId); + +} diff --git a/src/main/java/com/iemr/flw/service/DynamicFormResponseService.java b/src/main/java/com/iemr/flw/service/DynamicFormResponseService.java new file mode 100644 index 000000000..cca29e2e8 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/DynamicFormResponseService.java @@ -0,0 +1,66 @@ +/* + * 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; + +import com.iemr.flw.dto.iemr.FormResponseDTO; +import com.iemr.flw.dto.iemr.FormResponseRequest; +import com.iemr.flw.masterEnum.FormType; +import com.iemr.flw.utils.exception.IEMRException; + +import java.util.List; + +/** + * Contract for saving and retrieving dynamic form responses. + * + * @author Piramal Swasthya + */ +public interface DynamicFormResponseService { + + /** Save PRE_SUBMIT section answers and advance status to SUBMITTED. */ + FormResponseDTO submitForm(FormResponseRequest request); + + /** Save POST_SUBMIT section answers and advance status to COMPLETE. */ + FormResponseDTO completeForm(FormResponseRequest request, String jwtToken) throws IEMRException; + + /** All responses for a beneficiary filtered by form UUID. */ + List getResponsesByBeneficiary(Long beneficiaryId, String formUuid); + + /** Single response with all nested section and question answers. */ + FormResponseDTO getResponseById(Long responseId); + + /** + * Submit multiple form responses in one bulk transaction. + * All FormResponse rows are batch-inserted via saveAll() so responseIds are available + * before section/question processing begins. All-or-nothing: any failure rolls back all. + */ + List submitBulk(List requests, String jwtToken); + + /** + * Returns SUBMITTED responses for the given form IDs whose {@code lastFollowUpAt} + * falls within the 24-hour window that started exactly {@code delayDays} days ago. + * Used by the follow-up notification scheduler. + */ + List findPendingFollowUps(List formIds, int delayDays); + + /** Returns beneficiary IDs with COMPLETE status for the given form type, optionally filtered by village and/or provider service map. */ + List getCompletedBeneficiaries(FormType formType, Integer villageId, Integer providerServiceMapId); +} diff --git a/src/main/java/com/iemr/flw/service/StopTBService.java b/src/main/java/com/iemr/flw/service/StopTBService.java new file mode 100644 index 000000000..e549daa6f --- /dev/null +++ b/src/main/java/com/iemr/flw/service/StopTBService.java @@ -0,0 +1,22 @@ +package com.iemr.flw.service; + +import java.util.List; +import java.util.Map; + +public interface StopTBService { + // Nurse — General Examination + List> saveGeneralExamination(List> dataList) throws Exception; + Map getAllGeneralExaminations(Integer providerServiceMapID, Integer villageID) throws Exception; + + // Nurse — TB Screening + List> saveNurseTBScreening(List> dataList) throws Exception; + Map getAllNurseTBScreenings(Integer providerServiceMapID, Integer villageID) throws Exception; + + // Nurse — General OPD + List> saveGeneralOpd(List> dataList) throws Exception; + Map getAllGeneralOpd(Integer providerServiceMapID, Integer villageID) throws Exception; + + // Nurse — Diagnostics + List> saveDiagnostics(List> dataList) throws Exception; + Map getAllDiagnostics(Integer providerServiceMapID, Integer villageID) throws Exception; +} diff --git a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java index 64505b791..6471f7996 100644 --- a/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java +++ b/src/main/java/com/iemr/flw/service/TBConfirmedCaseService.java @@ -13,4 +13,6 @@ public interface TBConfirmedCaseService { String getByBenId(Long benId, String authorisation) throws Exception; String getByUserId(String authorisation) throws Exception; + + String getByProviderServiceMapId(Integer providerServiceMapID, Integer villageID) throws Exception; } diff --git a/src/main/java/com/iemr/flw/service/TBStopVisitService.java b/src/main/java/com/iemr/flw/service/TBStopVisitService.java new file mode 100644 index 000000000..0e15fd9b3 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/TBStopVisitService.java @@ -0,0 +1,9 @@ +package com.iemr.flw.service; + +import com.iemr.flw.domain.iemr.BenVisitDetail; + +public interface TBStopVisitService { + + BenVisitDetail getOrCreateVisitForToday(Long beneficiaryRegID, Integer providerServiceMapID, + String createdBy, Integer vanID, Integer parkingPlaceID); +} diff --git a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java index 15ca0e7cc..f9098c398 100644 --- a/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/AbhaBeneficiaryServiceImpl.java @@ -3,6 +3,7 @@ import com.google.gson.Gson; import com.iemr.flw.controller.AbhaBeneficiaryController; import com.iemr.flw.domain.iemr.AbhaApiResponse; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarymapping; import com.iemr.flw.dto.abhaBeneficiary.AbhaBeneficiaryDTO; import com.iemr.flw.dto.iemr.AbhaRequestDTO; import com.iemr.flw.repo.identity.BeneficiaryRepo; @@ -55,7 +56,10 @@ public Object getBeneficiaryByAbha(AbhaRequestDTO request) { if(request.getHouseHoldId()!=null){ benRedId = beneficiaryRepo.findByHouseoldId(request.getHouseHoldId()).get(0).getBenRegId(); if(benRedId!=null){ - benDetailsdId = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)).getBenDetailsId(); + List mappings = beneficiaryRepo.findByBenRegIdFromMapping(BigInteger.valueOf(benRedId)); + if (!mappings.isEmpty()) { + benDetailsdId = mappings.get(0).getBenDetailsId(); + } } if(benDetailsdId!=null){ 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 23c4bd602..b70ce80ed 100644 --- a/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/BeneficiaryServiceImpl.java @@ -1,5 +1,6 @@ package com.iemr.flw.service.impl; +import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Date; import java.sql.Timestamp; @@ -21,6 +22,7 @@ import com.iemr.flw.dto.iemr.EyeCheckupListDTO; import com.iemr.flw.dto.iemr.EyeCheckupRequestDTO; import com.iemr.flw.masterEnum.GroupName; +import com.iemr.flw.domain.iemr.BenFlowStatus; import com.iemr.flw.repo.iemr.*; import com.iemr.flw.service.IncentiveLogicService; import com.iemr.flw.service.UserService; @@ -54,8 +56,12 @@ import com.iemr.flw.domain.identity.RMNCHMBeneficiarymapping; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.mapper.InputMapper; +import com.iemr.flw.domain.iemr.BenAnthropometryDetail; +import com.iemr.flw.domain.iemr.BenPhysicalVitalDetail; import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.identity.HouseHoldRepo; +import com.iemr.flw.repo.iemr.BenAnthropometryRepo; +import com.iemr.flw.repo.iemr.BenPhysicalVitalRepo; import com.iemr.flw.service.BeneficiaryService; import com.iemr.flw.utils.config.ConfigProperties; import com.iemr.flw.utils.http.HttpUtils; @@ -101,20 +107,68 @@ public class BeneficiaryServiceImpl implements BeneficiaryService { @Autowired private IncentiveLogicService incentiveLogicService; + @Autowired + private BenFlowStatusRepo benFlowStatusRepo; + + @Autowired + private UserServiceRoleRepo userRepo; + + @Autowired + private BenAnthropometryRepo benAnthropometryRepo; + + @Autowired + private BenPhysicalVitalRepo benPhysicalVitalRepo; + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy"); @Override public String getBenData(GetBenRequestHandler request, String authorisation) throws Exception { - if (request == null || request.getAshaId() == null) { - throw new Exception("Invalid/missing asha details"); + if (request == null) { + throw new Exception("Invalid request"); } if (request.getPageNo() == null || request.getPageNo() < 0) { throw new Exception("Invalid page number"); } + int pageSize = Integer.parseInt(door_to_door_page_size); + + // Stop TB path: filter by providerServiceMapID + villageID + if (request.getProviderServiceMapID() != null && request.getVillageID() != null) { + List flows = benFlowStatusRepo.getRegistrarWorklist( + request.getProviderServiceMapID(), request.getVillageID()); + + if (flows == null || flows.isEmpty()) return null; + + List allAddresses = new ArrayList<>(); + for (BenFlowStatus flow : flows) { + if (flow.getBeneficiaryRegID() == null) continue; + List mappings = beneficiaryRepo.findByBenRegIdFromMapping( + BigInteger.valueOf(flow.getBeneficiaryRegID())); + if (mappings.isEmpty()) continue; + RMNCHMBeneficiarymapping mapping = mappings.get(0); + if (mapping.getBenAddressId() == null) continue; + RMNCHMBeneficiaryaddress address = beneficiaryRepo.getAddressById(mapping.getBenAddressId()); + if (address != null) allAddresses.add(address); + } + + if (allAddresses.isEmpty()) return null; + + int totalPage = (int) Math.ceil((double) allAddresses.size() / pageSize); + int start = request.getPageNo() * pageSize; + int end = Math.min(start + pageSize, allAddresses.size()); + if (start >= allAddresses.size()) return null; + + return getMappingsForAddressIDs(allAddresses.subList(start, end), totalPage, authorisation); + } + + // Normal FLW/ASHA path + if (request.getAshaId() == null) { + throw new Exception("Invalid/missing asha details"); + } + String userName = beneficiaryRepo.getUserName(request.getAshaId()); if (userName == null || userName.isEmpty()) { @@ -123,12 +177,10 @@ public String getBenData(GetBenRequestHandler request, String authorisation) thr request.setUserName(userName); - int pageSize = Integer.parseInt(door_to_door_page_size); PageRequest pageRequest = PageRequest.of(request.getPageNo(), pageSize); Page pageResult; - // ✅ Date Filter Handling if (request.getFromDate() != null && request.getToDate() != null) { if (request.getFromDate().after(request.getToDate())) { @@ -143,7 +195,6 @@ public String getBenData(GetBenRequestHandler request, String authorisation) thr ); } else { - pageResult = beneficiaryRepo.getBenDataByUser(userName, pageRequest); } @@ -215,11 +266,9 @@ private String getMappingsForAddressIDs(List addressLi .getDetailsByRegID((m.getBenRegId()).longValue()).isEmpty()){ benDetailsRMNCH_OBJ = beneficiaryRepo .getDetailsByRegID((m.getBenRegId()).longValue()).get(0); - } benBotnBirthRMNCH_ROBJ = beneficiaryRepo.getBornBirthByRegID((m.getBenRegId()).longValue()); - if (benDetailsRMNCH_OBJ != null && benDetailsRMNCH_OBJ.getHouseoldId() != null) if(!houseHoldRepo .getByHouseHoldID(benDetailsRMNCH_OBJ.getHouseoldId()).isEmpty()){ @@ -294,6 +343,29 @@ private String getMappingsForAddressIDs(List addressLi benDetailsRMNCH_OBJ.setAddressLine2(benAddressOBJ.getPermAddrLine2()); if (benAddressOBJ.getPermAddrLine3() != null) benDetailsRMNCH_OBJ.setAddressLine3(benAddressOBJ.getPermAddrLine3()); + if (benAddressOBJ.getPermPinCode() != null) + benDetailsRMNCH_OBJ.setPinCode(benAddressOBJ.getPermPinCode()); + + // GPS fallback: if not in RMNCH details (syncdatatoamrti not yet called), + // pull from i_beneficiaryaddress (saved during TM-API registration) + if (benDetailsRMNCH_OBJ.getGpsLatitude() == null && benAddressOBJ.getGpsLatitude() != null) + benDetailsRMNCH_OBJ.setGpsLatitude(benAddressOBJ.getGpsLatitude()); + if (benDetailsRMNCH_OBJ.getGpsLongitude() == null && benAddressOBJ.getGpsLongitude() != null) + benDetailsRMNCH_OBJ.setGpsLongitude(benAddressOBJ.getGpsLongitude()); + if (benDetailsRMNCH_OBJ.getDigipin() == null && benAddressOBJ.getDigipin() != null) + benDetailsRMNCH_OBJ.setDigipin(benAddressOBJ.getDigipin()); + if (benDetailsRMNCH_OBJ.getGpsTimestamp() == null && benAddressOBJ.getGpsTimestamp() != null) + benDetailsRMNCH_OBJ.setGpsTimestamp(benAddressOBJ.getGpsTimestamp()); + if (benDetailsRMNCH_OBJ.getIsGpsUnavailable() == null && benAddressOBJ.getIsGpsUnavailable() != null) + benDetailsRMNCH_OBJ.setIsGpsUnavailable(benAddressOBJ.getIsGpsUnavailable()); + if (benDetailsRMNCH_OBJ.getGpsUnavailableReason() == null && benAddressOBJ.getGpsUnavailableReason() != null) + benDetailsRMNCH_OBJ.setGpsUnavailableReason(benAddressOBJ.getGpsUnavailableReason()); + + // Map GPS double fields to the exposed latitude/longitude BigDecimal fields for response + if (benDetailsRMNCH_OBJ.getGpsLatitude() != null) + benDetailsRMNCH_OBJ.setLatitude(BigDecimal.valueOf(benDetailsRMNCH_OBJ.getGpsLatitude())); + if (benDetailsRMNCH_OBJ.getGpsLongitude() != null) + benDetailsRMNCH_OBJ.setLongitude(BigDecimal.valueOf(benDetailsRMNCH_OBJ.getGpsLongitude())); // ----------------------------------------------------------------------------- @@ -319,8 +391,15 @@ private String getMappingsForAddressIDs(List addressLi if (benContactOBJ.getPreferredPhoneNum() != null) benDetailsRMNCH_OBJ.setContact_number(benContactOBJ.getPreferredPhoneNum()); - if (benDetailsOBJ.getDob() != null) + if (benDetailsOBJ.getDob() != null) { benDetailsRMNCH_OBJ.setDob(benDetailsOBJ.getDob()); + } else { + // i_beneficiarydetails.dob is null for Stop TB mobile registrations + // (Identity-API mapper commented out) — fall back to i_ben_flow_outreach.ben_dob + List flows = benFlowStatusRepo.findByBeneficiaryRegID(m.getBenRegId().longValue()); + if (!flows.isEmpty() && flows.get(0).getDob() != null) + benDetailsRMNCH_OBJ.setDob(flows.get(0).getDob()); + } if (benDetailsOBJ.getFatherName() != null) benDetailsRMNCH_OBJ.setFatherName(benDetailsOBJ.getFatherName()); if (benDetailsOBJ.getFirstName() != null) @@ -363,9 +442,9 @@ private String getMappingsForAddressIDs(List addressLi String ageDetails = ""; int age_val = 0; String ageUnit = null; - if (benDetailsOBJ.getDob() != null) { + if (benDetailsRMNCH_OBJ.getDob() != null) { - Date date = new Date(benDetailsOBJ.getDob().getTime()); + Date date = new Date(benDetailsRMNCH_OBJ.getDob().getTime()); Calendar cal = Calendar.getInstance(); cal.setTime(date); @@ -438,8 +517,82 @@ private String getMappingsForAddressIDs(List addressLi ? benDetailsRMNCH_OBJ.getIsDeactivate() : false ); + resultMap.put("economicStatus",benDetailsOBJ.getEconomicStatus()); + resultMap.put("economicStatusId",benDetailsOBJ.getEconomicStatusId()); + resultMap.put("residentialAreaId",benDetailsOBJ.getResidentialAreaId()); + resultMap.put("residentialArea",benDetailsOBJ.getResidentialArea()); + resultMap.put("address",benDetailsOBJ.getAddress()); + resultMap.put("updateDate", benDetailsOBJ.getLastModDate()); + resultMap.put("updatedBy", benDetailsOBJ.getModifiedBy()); resultMap.put("BenRegId", m.getBenRegId()); + // occupation from i_beneficiarydetails + if (benDetailsOBJ != null && benDetailsOBJ.getOccupation() != null) + benDetailsRMNCH_OBJ.setOccupation(benDetailsOBJ.getOccupation()); + + // anthropometry from t_phy_anthropometry, vitals from t_phy_vitals + // fallback to otherFields if exam not yet saved for this beneficiary + Long benRegIdLong = m.getBenRegId() != null ? m.getBenRegId().longValue() : null; + if (benRegIdLong != null) { + List anthroList = + benAnthropometryRepo.findByBeneficiaryRegIDOrderByCreatedDateDesc(benRegIdLong); + List vitalList = + benPhysicalVitalRepo.findByBeneficiaryRegIDOrderByCreatedDateDesc(benRegIdLong); + + Map anthropometry = new HashMap<>(); + if (!anthroList.isEmpty()) { + BenAnthropometryDetail anthro = anthroList.get(0); + if (anthro.getHeightCm() != null) anthropometry.put("height", anthro.getHeightCm()); + if (anthro.getWeightKg() != null) anthropometry.put("weight", anthro.getWeightKg()); + if (anthro.getBmi() != null) anthropometry.put("bmi", anthro.getBmi()); + } + if (!vitalList.isEmpty()) { + BenPhysicalVitalDetail vital = vitalList.get(0); + if (vital.getTemperature() != null) anthropometry.put("temperatureValue", vital.getTemperature()); + if (vital.getPulseRate() != null) anthropometry.put("pulseRate", vital.getPulseRate()); + if (vital.getSystolicBP() != null) anthropometry.put("systolicBP", vital.getSystolicBP()); + if (vital.getDiastolicBP() != null) anthropometry.put("diastolicBP", vital.getDiastolicBP()); + if (vital.getBloodGlucoseRandom() != null) anthropometry.put("bloodGlucoseRandom", vital.getBloodGlucoseRandom()); + } + + // fallback: if no exam saved yet, read from registration otherFields + if (anthropometry.isEmpty() && benDetailsOBJ != null && benDetailsOBJ.getOtherFields() != null) { + try { + Map extraFields = new Gson().fromJson(benDetailsOBJ.getOtherFields(), Map.class); + if (extraFields.containsKey("weight")) anthropometry.put("weight", extraFields.get("weight")); + if (extraFields.containsKey("height")) anthropometry.put("height", extraFields.get("height")); + if (extraFields.containsKey("bmi")) anthropometry.put("bmi", extraFields.get("bmi")); + if (extraFields.containsKey("temperatureValue")) anthropometry.put("temperatureValue", extraFields.get("temperatureValue")); + } catch (Exception ex) { + logger.warn("Could not parse otherFields for fallback anthropometry: " + benDetailsOBJ.getBeneficiaryDetailsId()); + } + } + if (!anthropometry.isEmpty()) resultMap.put("anthropometry", anthropometry); + } + + // Stop TB fields from ExtraFields + Map stopTBDetails = new HashMap<>(); + if (benDetailsOBJ != null && benDetailsOBJ.getOtherFields() != null) { + try { + Map extraFields = new Gson().fromJson(benDetailsOBJ.getOtherFields(), Map.class); + + if (extraFields.containsKey("personFrom")) stopTBDetails.put("personFrom", extraFields.get("personFrom")); + if (extraFields.containsKey("caseFindingType")) stopTBDetails.put("caseFindingType", extraFields.get("caseFindingType")); + if (extraFields.containsKey("isMobileAvailable")) stopTBDetails.put("isMobileAvailable", extraFields.get("isMobileAvailable")); + if (extraFields.containsKey("tuId")) stopTBDetails.put("tuId", extraFields.get("tuId")); + if (extraFields.containsKey("tuName")) stopTBDetails.put("tuName", extraFields.get("tuName")); + + // economicStatus and residentialArea into beneficiaryDetails + if (extraFields.containsKey("economicStatus")) benDetailsRMNCH_OBJ.setEconomicStatus((String) extraFields.get("economicStatus")); + if (extraFields.containsKey("economicStatusId")) benDetailsRMNCH_OBJ.setEconomicStatusId(((Number) extraFields.get("economicStatusId")).intValue()); + if (extraFields.containsKey("residentialArea")) benDetailsRMNCH_OBJ.setResidentialArea((String) extraFields.get("residentialArea")); + if (extraFields.containsKey("residentialAreaId")) benDetailsRMNCH_OBJ.setResidentialAreaId(((Number) extraFields.get("residentialAreaId")).intValue()); + } catch (Exception ex) { + logger.warn("Could not parse ExtraFields for benDetailsId: " + benDetailsOBJ.getBeneficiaryDetailsId()); + } + } + if (!stopTBDetails.isEmpty()) resultMap.put("stopTBDetails", stopTBDetails); + // adding asha id / created by - user id if (benAddressOBJ.getCreatedBy() != null) { Integer userID = beneficiaryRepo.getUserIDByUserName(benAddressOBJ.getCreatedBy()); diff --git a/src/main/java/com/iemr/flw/service/impl/DynamicFormDefinitionServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DynamicFormDefinitionServiceImpl.java new file mode 100644 index 000000000..c40b65d7b --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/DynamicFormDefinitionServiceImpl.java @@ -0,0 +1,416 @@ +/* + * 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.impl; + +import com.iemr.flw.domain.iemr.DynamicForm; +import com.iemr.flw.domain.iemr.FormSection; +import com.iemr.flw.domain.iemr.FormVersion; +import com.iemr.flw.domain.iemr.OptionCondition; +import com.iemr.flw.domain.iemr.QuestionOption; +import com.iemr.flw.domain.iemr.QuestionValidation; +import com.iemr.flw.domain.iemr.SectionQuestion; +import com.iemr.flw.dto.iemr.DynamicFormDTO; +import com.iemr.flw.dto.iemr.FormSectionDTO; +import com.iemr.flw.dto.iemr.OptionConditionDTO; +import com.iemr.flw.dto.iemr.QuestionOptionDTO; +import com.iemr.flw.dto.iemr.QuestionValidationDTO; +import com.iemr.flw.dto.iemr.SectionQuestionDTO; +import com.iemr.flw.mapper.DynamicFormMapper; +import com.iemr.flw.repo.iemr.DynamicFormRepo; +import com.iemr.flw.repo.iemr.FormSectionRepo; +import com.iemr.flw.repo.iemr.FormVersionRepo; +import com.iemr.flw.repo.iemr.OptionConditionRepo; +import com.iemr.flw.repo.iemr.QuestionOptionRepo; +import com.iemr.flw.repo.iemr.QuestionValidationRepo; +import com.iemr.flw.repo.iemr.SectionQuestionRepo; +import com.iemr.flw.service.DynamicFormDefinitionService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Implementation of DynamicFormDefinitionService with version-aware writes. + * Every structural change clones all sections fresh into a new FormVersion. + * Sections have a direct FK to FormVersion (no join table). + * + * @author Piramal Swasthya + */ +@Slf4j +@RequiredArgsConstructor +@Service +public class DynamicFormDefinitionServiceImpl implements DynamicFormDefinitionService { + + private final DynamicFormRepo formRepo; + private final FormSectionRepo sectionRepo; + private final SectionQuestionRepo questionRepo; + private final QuestionOptionRepo optionRepo; + private final OptionConditionRepo conditionRepo; + private final QuestionValidationRepo validationRepo; + private final FormVersionRepo versionRepo; + private final DynamicFormMapper mapper; + + // ── PUBLIC WRITE METHODS ────────────────────────────────────────────────── + + @Override + @Transactional + public DynamicFormDTO createForm(DynamicFormDTO dto) { + formRepo.findByFormTypeAndIsActive(dto.getFormType(), true).ifPresent(existing -> { + throw new IllegalStateException( + "An active form of type " + dto.getFormType() + " already exists (formId=" + + existing.getFormId() + "). Deactivate it before creating a new one."); + }); + DynamicForm form = mapper.toEntity(dto); + // TODO: set audit fields when auth is re-enabled for /dynamicForm endpoints + // form.setCreatedBy(jwtUtil.extractUsername(authorization)); + // form.setUpdatedBy(jwtUtil.extractUsername(authorization)); + DynamicForm savedForm = formRepo.save(form); + FormVersion version = createNewVersion(savedForm, 1, null, null); + buildSectionsFromDto(dto.getSections(), version); + log.info("Form created: {} (v1)", savedForm.getFormUuid()); + return loadLatestFromDb(savedForm.getFormId()); + } + + @Override + @Transactional + public DynamicFormDTO updateForm(Long formId, DynamicFormDTO dto) { + DynamicForm form = requireForm(formId); + FormVersion current = requireLatestVersion(formId); + int nextVersion = current.getVersionNumber() + 1; + FormVersion newVersion = createNewVersion(form, nextVersion, null, null); + buildSectionsFromDto(dto.getSections(), newVersion); + current.setIsLatest(false); + versionRepo.save(current); + log.info("Form updated: {} -> v{}", form.getFormUuid(), nextVersion); + return loadLatestFromDb(formId); + } + + @Override + @Transactional + public void activateForm(Long formId) { + DynamicForm form = requireForm(formId); + form.setIsActive(true); + formRepo.save(form); + log.info("Form activated: {}", form.getFormUuid()); + } + + @Override + @Transactional + public void deactivateForm(Long formId) { + DynamicForm form = requireForm(formId); + form.setIsActive(false); + formRepo.save(form); + log.info("Form deactivated: {}", form.getFormUuid()); + } + + @Override + public DynamicFormDTO getFormDefinition(Long formId) { + return loadLatestFromDb(formId); + } + + @Override + public DynamicFormDTO getFormDefinitionByVersion(Long formId, Integer versionNumber) { + FormVersion version = versionRepo.findByDynamicForm_FormIdAndVersionNumber(formId, versionNumber) + .orElseThrow(() -> new RuntimeException( + "Version " + versionNumber + " not found for formId: " + formId)); + return buildFormDto(version.getDynamicForm(), version); + } + + @Override + public List getAllForms() { + return formRepo.findByIsActiveOrderByFormIdAsc(true) + .stream() + .map(form -> { + try { + return loadLatestFromDb(form.getFormId()); + } catch (RuntimeException e) { + log.warn("Skipping form {} — no active version: {}", form.getFormId(), e.getMessage()); + return null; + } + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + // ── VERSION MANAGEMENT ──────────────────────────────────────────────────── + + private FormVersion createNewVersion(DynamicForm form, int versionNumber, + String createdBy, String notes) { + FormVersion version = new FormVersion(); + version.setDynamicForm(form); + version.setVersionNumber(versionNumber); + version.setIsLatest(true); + version.setCreatedBy(createdBy); + // TODO: set audit fields when auth is re-enabled for /dynamicForm endpoints + // version.setCreatedBy(jwtUtil.extractUsername(authorization)); + // version.setUpdatedBy(jwtUtil.extractUsername(authorization)); + version.setNotes(notes); + return versionRepo.save(version); + } + + // ── BUILD HELPERS (DTO → Entity) ────────────────────────────────────────── + + /** + * Two-pass build: + * Pass 1 — persist sections, questions, options, validations; collect uuid→entity maps. + * Pass 2 — wire conditions using targetQuestionUuid/targetSectionUuid from those maps. + */ + private void buildSectionsFromDto(List dtos, FormVersion version) { + if (dtos == null) return; + + Map sectionByUuid = new LinkedHashMap<>(); + Map questionByUuid = new LinkedHashMap<>(); + Map> pendingConditions = new LinkedHashMap<>(); + + // Pass 1: sections → questions → options + validations + for (FormSectionDTO sDto : dtos) { + FormSection section = mapper.toEntity(sDto); + section.setFormVersion(version); + section.setQuestions(new ArrayList<>()); + FormSection savedSection = sectionRepo.save(section); + sectionByUuid.put(savedSection.getSectionUuid(), savedSection); + + if (sDto.getQuestions() == null) continue; + for (SectionQuestionDTO qDto : sDto.getQuestions()) { + SectionQuestion q = mapper.toEntity(qDto); + q.setFormSection(savedSection); + q.setOptions(new ArrayList<>()); + q.setValidations(new ArrayList<>()); + SectionQuestion savedQ = questionRepo.save(q); + questionByUuid.put(savedQ.getQuestionUuid(), savedQ); + + if (qDto.getOptions() != null) { + for (QuestionOptionDTO oDto : qDto.getOptions()) { + QuestionOption opt = mapper.toEntity(oDto); + opt.setSectionQuestion(savedQ); + opt.setConditions(new ArrayList<>()); + QuestionOption savedOpt = optionRepo.save(opt); + if (oDto.getConditions() != null && !oDto.getConditions().isEmpty()) { + pendingConditions.put(savedOpt, oDto.getConditions()); + } + } + } + if (qDto.getValidations() != null) { + for (QuestionValidationDTO vDto : qDto.getValidations()) { + buildValidationEntity(vDto, savedQ); + } + } + } + } + + // Pass 2: conditions — resolve targets by UUID (create path) or ID (addCondition path) + for (Map.Entry> entry : pendingConditions.entrySet()) { + QuestionOption opt = entry.getKey(); + for (OptionConditionDTO cDto : entry.getValue()) { + OptionCondition cond = new OptionCondition(); + cond.setActionType(cDto.getActionType()); + cond.setQuestionOption(opt); + + if (cDto.getTargetQuestionUuid() != null) { + SectionQuestion target = questionByUuid.get(cDto.getTargetQuestionUuid()); + if (target == null) throw new RuntimeException( + "targetQuestionUuid not found in this form: " + cDto.getTargetQuestionUuid()); + cond.setTargetQuestion(target); + } else if (cDto.getTargetQuestionId() != null) { + cond.setTargetQuestion(requireQuestion(cDto.getTargetQuestionId())); + } + + if (cDto.getTargetSectionUuid() != null) { + FormSection target = sectionByUuid.get(cDto.getTargetSectionUuid()); + if (target == null) throw new RuntimeException( + "targetSectionUuid not found in this form: " + cDto.getTargetSectionUuid()); + cond.setTargetSection(target); + } else if (cDto.getTargetSectionId() != null) { + cond.setTargetSection(requireSection(cDto.getTargetSectionId())); + } + + conditionRepo.save(cond); + } + } + } + + private QuestionValidation buildValidationEntity(QuestionValidationDTO dto, + SectionQuestion question) { + QuestionValidation v = mapper.toEntity(dto); + v.setSectionQuestion(question); + return validationRepo.save(v); + } + + // ── LOAD / READ HELPERS ─────────────────────────────────────────────────── + + private DynamicFormDTO loadLatestFromDb(Long formId) { + FormVersion version = versionRepo.findByDynamicForm_FormIdAndIsLatest(formId, true) + .orElseThrow(() -> new RuntimeException("No active version for formId: " + formId)); + return buildFormDto(version.getDynamicForm(), version); + } + + /** + * Builds the full form DTO using exactly 5 queries (constant regardless of form size). + * All grouping, visibleByDefault computation, and embedded question/section population + * happen in memory — zero extra queries beyond the initial 5. + */ + private DynamicFormDTO buildFormDto(DynamicForm form, FormVersion version) { + // Query 1: sections + List sections = sectionRepo + .findByFormVersion_VersionIdOrderByDisplayOrderAsc(version.getVersionId()); + if (sections.isEmpty()) { + DynamicFormDTO dto = mapper.toDto(form); + dto.setVersionNumber(version.getVersionNumber()); + dto.setSections(Collections.emptyList()); + return dto; + } + + List sectionIds = sections.stream().map(FormSection::getSectionId) + .collect(Collectors.toList()); + + // Query 2: questions + List allQuestions = questionRepo + .findBySectionIdsOrderByDisplayOrderAsc(sectionIds); + + List questionIds = allQuestions.stream().map(SectionQuestion::getQuestionId) + .collect(Collectors.toList()); + + List allOptions; + List allValidations; + List allConditions; + + if (questionIds.isEmpty()) { + allOptions = Collections.emptyList(); + allValidations = Collections.emptyList(); + allConditions = Collections.emptyList(); + } else { + // Query 3: options + allOptions = optionRepo.findByQuestionIdsOrderByDisplayOrderAsc(questionIds); + // Query 4: validations + allValidations = validationRepo.findByQuestionIds(questionIds); + + List optionIds = allOptions.stream().map(QuestionOption::getOptionId) + .collect(Collectors.toList()); + // Query 5: conditions (LEFT JOIN FETCH targets) + allConditions = optionIds.isEmpty() ? Collections.emptyList() + : conditionRepo.findByOptionIds(optionIds); + } + + // Compute hidden question IDs (those targeted by any condition) + Set hiddenIds = allConditions.stream() + .filter(c -> c.getTargetQuestion() != null) + .map(c -> c.getTargetQuestion().getQuestionId()) + .collect(Collectors.toSet()); + + // Build index maps — no extra queries; FKs already in memory via JOIN FETCH + Map> questionsBySection = allQuestions.stream() + .collect(Collectors.groupingBy(q -> q.getFormSection().getSectionId())); + Map> optionsByQuestion = allOptions.stream() + .collect(Collectors.groupingBy(o -> o.getSectionQuestion().getQuestionId())); + Map> validationsByQuestion = allValidations.stream() + .collect(Collectors.groupingBy(v -> v.getSectionQuestion().getQuestionId())); + Map> conditionsByOption = allConditions.stream() + .collect(Collectors.groupingBy(c -> c.getQuestionOption().getOptionId())); + + DynamicFormDTO dto = mapper.toDto(form); + dto.setVersionNumber(version.getVersionNumber()); + dto.setSections(assembleSectionDtos(sections, questionsBySection, optionsByQuestion, + validationsByQuestion, conditionsByOption, hiddenIds)); + return dto; + } + + private List assembleSectionDtos( + List sections, + Map> questionsBySection, + Map> optionsByQuestion, + Map> validationsByQuestion, + Map> conditionsByOption, + Set hiddenIds) { + return sections.stream().map(section -> { + FormSectionDTO sDto = mapper.toDto(section); + List qs = questionsBySection + .getOrDefault(section.getSectionId(), Collections.emptyList()); + sDto.setQuestions(assembleQuestionDtos(qs, optionsByQuestion, + validationsByQuestion, conditionsByOption, hiddenIds)); + return sDto; + }).collect(Collectors.toList()); + } + + private List assembleQuestionDtos( + List questions, + Map> optionsByQuestion, + Map> validationsByQuestion, + Map> conditionsByOption, + Set hiddenIds) { + return questions.stream().map(q -> { + SectionQuestionDTO qDto = mapper.toDto(q); + qDto.setVisibleByDefault(!hiddenIds.contains(q.getQuestionId())); + List opts = optionsByQuestion + .getOrDefault(q.getQuestionId(), Collections.emptyList()); + qDto.setOptions(assembleOptionDtos(opts, conditionsByOption)); + qDto.setValidations(validationsByQuestion + .getOrDefault(q.getQuestionId(), Collections.emptyList()) + .stream().map(mapper::toDto).collect(Collectors.toList())); + return qDto; + }).collect(Collectors.toList()); + } + + private List assembleOptionDtos( + List options, + Map> conditionsByOption) { + return options.stream().map(opt -> { + QuestionOptionDTO oDto = mapper.toDto(opt); + oDto.setConditions(conditionsByOption + .getOrDefault(opt.getOptionId(), Collections.emptyList()) + .stream().map(mapper::toDto).collect(Collectors.toList())); + return oDto; + }).collect(Collectors.toList()); + } + + // ── REQUIRE HELPERS ─────────────────────────────────────────────────────── + + private DynamicForm requireForm(Long formId) { + return formRepo.findById(formId) + .orElseThrow(() -> new RuntimeException("Form not found: " + formId)); + } + + private FormVersion requireLatestVersion(Long formId) { + return versionRepo.findByDynamicForm_FormIdAndIsLatest(formId, true) + .orElseThrow(() -> new RuntimeException( + "No latest version found for formId: " + formId)); + } + + private FormSection requireSection(Long sectionId) { + return sectionRepo.findById(sectionId) + .orElseThrow(() -> new RuntimeException("Section not found: " + sectionId)); + } + + private SectionQuestion requireQuestion(Long questionId) { + return questionRepo.findById(questionId) + .orElseThrow(() -> new RuntimeException("Question not found: " + questionId)); + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java new file mode 100644 index 000000000..6e3b29c2f --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/DynamicFormResponseServiceImpl.java @@ -0,0 +1,504 @@ +/* + * 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.impl; + +import com.iemr.flw.domain.iemr.FormResponse; +import com.iemr.flw.domain.iemr.FormSection; +import com.iemr.flw.domain.iemr.FormVersion; +import com.iemr.flw.domain.iemr.QuestionOption; +import com.iemr.flw.domain.iemr.QuestionResponse; +import com.iemr.flw.domain.iemr.SectionQuestion; +import com.iemr.flw.domain.iemr.SectionResponse; +import com.iemr.flw.dto.iemr.FormResponseDTO; +import com.iemr.flw.dto.iemr.FormResponseRequest; +import com.iemr.flw.dto.iemr.QuestionAnswerRequest; +import com.iemr.flw.dto.iemr.QuestionResponseDTO; +import com.iemr.flw.dto.iemr.SectionAnswerRequest; +import com.iemr.flw.dto.iemr.SectionResponseDTO; +import com.iemr.flw.domain.iemr.DynamicForm; +import com.iemr.flw.masterEnum.FormType; +import com.iemr.flw.repo.iemr.DynamicFormRepo; +import com.iemr.flw.repo.iemr.FormResponseRepo; +import com.iemr.flw.repo.iemr.FormSectionRepo; +import com.iemr.flw.repo.iemr.FormVersionRepo; +import com.iemr.flw.repo.iemr.QuestionOptionRepo; +import com.iemr.flw.repo.iemr.QuestionResponseRepo; +import com.iemr.flw.repo.iemr.SectionQuestionRepo; +import com.iemr.flw.repo.iemr.SectionResponseRepo; +import com.iemr.flw.masterEnum.QuestionType; +import com.iemr.flw.service.CampConfigService; +import com.iemr.flw.service.DynamicFormResponseService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Handles save, submit, complete, and fetch of dynamic form responses. + * Resolves the latest FormVersion server-side so the client only needs to send formUuid. + * + * @author Piramal Swasthya + */ +@Slf4j +@RequiredArgsConstructor +@Service +public class DynamicFormResponseServiceImpl implements DynamicFormResponseService { + + private static final String STATUS_DRAFT = "DRAFT"; + private static final String STATUS_SUBMITTED = "SUBMITTED"; + private static final String STATUS_COMPLETE = "COMPLETE"; + private static final String SECTION_STATUS_DONE = "DONE"; + + private final DynamicFormRepo dynamicFormRepo; + private final FormResponseRepo formResponseRepo; + private final SectionResponseRepo sectionResponseRepo; + private final QuestionResponseRepo questionResponseRepo; + private final FormVersionRepo formVersionRepo; + private final FormSectionRepo formSectionRepo; + private final SectionQuestionRepo sectionQuestionRepo; + private final QuestionOptionRepo questionOptionRepo; + private final FormResponseItemSaver itemSaver; + private final JwtUtil jwtUtil; + private final CampConfigService campConfigService; + + @Override + @Transactional + public FormResponseDTO submitForm(FormResponseRequest request) { + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + FormVersion version = resolveLatestVersion(request.getFormUuid()); + Timestamp now = new Timestamp(System.currentTimeMillis()); + FormResponse formResponse; + if (request.getResponseId() != null) { + // Re-submit: update existing SUBMITTED response's sections + formResponse = formResponseRepo.findById(request.getResponseId()) + .orElseThrow(() -> new NoSuchElementException( + "FormResponse not found: " + request.getResponseId())); + if (STATUS_COMPLETE.equals(formResponse.getStatus())) { + throw new IllegalStateException( + "Cannot update a COMPLETE response (responseId=" + request.getResponseId() + ")"); + } + // Bump submittedAt to reflect the re-submission time + formResponse.setStatus(STATUS_SUBMITTED); + formResponse.setSubmittedAt(now); + formResponse.setLastFollowUpAt(now); + formResponse = formResponseRepo.save(formResponse); + } else { + formResponse = createFormResponse(request, version, STATUS_SUBMITTED, now, vanID, parkingPlaceID); + } + return processSections(formResponse, request, version, null, vanID, parkingPlaceID); + } + + @Override + @Transactional + public FormResponseDTO completeForm(FormResponseRequest request, String jwtToken) throws IEMRException { + String actor = jwtUtil.extractUserId(jwtToken).toString(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + + FormVersion version = resolveLatestVersion(request.getFormUuid()); + Long formId = version.getDynamicForm().getFormId(); + Timestamp now = new Timestamp(System.currentTimeMillis()); + + List existing = + formResponseRepo.findByBeneficiaryIdAndFormId(request.getBeneficiaryId(), formId); + FormResponse formResponse = existing.isEmpty() + ? createFormResponse(request, version, STATUS_COMPLETE, now, vanID, parkingPlaceID) + : existing.get(0); + + formResponse.setUpdatedBy(actor); + formResponse.setStatus(STATUS_COMPLETE); + formResponse.setCompletedAt(now); + formResponse = formResponseRepo.save(formResponse); + return processSections(formResponse, request, version, actor, vanID, parkingPlaceID); + } + + @Override + @Transactional(readOnly = true) + public List getResponsesByBeneficiary(Long beneficiaryId, String formUuid) { + FormVersion version = resolveLatestVersion(formUuid); + Long formId = version.getDynamicForm().getFormId(); + + List responses = + formResponseRepo.findByBeneficiaryIdAndFormId(beneficiaryId, formId); + return responses.stream() + .map(r -> buildFormResponseDTO(r, loadSectionResponseDTOs(r.getResponseId()))) + .collect(Collectors.toList()); + } + + @Override + @Transactional(readOnly = true) + public FormResponseDTO getResponseById(Long responseId) { + FormResponse formResponse = formResponseRepo.findById(responseId) + .orElseThrow(() -> new NoSuchElementException("FormResponse not found: " + responseId)); + return buildFormResponseDTO(formResponse, loadSectionResponseDTOs(responseId)); + } + + // ---- private helpers ---- + + private FormVersion resolveLatestVersion(String formUuid) { + return formVersionRepo.findByDynamicForm_FormUuidAndIsLatest(formUuid, true) + .orElseThrow(() -> new NoSuchElementException( + "No active FormVersion found for form code: " + formUuid)); + } + + /** Creates a new FormResponse row. */ + private FormResponse createFormResponse( + FormResponseRequest request, + FormVersion version, + String status, + Timestamp submittedAt, + Integer vanID, + Integer parkingPlaceID) { + + FormResponse formResponse = FormResponse.builder() + .beneficiaryId(request.getBeneficiaryId()) + .formId(version.getDynamicForm().getFormId()) + .versionId(version.getVersionId()) + .officerId(request.getOfficerId()) + .status(status) + .submittedAt(submittedAt) + .lastFollowUpAt(submittedAt) + // TODO: set audit fields when auth is re-enabled for /dynamicForm/response endpoints + // .createdBy(jwtUtil.extractUsername(authorization)) + // .updatedBy(jwtUtil.extractUsername(authorization)) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build(); + return formResponseRepo.save(formResponse); + } + + /** + * Batch-loads all sections and questions for the version, then processes each answered section. + */ + private FormResponseDTO processSections( + FormResponse formResponse, + FormResponseRequest request, + FormVersion version, + String actor, + Integer vanID, + Integer parkingPlaceID) { + + List allSections = + formSectionRepo.findByFormVersion_VersionIdOrderByDisplayOrderAsc(version.getVersionId()); + Map sectionByUuid = allSections.stream() + .collect(Collectors.toMap(FormSection::getSectionUuid, Function.identity())); + + Set sectionIds = allSections.stream() + .map(FormSection::getSectionId) + .collect(Collectors.toSet()); + + List allQuestions = + sectionQuestionRepo.findBySectionIdsOrderByDisplayOrderAsc(sectionIds); + Map> questionsBySection = allQuestions.stream() + .collect(Collectors.groupingBy( + q -> q.getFormSection().getSectionId(), + Collectors.toMap(SectionQuestion::getQuestionUuid, Function.identity()))); + + Set questionIds = allQuestions.stream() + .map(SectionQuestion::getQuestionId) + .collect(Collectors.toSet()); + List allOptions = + questionOptionRepo.findByQuestionIdsOrderByDisplayOrderAsc(questionIds); + + // Map: questionId → (optionValue → QuestionOption) + Map> optionsByQuestion = allOptions.stream() + .collect(Collectors.groupingBy( + o -> o.getSectionQuestion().getQuestionId(), + Collectors.toMap(QuestionOption::getOptionValue, Function.identity()))); + + List sectionDTOs = new ArrayList<>(); + for (SectionAnswerRequest sectionReq : request.getSections()) { + if (sectionReq.getSectionUuid() == null) { + throw new IllegalArgumentException( + "sectionUuid is null — did you send sectionCode instead?"); + } + FormSection section = sectionByUuid.get(sectionReq.getSectionUuid()); + if (section == null) { + throw new NoSuchElementException( + "Section '" + sectionReq.getSectionUuid() + + "' not found in form '" + request.getFormUuid() + "'"); + } + + SectionResponse sectionResponse = upsertSectionResponse( + formResponse.getResponseId(), section.getSectionId(), actor, vanID, parkingPlaceID); + + if ("POST_SUBMIT".equals(section.getSectionPhase())) { + formResponse.setLastFollowUpAt(sectionResponse.getSavedAt()); + formResponseRepo.save(formResponse); + } + + Map questionMap = + questionsBySection.getOrDefault(section.getSectionId(), Map.of()); + + List questionResponses = processAnswers( + sectionResponse.getSectionResponseId(), + sectionReq.getAnswers(), + questionMap, + optionsByQuestion, + actor, + vanID, + parkingPlaceID); + + questionResponseRepo.saveAll(questionResponses); + + sectionDTOs.add(buildSectionResponseDTO(sectionResponse, questionResponses)); + } + + return buildFormResponseDTO(formResponse, sectionDTOs); + } + + private SectionResponse upsertSectionResponse(Long responseId, Long sectionId, String actor, + Integer vanID, Integer parkingPlaceID) { + Optional existing = + sectionResponseRepo.findByResponseIdAndSectionId(responseId, sectionId); + if (existing.isPresent()) { + SectionResponse sr = existing.get(); + sr.setStatus(SECTION_STATUS_DONE); + sr.setSavedAt(new Timestamp(System.currentTimeMillis())); + sr.setUpdatedBy(actor); + if (sr.getVanID() == null) { sr.setVanID(vanID); sr.setParkingPlaceID(parkingPlaceID); } + return sectionResponseRepo.save(sr); + } + SectionResponse sr = SectionResponse.builder() + .responseId(responseId) + .sectionId(sectionId) + .status(SECTION_STATUS_DONE) + .savedAt(new Timestamp(System.currentTimeMillis())) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build(); + return sectionResponseRepo.save(sr); + } + + private List processAnswers( + Long sectionResponseId, + List answers, + Map questionMap, + Map> optionsByQuestion, + String actor, + Integer vanID, + Integer parkingPlaceID) { + + List results = new ArrayList<>(); + + for (QuestionAnswerRequest answer : answers) { + if (answer.getQuestionUuid() == null) { + throw new IllegalArgumentException( + "questionUuid is null — did you send questionCode instead?"); + } + SectionQuestion question = questionMap.get(answer.getQuestionUuid()); + if (question == null) { + throw new NoSuchElementException( + "Question '" + answer.getQuestionUuid() + "' not found in section"); + } + QuestionType type = question.getQuestionType(); + Long questionId = question.getQuestionId(); + + if (type == QuestionType.DISPLAY) { + // DISPLAY questions carry no answer data + continue; + } + + // Delete any existing answers for this question in this section (handles re-saves) + questionResponseRepo.deleteByQuestionIdAndSectionResponseId(questionId, sectionResponseId); + + if (type == QuestionType.RADIO) { + if (answer.getOptionValue() != null) { + QuestionOption opt = resolveOption( + optionsByQuestion, questionId, answer.getOptionValue(), answer.getQuestionUuid()); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .optionId(opt != null ? opt.getOptionId() : null) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } else if (type == QuestionType.MCQ) { + if (answer.getOptionValues() != null) { + for (String val : answer.getOptionValues()) { + QuestionOption opt = resolveOption( + optionsByQuestion, questionId, val, answer.getQuestionUuid()); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .optionId(opt != null ? opt.getOptionId() : null) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } + } else { + // TEXT, DATE, AUTO_FILL — prefer answerText, then answerDate, then optionValue (legacy) + String value = answer.getAnswerText() != null ? answer.getAnswerText() + : answer.getAnswerDate() != null ? answer.getAnswerDate() + : answer.getOptionValue(); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .answerText(value) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } + return results; + } + + private QuestionOption resolveOption( + Map> optionsByQuestion, + Long questionId, + String optionValue, + String questionUuid) { + + Map opts = optionsByQuestion.get(questionId); + if (opts == null || !opts.containsKey(optionValue)) { + log.warn("Option value '{}' not found for question '{}', storing null optionId", + optionValue, questionUuid); + return null; + } + return opts.get(optionValue); + } + + // ---- read helpers ---- + + private List loadSectionResponseDTOs(Long responseId) { + List sections = sectionResponseRepo.findByResponseId(responseId); + if (sections.isEmpty()) { + return List.of(); + } + Set srIds = sections.stream() + .map(SectionResponse::getSectionResponseId) + .collect(Collectors.toSet()); + List allAnswers = + questionResponseRepo.findBySectionResponseIdIn(srIds); + Map> answersBySectionResponse = allAnswers.stream() + .collect(Collectors.groupingBy(QuestionResponse::getSectionResponseId)); + + return sections.stream() + .map(sr -> buildSectionResponseDTO( + sr, + answersBySectionResponse.getOrDefault(sr.getSectionResponseId(), List.of()))) + .collect(Collectors.toList()); + } + + private FormResponseDTO buildFormResponseDTO(FormResponse r, List sections) { + return FormResponseDTO.builder() + .responseId(r.getResponseId()) + .beneficiaryId(r.getBeneficiaryId()) + .formId(r.getFormId()) + .versionId(r.getVersionId()) + .officerId(r.getOfficerId()) + .status(r.getStatus()) + .createdBy(r.getCreatedBy()) + .updatedBy(r.getUpdatedBy()) + .submittedAt(r.getSubmittedAt()) + .completedAt(r.getCompletedAt()) + .lastFollowUpAt(r.getLastFollowUpAt()) + .createdAt(r.getCreatedAt()) + .updatedAt(r.getUpdatedAt()) + .sections(sections) + .build(); + } + + private SectionResponseDTO buildSectionResponseDTO( + SectionResponse sr, List answers) { + List answerDTOs = answers.stream() + .map(a -> QuestionResponseDTO.builder() + .questionResponseId(a.getQuestionResponseId()) + .questionId(a.getQuestionId()) + .optionId(a.getOptionId()) + .answerText(a.getAnswerText()) + .build()) + .collect(Collectors.toList()); + return SectionResponseDTO.builder() + .sectionResponseId(sr.getSectionResponseId()) + .sectionId(sr.getSectionId()) + .status(sr.getStatus()) + .savedAt(sr.getSavedAt()) + .answers(answerDTOs) + .build(); + } + + @Override + public List submitBulk(List requests, String jwtToken) { + if (requests == null || requests.isEmpty()) return List.of(); + List results = new ArrayList<>(); + for (FormResponseRequest req : requests) { + try { + results.add(itemSaver.saveForBulk(req, jwtToken)); + } catch (Exception ex) { + log.warn("submitBulk: item skipped for beneficiaryId={} — {}", + req.getBeneficiaryId(), ex.getMessage()); + } + } + return results; + } + + @Override + @Transactional(readOnly = true) + public List findPendingFollowUps(List formIds, int delayDays) { + if (formIds == null || formIds.isEmpty()) { + return List.of(); + } + LocalDate target = LocalDate.now().minusDays(delayDays); + Timestamp windowStart = Timestamp.valueOf(target.atStartOfDay()); + Timestamp windowEnd = Timestamp.valueOf(target.plusDays(1).atStartOfDay()); + return formResponseRepo.findPendingFollowUps(formIds, windowStart, windowEnd) + .stream() + .map(r -> buildFormResponseDTO(r, List.of())) + .collect(Collectors.toList()); + } + + @Override + @Transactional(readOnly = true) + public List getCompletedBeneficiaries(FormType formType, Integer villageId, Integer providerServiceMapId) { + DynamicForm form = dynamicFormRepo.findByFormTypeAndIsActive(formType, true) + .orElseThrow(() -> new NoSuchElementException( + "No active form found for type: " + formType)); + return (villageId != null || providerServiceMapId != null) + ? formResponseRepo.findBeneficiaryIdsByFormIdAndStatusFiltered(form.getFormId(), STATUS_COMPLETE, villageId, providerServiceMapId) + : formResponseRepo.findBeneficiaryIdsByFormIdAndStatus(form.getFormId(), STATUS_COMPLETE); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/FormFollowUpNotificationScheduler.java b/src/main/java/com/iemr/flw/service/impl/FormFollowUpNotificationScheduler.java new file mode 100644 index 000000000..5062c9fb1 --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/FormFollowUpNotificationScheduler.java @@ -0,0 +1,110 @@ +/* + * 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.impl; + +import com.iemr.flw.domain.iemr.DynamicForm; +import com.iemr.flw.dto.iemr.FormResponseDTO; +import com.iemr.flw.repo.iemr.DynamicFormRepo; +import com.iemr.flw.service.DynamicFormResponseService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Generic daily scheduler that sends follow-up push notifications for any active + * dynamic form with a configured {@code followUpDelayDays}. The notification fires + * exactly N days after the most recently completed section (PRE_SUBMIT submission or + * any subsequent POST_SUBMIT section completion). + * + * @author Piramal Swasthya + */ +@Service +public class FormFollowUpNotificationScheduler { + + private static final Logger log = + LoggerFactory.getLogger(FormFollowUpNotificationScheduler.class); + + private final DynamicFormRepo dynamicFormRepo; + private final DynamicFormResponseService responseService; + private final NotificationService notificationService; + + public FormFollowUpNotificationScheduler( + DynamicFormRepo dynamicFormRepo, + DynamicFormResponseService responseService, + NotificationService notificationService) { + this.dynamicFormRepo = dynamicFormRepo; + this.responseService = responseService; + this.notificationService = notificationService; + } + + @Scheduled(cron = "0 0 9 * * *") + public void sendFollowUpReminders() { + log.info("FormFollowUpNotificationScheduler: starting daily follow-up scan"); + + List formsWithDelay = + dynamicFormRepo.findByIsActiveTrueAndFollowUpDelayDaysIsNotNull(); + + if (formsWithDelay.isEmpty()) { + log.debug("No active forms with followUpDelayDays configured — skipping"); + return; + } + + // Group by delay value so we issue one batch DB query per distinct delay + Map> byDelay = formsWithDelay.stream() + .collect(Collectors.groupingBy( + DynamicForm::getFollowUpDelayDays, + Collectors.mapping(DynamicForm::getFormId, Collectors.toList()))); + + for (Map.Entry> entry : byDelay.entrySet()) { + int delayDays = entry.getKey(); + List formIds = entry.getValue(); + + try { + List pending = + responseService.findPendingFollowUps(formIds, delayDays); + + log.info("delayDays={}: found {} pending follow-up(s)", delayDays, pending.size()); + + for (FormResponseDTO r : pending) { + try { + //Notification sending logic + log.info("Sent follow-up notification: responseId={}, officerId={}", + r.getResponseId(), r.getOfficerId()); + } catch (Exception e) { + log.error("Failed to send notification for responseId={}: {}", + r.getResponseId(), e.getMessage()); + } + } + } catch (Exception e) { + log.error("Follow-up scheduler failed for delayDays={}: {}", + delayDays, e.getMessage(), e); + } + } + + log.info("FormFollowUpNotificationScheduler: scan complete"); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java b/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java new file mode 100644 index 000000000..6a8fb863f --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/FormResponseItemSaver.java @@ -0,0 +1,420 @@ +/* + * 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.impl; + +import com.iemr.flw.domain.iemr.FormResponse; +import com.iemr.flw.domain.iemr.FormSection; +import com.iemr.flw.domain.iemr.FormVersion; +import com.iemr.flw.domain.iemr.QuestionOption; +import com.iemr.flw.domain.iemr.QuestionResponse; +import com.iemr.flw.domain.iemr.SectionQuestion; +import com.iemr.flw.domain.iemr.SectionResponse; +import com.iemr.flw.dto.iemr.FormResponseDTO; +import com.iemr.flw.dto.iemr.FormResponseRequest; +import com.iemr.flw.dto.iemr.QuestionAnswerRequest; +import com.iemr.flw.dto.iemr.QuestionResponseDTO; +import com.iemr.flw.dto.iemr.SectionAnswerRequest; +import com.iemr.flw.dto.iemr.SectionResponseDTO; +import com.iemr.flw.repo.iemr.FormResponseRepo; +import com.iemr.flw.repo.iemr.FormSectionRepo; +import com.iemr.flw.repo.iemr.FormVersionRepo; +import com.iemr.flw.repo.iemr.QuestionOptionRepo; +import com.iemr.flw.repo.iemr.QuestionResponseRepo; +import com.iemr.flw.repo.iemr.SectionQuestionRepo; +import com.iemr.flw.repo.iemr.SectionResponseRepo; +import com.iemr.flw.masterEnum.QuestionType; +import com.iemr.flw.service.CampConfigService; +import com.iemr.flw.utils.JwtUtil; +import com.iemr.flw.utils.exception.IEMRException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Saves a single dynamic form response in its own REQUIRES_NEW transaction. + * Used by submitBulk so that each item in the batch is independently committed or rolled back — + * a failed item does not affect sibling items in the same bulk request. + * + * @author Piramal Swasthya + */ +@Slf4j +@RequiredArgsConstructor +@Component +public class FormResponseItemSaver { + + private static final String STATUS_SUBMITTED = "SUBMITTED"; + private static final String SECTION_STATUS_DONE = "DONE"; + + private final FormResponseRepo formResponseRepo; + private final SectionResponseRepo sectionResponseRepo; + private final QuestionResponseRepo questionResponseRepo; + private final FormVersionRepo formVersionRepo; + private final FormSectionRepo formSectionRepo; + private final SectionQuestionRepo sectionQuestionRepo; + private final QuestionOptionRepo questionOptionRepo; + private final JwtUtil jwtUtil; + private final CampConfigService campConfigService; + + /** + * Saves one form response in its own independent REQUIRES_NEW transaction. + * Order: validate → delete old → save new. If save fails the transaction rolls back, + * restoring the deleted rows automatically. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW) + public FormResponseDTO saveForBulk(FormResponseRequest req, String jwtToken) throws IEMRException { + String actor = jwtUtil.extractUserId(jwtToken).toString(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + FormVersion version = resolveLatestVersion(req.getFormUuid()); + Timestamp now = new Timestamp(System.currentTimeMillis()); + Long formId = version.getDynamicForm().getFormId(); + + // Step 1: Validate all section + question UUIDs BEFORE any writes or deletes + validateRequest(req, version); + + // Step 2: Check for an existing response for this beneficiary+form + List existing = + formResponseRepo.findByBeneficiaryIdAndFormId(req.getBeneficiaryId(), formId); + + FormResponse formResponse; + if (!existing.isEmpty()) { + formResponse = existing.get(0); + Long responseId = formResponse.getResponseId(); + + // Step 3: Update FormResponse header + formResponse.setStatus(STATUS_SUBMITTED); + formResponse.setSubmittedAt(now); + formResponse.setUpdatedBy(actor); + formResponse.setLastFollowUpAt(now); + formResponse = formResponseRepo.save(formResponse); + log.info("saveForBulk: overwriting responseId={} for beneficiaryId={}", + formResponse.getResponseId(), req.getBeneficiaryId()); + } else { + formResponse = createFormResponse(req, version, now, actor, vanID, parkingPlaceID); + } + + // Step 5: Insert fresh sections and answers + return processSections(formResponse, req, version, actor, vanID, parkingPlaceID); + } + + /** Pre-flight: validates every sectionUuid and questionUuid in the request exist in the form. */ + private void validateRequest(FormResponseRequest req, FormVersion version) { + List allSections = + formSectionRepo.findByFormVersion_VersionIdOrderByDisplayOrderAsc(version.getVersionId()); + Map sectionByUuid = allSections.stream() + .collect(Collectors.toMap(FormSection::getSectionUuid, Function.identity())); + + Set sectionIds = allSections.stream() + .map(FormSection::getSectionId) + .collect(Collectors.toSet()); + List allQuestions = + sectionQuestionRepo.findBySectionIdsOrderByDisplayOrderAsc(sectionIds); + Map> questionUuidsBySectionId = allQuestions.stream() + .collect(Collectors.groupingBy( + q -> q.getFormSection().getSectionId(), + Collectors.mapping(SectionQuestion::getQuestionUuid, Collectors.toSet()))); + + for (SectionAnswerRequest sectionReq : req.getSections()) { + FormSection section = sectionByUuid.get(sectionReq.getSectionUuid()); + if (section == null) { + throw new NoSuchElementException( + "Section '" + sectionReq.getSectionUuid() + + "' not found in form '" + req.getFormUuid() + "'"); + } + Set validQuestions = + questionUuidsBySectionId.getOrDefault(section.getSectionId(), Set.of()); + for (QuestionAnswerRequest answer : sectionReq.getAnswers()) { + if (answer.getQuestionUuid() != null + && !validQuestions.contains(answer.getQuestionUuid())) { + throw new NoSuchElementException( + "Question '" + answer.getQuestionUuid() + + "' not found in section '" + sectionReq.getSectionUuid() + "'"); + } + } + } + } + + // ---- private helpers ---- + + private FormVersion resolveLatestVersion(String formUuid) { + return formVersionRepo.findByDynamicForm_FormUuidAndIsLatest(formUuid, true) + .orElseThrow(() -> new NoSuchElementException( + "No active FormVersion found for form: " + formUuid)); + } + + private FormResponse createFormResponse(FormResponseRequest req, FormVersion version, Timestamp now, String actor, + Integer vanID, Integer parkingPlaceID) { + FormResponse formResponse = FormResponse.builder() + .beneficiaryId(req.getBeneficiaryId()) + .formId(version.getDynamicForm().getFormId()) + .versionId(version.getVersionId()) + .officerId(req.getOfficerId()) + .status(STATUS_SUBMITTED) + .createdBy(actor) + .updatedBy(actor) + .submittedAt(now) + .lastFollowUpAt(now) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build(); + return formResponseRepo.save(formResponse); + } + + private FormResponseDTO processSections(FormResponse formResponse, FormResponseRequest req, FormVersion version, String actor, + Integer vanID, Integer parkingPlaceID) { + List allSections = + formSectionRepo.findByFormVersion_VersionIdOrderByDisplayOrderAsc(version.getVersionId()); + Map sectionByUuid = allSections.stream() + .collect(Collectors.toMap(FormSection::getSectionUuid, Function.identity())); + + Set sectionIds = allSections.stream() + .map(FormSection::getSectionId) + .collect(Collectors.toSet()); + + List allQuestions = + sectionQuestionRepo.findBySectionIdsOrderByDisplayOrderAsc(sectionIds); + Map> questionsBySection = allQuestions.stream() + .collect(Collectors.groupingBy( + q -> q.getFormSection().getSectionId(), + Collectors.toMap(SectionQuestion::getQuestionUuid, Function.identity()))); + + Set questionIds = allQuestions.stream() + .map(SectionQuestion::getQuestionId) + .collect(Collectors.toSet()); + List allOptions = + questionOptionRepo.findByQuestionIdsOrderByDisplayOrderAsc(questionIds); + Map> optionsByQuestion = allOptions.stream() + .collect(Collectors.groupingBy( + o -> o.getSectionQuestion().getQuestionId(), + Collectors.toMap(QuestionOption::getOptionValue, Function.identity()))); + + List sectionDTOs = new ArrayList<>(); + for (SectionAnswerRequest sectionReq : req.getSections()) { + if (sectionReq.getSectionUuid() == null) { + throw new IllegalArgumentException( + "sectionUuid is null — did you send sectionCode instead?"); + } + FormSection section = sectionByUuid.get(sectionReq.getSectionUuid()); + if (section == null) { + throw new NoSuchElementException( + "Section '" + sectionReq.getSectionUuid() + + "' not found in form '" + req.getFormUuid() + "'"); + } + + // Delete existing SectionResponse (and its QuestionResponses) for this section only + sectionResponseRepo.findByResponseIdAndSectionId( + formResponse.getResponseId(), section.getSectionId()) + .ifPresent(sr -> { + questionResponseRepo.deleteBySectionResponseIdIn(Set.of(sr.getSectionResponseId())); + sectionResponseRepo.deleteById(sr.getSectionResponseId()); + }); + + SectionResponse sectionResponse = upsertSectionResponse( + formResponse.getResponseId(), section.getSectionId(), actor, vanID, parkingPlaceID); + + if ("POST_SUBMIT".equals(section.getSectionPhase())) { + formResponse.setLastFollowUpAt(sectionResponse.getSavedAt()); + formResponseRepo.save(formResponse); + } + + Map questionMap = + questionsBySection.getOrDefault(section.getSectionId(), Map.of()); + + List questionResponses = processAnswers( + sectionResponse.getSectionResponseId(), + sectionReq.getAnswers(), + questionMap, + optionsByQuestion, + actor, + vanID, + parkingPlaceID); + + questionResponseRepo.saveAll(questionResponses); + sectionDTOs.add(buildSectionResponseDTO(sectionResponse, questionResponses)); + } + + return buildFormResponseDTO(formResponse, sectionDTOs); + } + + private SectionResponse upsertSectionResponse(Long responseId, Long sectionId, String actor, + Integer vanID, Integer parkingPlaceID) { + Optional existing = + sectionResponseRepo.findByResponseIdAndSectionId(responseId, sectionId); + if (existing.isPresent()) { + SectionResponse sr = existing.get(); + sr.setStatus(SECTION_STATUS_DONE); + sr.setSavedAt(new Timestamp(System.currentTimeMillis())); + sr.setUpdatedBy(actor); + if (sr.getVanID() == null) { sr.setVanID(vanID); sr.setParkingPlaceID(parkingPlaceID); } + return sectionResponseRepo.save(sr); + } + SectionResponse sr = SectionResponse.builder() + .responseId(responseId) + .sectionId(sectionId) + .status(SECTION_STATUS_DONE) + .savedAt(new Timestamp(System.currentTimeMillis())) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build(); + return sectionResponseRepo.save(sr); + } + + private List processAnswers( + Long sectionResponseId, + List answers, + Map questionMap, + Map> optionsByQuestion, + String actor, + Integer vanID, + Integer parkingPlaceID) { + + List results = new ArrayList<>(); + for (QuestionAnswerRequest answer : answers) { + if (answer.getQuestionUuid() == null) { + throw new IllegalArgumentException( + "questionUuid is null — did you send questionCode instead?"); + } + SectionQuestion question = questionMap.get(answer.getQuestionUuid()); + if (question == null) { + throw new NoSuchElementException( + "Question '" + answer.getQuestionUuid() + "' not found in section"); + } + QuestionType type = question.getQuestionType(); + Long questionId = question.getQuestionId(); + + if (type == QuestionType.DISPLAY) { + continue; + } + + questionResponseRepo.deleteByQuestionIdAndSectionResponseId(questionId, sectionResponseId); + + if (type == QuestionType.RADIO) { + if (answer.getOptionValue() != null) { + QuestionOption opt = resolveOption(optionsByQuestion, questionId, + answer.getOptionValue(), answer.getQuestionUuid()); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .optionId(opt != null ? opt.getOptionId() : null) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } else if (type == QuestionType.MCQ) { + if (answer.getOptionValues() != null) { + for (String val : answer.getOptionValues()) { + QuestionOption opt = resolveOption(optionsByQuestion, questionId, val, + answer.getQuestionUuid()); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .optionId(opt != null ? opt.getOptionId() : null) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } + } else { + // TEXT, DATE, AUTO_FILL — prefer answerText, then answerDate, then optionValue (legacy) + String value = answer.getAnswerText() != null ? answer.getAnswerText() + : answer.getAnswerDate() != null ? answer.getAnswerDate() + : answer.getOptionValue(); + results.add(QuestionResponse.builder() + .sectionResponseId(sectionResponseId) + .questionId(questionId) + .answerText(value) + .createdBy(actor) + .updatedBy(actor) + .vanID(vanID) + .parkingPlaceID(parkingPlaceID) + .build()); + } + } + return results; + } + + private QuestionOption resolveOption(Map> optionsByQuestion, + Long questionId, String optionValue, String questionUuid) { + Map opts = optionsByQuestion.get(questionId); + if (opts == null || !opts.containsKey(optionValue)) { + log.warn("Option value '{}' not found for question '{}', storing null optionId", + optionValue, questionUuid); + return null; + } + return opts.get(optionValue); + } + + private FormResponseDTO buildFormResponseDTO(FormResponse r, List sections) { + return FormResponseDTO.builder() + .responseId(r.getResponseId()) + .beneficiaryId(r.getBeneficiaryId()) + .formId(r.getFormId()) + .versionId(r.getVersionId()) + .officerId(r.getOfficerId()) + .status(r.getStatus()) + .createdBy(r.getCreatedBy()) + .updatedBy(r.getUpdatedBy()) + .submittedAt(r.getSubmittedAt()) + .completedAt(r.getCompletedAt()) + .lastFollowUpAt(r.getLastFollowUpAt()) + .createdAt(r.getCreatedAt()) + .updatedAt(r.getUpdatedAt()) + .sections(sections) + .build(); + } + + private SectionResponseDTO buildSectionResponseDTO(SectionResponse sr, List answers) { + List answerDTOs = answers.stream() + .map(a -> QuestionResponseDTO.builder() + .questionResponseId(a.getQuestionResponseId()) + .questionId(a.getQuestionId()) + .optionId(a.getOptionId()) + .answerText(a.getAnswerText()) + .build()) + .collect(Collectors.toList()); + return SectionResponseDTO.builder() + .sectionResponseId(sr.getSectionResponseId()) + .sectionId(sr.getSectionId()) + .status(sr.getStatus()) + .savedAt(sr.getSavedAt()) + .answers(answerDTOs) + .build(); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java index f5ef4a092..ac4f74373 100644 --- a/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MalariaFollowUpServiceImpl.java @@ -51,6 +51,7 @@ public Boolean saveFollowUp(MalariaFollowUpDTO malariaFollowUpDTO,String token) dto.setUserId(jwtUtil.extractUserId(token)); MalariaFollowUp entity = new MalariaFollowUp(); BeanUtils.copyProperties(dto, entity); + entity.setModifiedBy(jwtUtil.extractUsername(token)); repository.save(entity); if(entity!=null){ incentiveLogicService.incentiveForMalariaFollowUp( @@ -76,6 +77,8 @@ public List getByUserId(Integer userId) { return repository.findByUserId(userId).stream().map(entity -> { MalariaFollowListUpDTO dto = new MalariaFollowListUpDTO(); BeanUtils.copyProperties(entity, dto); + dto.setUpdateDate(entity.getLastModDate()); + dto.setUpdatedBy(entity.getModifiedBy()); 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 41849ee3c..23973862a 100644 --- a/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/MaternalHealthServiceImpl.java @@ -216,6 +216,8 @@ public String saveANCVisit(List ancVisitDTOs, Integer userId) { benVisitDetail.setModifiedBy(it.getUpdatedBy()); benVisitDetail.setLastModDate(it.getUpdatedDate()); benVisitDetail.setProviderServiceMapID(it.getProviderServiceMapID()); + if (benVisitDetail.getCreatedDate() == null) + benVisitDetail.setCreatedDate(new java.sql.Timestamp(System.currentTimeMillis())); logger.info("Saving BenVisitDetail"); @@ -418,6 +420,8 @@ public String savePNCVisit(List pncVisitDTOs) { benVisitDetail.setProcessed("N"); benVisitDetail.setModifiedBy(it.getUpdatedBy()); benVisitDetail.setLastModDate(it.getUpdatedDate()); + if (benVisitDetail.getCreatedDate() == null) + benVisitDetail.setCreatedDate(new java.sql.Timestamp(System.currentTimeMillis())); benVisitDetail = benVisitDetailsRepo.save(benVisitDetail); // Saving Data in AncCare table diff --git a/src/main/java/com/iemr/flw/service/impl/StopTBServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/StopTBServiceImpl.java new file mode 100644 index 000000000..10016c4ac --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/StopTBServiceImpl.java @@ -0,0 +1,767 @@ +package com.iemr.flw.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarydetail; +import com.iemr.flw.domain.identity.RMNCHMBeneficiarymapping; +import com.iemr.flw.domain.iemr.BenAnthropometryDetail; +import com.iemr.flw.domain.iemr.BenChiefComplaint; +import com.iemr.flw.domain.iemr.BenFlowStatus; +import com.iemr.flw.domain.iemr.BenPhysicalVitalDetail; +import com.iemr.flw.domain.iemr.BenReferDetails; +import com.iemr.flw.domain.iemr.BenVisitDetail; +import com.iemr.flw.domain.iemr.PhyGeneralExamination; +import com.iemr.flw.domain.iemr.PrescribedDrugDetail; +import com.iemr.flw.domain.iemr.PrescriptionDetail; +import com.iemr.flw.domain.iemr.StopTBDiagnostics; +import com.iemr.flw.domain.iemr.StopTBGeneralExamination; +import com.iemr.flw.domain.iemr.StopTBGeneralOpd; +import com.iemr.flw.domain.iemr.TBScreening; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.BenAnthropometryRepo; +import com.iemr.flw.repo.iemr.BenChiefComplaintRepo; +import com.iemr.flw.repo.iemr.BenFlowStatusRepo; +import com.iemr.flw.repo.iemr.BenPhysicalVitalRepo; +import com.iemr.flw.repo.iemr.BenReferDetailsRepo; +import com.iemr.flw.repo.iemr.PhyGeneralExaminationRepo; +import com.iemr.flw.repo.iemr.PrescribedDrugDetailRepo; +import com.iemr.flw.repo.iemr.PrescriptionDetailRepo; +import com.iemr.flw.repo.iemr.StopTBDiagnosticsRepo; +import com.iemr.flw.repo.iemr.StopTBGeneralExaminationRepo; +import com.iemr.flw.repo.iemr.StopTBGeneralOpdRepo; +import com.iemr.flw.repo.iemr.TBScreeningRepo; +import com.iemr.flw.service.CampConfigService; +import com.iemr.flw.service.StopTBService; +import com.iemr.flw.service.TBStopVisitService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.*; + +@Service +public class StopTBServiceImpl implements StopTBService { + + private final Logger logger = LoggerFactory.getLogger(StopTBServiceImpl.class); + + @Autowired + private CampConfigService campConfigService; + + @Autowired + private BenFlowStatusRepo benFlowStatusRepo; + + @Autowired + private BeneficiaryRepo beneficiaryRepo; + + @Autowired + private StopTBGeneralExaminationRepo generalExaminationRepo; + + @Autowired + private TBScreeningRepo tbScreeningRepo; + + @Autowired + private StopTBGeneralOpdRepo generalOpdRepo; + + @Autowired + private StopTBDiagnosticsRepo diagnosticsRepo; + + @Autowired + private TBStopVisitService tbStopVisitService; + + @Autowired + private BenAnthropometryRepo benAnthropometryRepo; + + @Autowired + private BenPhysicalVitalRepo benPhysicalVitalRepo; + + @Autowired + private PhyGeneralExaminationRepo phyGeneralExaminationRepo; + + @Autowired + private BenChiefComplaintRepo benChiefComplaintRepo; + + @Autowired + private PrescriptionDetailRepo prescriptionDetailRepo; + + @Autowired + private PrescribedDrugDetailRepo prescribedDrugDetailRepo; + + @Autowired + private BenReferDetailsRepo benReferDetailsRepo; + + // ── Nurse: General Examination ──────────────────────────────────────────── + + @Override + @Transactional + public List> saveGeneralExamination(List> dataList) throws Exception { + List> results = new ArrayList<>(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + for (Map data : dataList) { + Long beneficiaryRegID = getLong(data, "beneficiaryRegID"); + if (beneficiaryRegID == null) throw new Exception("beneficiaryRegID is required"); + + Integer providerServiceMapID = getInt(data, "providerServiceMapID"); + String createdBy = getString(data, "createdBy"); + BenVisitDetail visit = tbStopVisitService.getOrCreateVisitForToday(beneficiaryRegID, providerServiceMapID, + createdBy, vanID, parkingPlaceID); + + StopTBGeneralExamination exam = generalExaminationRepo.findByBeneficiaryRegIDAndVisitCode(beneficiaryRegID, visit.getVisitCode()); + if (exam == null) exam = new StopTBGeneralExamination(); + boolean isNew = exam.getId() == null; + + exam.setBeneficiaryRegID(beneficiaryRegID); + exam.setVisitCode(visit.getVisitCode()); + exam.setBenVisitID(visit.getBenVisitId()); + exam.setProviderServiceMapID(providerServiceMapID); + exam.setPulseRate(getInt(data, "pulseRate")); + exam.setSystolicBP(getInt(data, "systolicBP")); + exam.setDiastolicBP(getInt(data, "diastolicBP")); + exam.setRandomBloodSugar(getDouble(data, "randomBloodSugar")); + exam.setPallorId(getInt(data, "pallorId")); + exam.setPallor(getString(data, "pallor")); + exam.setIcterusId(getInt(data, "icterusId")); + exam.setIcterus(getString(data, "icterus")); + exam.setLymphadenopathyId(getInt(data, "lymphadenopathyId")); + exam.setLymphadenopathy(getString(data, "lymphadenopathy")); + exam.setOedemaId(getInt(data, "oedemaId")); + exam.setOedema(getString(data, "oedema")); + exam.setCyanosisId(getInt(data, "cyanosisId")); + exam.setCyanosis(getString(data, "cyanosis")); + exam.setClubbingId(getInt(data, "clubbingId")); + exam.setClubbing(getString(data, "clubbing")); + exam.setKeyPopulationRiskFactorIds(toJsonString(data.get("keyPopulationRiskFactorIds"))); + exam.setKeyPopulationRiskFactors(toJsonString(data.get("keyPopulationRiskFactors"))); + exam.setHivStatusId(getInt(data, "hivStatusId")); + exam.setHivStatus(getString(data, "hivStatus")); + exam.setCreatedBy(getString(data, "createdBy")); + exam.setModifiedBy(getString(data, "createdBy")); + exam.setDeleted(false); + exam.setReferralToHWCNeeded(getBool(data, "referralToHWCNeeded")); + if (exam.getVanID() == null && vanID != null) { exam.setVanID(vanID); exam.setParkingPlaceID(parkingPlaceID); } + exam.setProcessed("N"); + + generalExaminationRepo.save(exam); + if (isNew) { + generalExaminationRepo.updateVanSerialNo(exam.getId()); + dualWriteExamToStandardTables(exam, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + } + + Map result = new HashMap<>(); + result.put("beneficiaryRegID", beneficiaryRegID); + result.put("referralToHWCNeeded", exam.getReferralToHWCNeeded()); + results.add(result); + } + return results; + } + + private boolean calculateReferralNeeded(StopTBGeneralExamination e) { + if (e.getPulseRate() != null && (e.getPulseRate() < 60 || e.getPulseRate() > 90)) return true; + if (e.getSystolicBP() != null && (e.getSystolicBP() >= 140 || e.getSystolicBP() < 90)) return true; + if (e.getDiastolicBP() != null && (e.getDiastolicBP() >= 90 || e.getDiastolicBP() < 60)) return true; + if (e.getRandomBloodSugar() != null && e.getRandomBloodSugar() >= 100) return true; + return false; + } + + @Override + public Map getAllGeneralExaminations(Integer providerServiceMapID, Integer villageID) throws Exception { + List list = (villageID != null) + ? generalExaminationRepo.findAllByProviderServiceMapIDAndVillageID(providerServiceMapID, villageID) + : generalExaminationRepo.findAllByProviderServiceMapID(providerServiceMapID); + List> items = new ArrayList<>(); + for (StopTBGeneralExamination e : list) items.add(examToMap(e)); + Map result = new HashMap<>(); + result.put("data", items); + result.put("count", items.size()); + return result; + } + + private Map examToMap(StopTBGeneralExamination e) { + Map m = new LinkedHashMap<>(); + m.put("id", e.getId()); + m.put("beneficiaryRegID", e.getBeneficiaryRegID()); + m.put("providerServiceMapID", e.getProviderServiceMapID()); + m.put("pulseRate", e.getPulseRate()); + m.put("systolicBP", e.getSystolicBP()); + m.put("diastolicBP", e.getDiastolicBP()); + m.put("randomBloodSugar", e.getRandomBloodSugar()); + m.put("pallorId", e.getPallorId()); + m.put("pallor", e.getPallor()); + m.put("icterusId", e.getIcterusId()); + m.put("icterus", e.getIcterus()); + m.put("lymphadenopathyId", e.getLymphadenopathyId()); + m.put("lymphadenopathy", e.getLymphadenopathy()); + m.put("oedemaId", e.getOedemaId()); + m.put("oedema", e.getOedema()); + m.put("cyanosisId", e.getCyanosisId()); + m.put("cyanosis", e.getCyanosis()); + m.put("clubbingId", e.getClubbingId()); + m.put("clubbing", e.getClubbing()); + m.put("keyPopulationRiskFactorIds", e.getKeyPopulationRiskFactorIds()); + m.put("keyPopulationRiskFactors", e.getKeyPopulationRiskFactors()); + m.put("hivStatusId", e.getHivStatusId()); + m.put("hivStatus", e.getHivStatus()); + m.put("referralToHWCNeeded", e.getReferralToHWCNeeded()); + m.put("createdBy", e.getCreatedBy()); + m.put("createdDate", e.getCreatedDate()); + m.put("updateDate", e.getLastModDate()); + m.put("updatedBy", e.getModifiedBy()); + return m; + } + + // ── Nurse: TB Screening ─────────────────────────────────────────────────── + + @Override + @Transactional + public List> saveNurseTBScreening(List> dataList) throws Exception { + List> results = new ArrayList<>(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + for (Map data : dataList) { + Long beneficiaryRegID = getLong(data, "beneficiaryRegID"); + if (beneficiaryRegID == null) throw new Exception("beneficiaryRegID is required"); + + Integer providerServiceMapID = getInt(data, "providerServiceMapID"); + String createdBy = getString(data, "createdBy"); + BenVisitDetail visit = tbStopVisitService.getOrCreateVisitForToday(beneficiaryRegID, providerServiceMapID, + createdBy, vanID, parkingPlaceID); + + TBScreening screening = tbScreeningRepo.findByBenRegIDAndVisitCode(beneficiaryRegID, visit.getVisitCode()); + if (screening == null) screening = new TBScreening(); + boolean isNew = screening.getId() == null; + + screening.setBenRegID(beneficiaryRegID); + screening.setVisitCode(visit.getVisitCode()); + screening.setProviderServiceMapID(providerServiceMapID); + screening.setCoughMoreThan2Weeks(getBool(data, "coughMoreThan2Weeks")); + screening.setBloodInSputum(getBool(data, "bloodInSputum")); + screening.setFeverMoreThan2Weeks(getBool(data, "feverMoreThan2Weeks")); + screening.setLossOfWeight(getBool(data, "lossOfWeight")); + screening.setNightSweats(getBool(data, "nightSweats")); + screening.setHistoryOfTb(getBool(data, "historyOfTb")); + screening.setTakingAntiTBDrugs(getBool(data, "takingAntiTBDrugs")); + screening.setFamilySufferingFromTB(getBool(data, "familySufferingFromTB")); + screening.setRiseOfFever(getBool(data, "riseOfFever")); + screening.setLossOfAppetite(getBool(data, "lossOfAppetite")); + screening.setContactWithTBPatient(getBool(data, "contactWithTBPatient")); + screening.setKeyPopulationRiskFactorIds(toJsonString(data.get("keyPopulationRiskFactorIds"))); + screening.setKeyPopulationRiskFactors(toJsonString(data.get("keyPopulationRiskFactors"))); + screening.setHivStatusId(getInt(data, "hivStatusId")); + screening.setHivStatus(getString(data, "hivStatus")); + String symptomaticInput = getString(data, "symptomatic"); + if ("Yes".equalsIgnoreCase(symptomaticInput)) { + screening.setSympotomatic(null); + screening.setAsymptomatic("Yes"); + } else if ("No".equalsIgnoreCase(symptomaticInput)) { + screening.setSympotomatic("Yes"); + screening.setAsymptomatic(null); + } else { + screening.setSympotomatic(null); + screening.setAsymptomatic(null); + } + screening.setReferredForDigitalChestXray(getBool(data, "referredForDigitalChestXray")); + screening.setReferredForSputumCollection(getBool(data, "referredForSputumCollection")); + screening.setSputumSampleSubmittedAt(getString(data, "sputumSampleSubmittedAt")); + screening.setRecommendedForTruenat(getBool(data, "recommendedForTruenat")); + screening.setRecommendedForLiquidCulture(getBool(data, "recommendedForLiquidCulture")); + screening.setTestDenialReasons(getString(data, "testDenialReasons")); + screening.setCreatedBy(getString(data, "createdBy")); + screening.setModifiedBy(getString(data, "createdBy")); + // PRD: date is user-provided, mandatory, not editable once submitted + if (screening.getVisitDate() == null) { + Timestamp provided = getTimestamp(data, "visitDate"); + screening.setVisitDate(provided != null ? provided : new Timestamp(System.currentTimeMillis())); + } + if (screening.getVanID() == null && vanID != null) { screening.setVanID(vanID); screening.setParkingPlaceID(parkingPlaceID); } + screening.setProcessed("N"); + + tbScreeningRepo.save(screening); + if (isNew) tbScreeningRepo.updateVanSerialNo(screening.getId()); + + Map result = new HashMap<>(); + result.put("beneficiaryRegID", beneficiaryRegID); + results.add(result); + } + return results; + } + + @Override + public Map getAllNurseTBScreenings(Integer providerServiceMapID, Integer villageID) throws Exception { + List list = (villageID != null) + ? tbScreeningRepo.findAllByProviderServiceMapIDAndVillageID(providerServiceMapID, villageID) + : tbScreeningRepo.findAllByProviderServiceMapID(providerServiceMapID); + List> items = new ArrayList<>(); + for (TBScreening s : list) items.add(screeningToMap(s)); + Map result = new HashMap<>(); + result.put("data", items); + result.put("count", items.size()); + return result; + } + + private Map screeningToMap(TBScreening s) { + Map m = new LinkedHashMap<>(); + m.put("id", s.getId()); + m.put("beneficiaryRegID", s.getBenRegID()); + m.put("providerServiceMapID", s.getProviderServiceMapID()); + m.put("coughMoreThan2Weeks", s.getCoughMoreThan2Weeks()); + m.put("bloodInSputum", s.getBloodInSputum()); + m.put("feverMoreThan2Weeks", s.getFeverMoreThan2Weeks()); + m.put("lossOfWeight", s.getLossOfWeight()); + m.put("nightSweats", s.getNightSweats()); + m.put("historyOfTb", s.getHistoryOfTb()); + m.put("takingAntiTBDrugs", s.getTakingAntiTBDrugs()); + m.put("familySufferingFromTB", s.getFamilySufferingFromTB()); + m.put("riseOfFever", s.getRiseOfFever()); + m.put("lossOfAppetite", s.getLossOfAppetite()); + m.put("contactWithTBPatient", s.getContactWithTBPatient()); + m.put("keyPopulationRiskFactorIds", s.getKeyPopulationRiskFactorIds()); + m.put("keyPopulationRiskFactors", s.getKeyPopulationRiskFactors()); + m.put("hivStatusId", s.getHivStatusId()); + m.put("hivStatus", s.getHivStatus()); + if ("Yes".equalsIgnoreCase(s.getAsymptomatic())) { + m.put("symptomatic", "Yes"); + } else if ("Yes".equalsIgnoreCase(s.getSympotomatic())) { + m.put("symptomatic", "No"); + } else { + m.put("symptomatic", null); + } + m.put("referredForDigitalChestXray", s.getReferredForDigitalChestXray()); + m.put("referredForSputumCollection", s.getReferredForSputumCollection()); + m.put("sputumSampleSubmittedAt", s.getSputumSampleSubmittedAt()); + m.put("recommendedForTruenat", s.getRecommendedForTruenat()); + m.put("recommendedForLiquidCulture", s.getRecommendedForLiquidCulture()); + m.put("testDenialReasons", s.getTestDenialReasons()); + m.put("createdBy", s.getCreatedBy()); + m.put("visitDate", s.getVisitDate()); + m.put("updateDate", s.getLastModDate()); + m.put("updatedBy", s.getModifiedBy()); + return m; + } + + // ── Nurse: General OPD ──────────────────────────────────────────────────── + + @Override + @Transactional + public List> saveGeneralOpd(List> dataList) throws Exception { + List> results = new ArrayList<>(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + for (Map data : dataList) { + Long beneficiaryRegID = getLong(data, "beneficiaryRegID"); + if (beneficiaryRegID == null) throw new Exception("beneficiaryRegID is required"); + + Integer providerServiceMapID = getInt(data, "providerServiceMapID"); + String createdBy = getString(data, "createdBy"); + BenVisitDetail visit = tbStopVisitService.getOrCreateVisitForToday(beneficiaryRegID, providerServiceMapID, + createdBy, vanID, parkingPlaceID); + + StopTBGeneralOpd opd = generalOpdRepo.findByBenRegIDAndVisitCode(beneficiaryRegID, visit.getVisitCode()); + if (opd == null) opd = new StopTBGeneralOpd(); + boolean isNew = opd.getId() == null; + + opd.setBenRegID(beneficiaryRegID); + opd.setVisitCode(visit.getVisitCode()); + opd.setBenVisitID(visit.getBenVisitId()); + opd.setProviderServiceMapID(providerServiceMapID); + opd.setChiefComplaint(toJsonString(data.get("chiefComplaint"))); + opd.setMedication(getString(data, "medication")); + opd.setDosage(getString(data, "dosage")); + opd.setFrequency(getString(data, "frequency")); + opd.setDuration(getString(data, "duration")); + opd.setNotes(getString(data, "notes")); + opd.setCreatedBy(getString(data, "createdBy")); + opd.setModifiedBy(getString(data, "createdBy")); + opd.setDeleted(false); + if (opd.getVanID() == null && vanID != null) { opd.setVanID(vanID); opd.setParkingPlaceID(parkingPlaceID); } + opd.setProcessed("N"); + + generalOpdRepo.save(opd); + if (isNew) { + generalOpdRepo.updateVanSerialNo(opd.getId()); + dualWriteOpdToStandardTables(opd, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + } + + Map result = new HashMap<>(); + result.put("beneficiaryRegID", beneficiaryRegID); + results.add(result); + } + return results; + } + + @Override + public Map getAllGeneralOpd(Integer providerServiceMapID, Integer villageID) throws Exception { + List list = (villageID != null) + ? generalOpdRepo.findAllByProviderServiceMapIDAndVillageID(providerServiceMapID, villageID) + : generalOpdRepo.findAllByProviderServiceMapID(providerServiceMapID); + List> items = new ArrayList<>(); + for (StopTBGeneralOpd o : list) items.add(opdToMap(o)); + Map result = new HashMap<>(); + result.put("data", items); + result.put("count", items.size()); + return result; + } + + private Map opdToMap(StopTBGeneralOpd o) { + Map m = new LinkedHashMap<>(); + m.put("id", o.getId()); + m.put("beneficiaryRegID", o.getBenRegID()); + m.put("providerServiceMapID", o.getProviderServiceMapID()); + m.put("chiefComplaint", o.getChiefComplaint()); + m.put("medication", o.getMedication()); + m.put("dosage", o.getDosage()); + m.put("frequency", o.getFrequency()); + m.put("duration", o.getDuration()); + m.put("notes", o.getNotes()); + m.put("createdBy", o.getCreatedBy()); + m.put("createdDate", o.getCreatedDate()); + m.put("updateDate", o.getLastModDate()); + m.put("updatedBy", o.getModifiedBy()); + return m; + } + + // ── Nurse: Diagnostics ──────────────────────────────────────────────────── + + @Override + @Transactional + public List> saveDiagnostics(List> dataList) throws Exception { + List> results = new ArrayList<>(); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + for (Map data : dataList) { + Long benRegID = getLong(data, "benRegID"); + if (benRegID == null) throw new Exception("benRegID is required"); + + StopTBDiagnostics diag = diagnosticsRepo.findByBenRegID(benRegID); + if (diag == null) diag = new StopTBDiagnostics(); + boolean isNew = diag.getId() == null; + + diag.setBenRegID(benRegID); + diag.setProviderServiceMapID(getInt(data, "providerServiceMapID")); + + // PRD: date is user-provided, not editable once submitted + if (diag.getVisitDate() == null) { + Timestamp provided = getTimestamp(data, "visitDate"); + diag.setVisitDate(provided != null ? provided : new Timestamp(System.currentTimeMillis())); + } + + diag.setNikshayId(getString(data, "nikshayId")); + + diag.setIsReferredForDigitalChestXray(getBool(data, "isReferredForDigitalChestXray")); + diag.setReasonForDenialChestXray(getString(data, "reasonForDenialChestXray")); + diag.setReasonForDenialChestXrayOther(getString(data, "reasonForDenialChestXrayOther")); + diag.setIsDigitalChestXrayConducted(getBool(data, "isDigitalChestXrayConducted")); + diag.setReasonNotConductedChestXray(getString(data, "reasonNotConductedChestXray")); + diag.setReasonNotConductedChestXrayOther(getString(data, "reasonNotConductedChestXrayOther")); + diag.setDigitalChestXrayResult(getString(data, "digitalChestXrayResult")); + + diag.setIsReferredForSputumCollection(getBool(data, "isReferredForSputumCollection")); + diag.setReasonForDenialSputum(getString(data, "reasonForDenialSputum")); + diag.setReasonForDenialSputumOther(getString(data, "reasonForDenialSputumOther")); + diag.setSputumSubmittedAt(getString(data, "sputumSubmittedAt")); + + diag.setIsTruenatConducted(getBool(data, "isTruenatConducted")); + diag.setReasonNotConductedNaat(getString(data, "reasonNotConductedNaat")); + diag.setReasonNotConductedNaatOther(getString(data, "reasonNotConductedNaatOther")); + diag.setTruenatResult(getString(data, "truenatResult")); + + diag.setRecommendedForLiquidCulture(getBool(data, "recommendedForLiquidCulture")); + // PRD: liquid culture result can be updated after submission (results come after 40-45 days) + if (data.containsKey("liquidCultureResult")) { + diag.setLiquidCultureResult(getString(data, "liquidCultureResult")); + } + diag.setCreatedBy(getString(data, "createdBy")); + diag.setModifiedBy(getString(data, "createdBy")); + diag.setDeleted(false); + if (diag.getVanID() == null && vanID != null) { diag.setVanID(vanID); diag.setParkingPlaceID(parkingPlaceID); } + diag.setProcessed("N"); + + diagnosticsRepo.save(diag); + if (isNew) diagnosticsRepo.updateVanSerialNo(diag.getId()); + + Map result = new HashMap<>(); + result.put("benRegID", benRegID); + results.add(result); + } + return results; + } + + @Override + public Map getAllDiagnostics(Integer providerServiceMapID, Integer villageID) throws Exception { + List list = (villageID != null) + ? diagnosticsRepo.findAllByProviderServiceMapIDAndVillageID(providerServiceMapID, villageID) + : diagnosticsRepo.findAllByProviderServiceMapID(providerServiceMapID); + List> items = new ArrayList<>(); + for (StopTBDiagnostics d : list) items.add(diagnosticsToMap(d)); + Map result = new HashMap<>(); + result.put("data", items); + result.put("count", items.size()); + return result; + } + + private Map diagnosticsToMap(StopTBDiagnostics d) { + Map m = new LinkedHashMap<>(); + m.put("id", d.getId()); + m.put("benRegID", d.getBenRegID()); + m.put("providerServiceMapID", d.getProviderServiceMapID()); + m.put("visitDate", d.getVisitDate()); + m.put("nikshayId", d.getNikshayId()); + m.put("isReferredForDigitalChestXray", d.getIsReferredForDigitalChestXray()); + m.put("reasonForDenialChestXray", d.getReasonForDenialChestXray()); + m.put("reasonForDenialChestXrayOther", d.getReasonForDenialChestXrayOther()); + m.put("isDigitalChestXrayConducted", d.getIsDigitalChestXrayConducted()); + m.put("reasonNotConductedChestXray", d.getReasonNotConductedChestXray()); + m.put("reasonNotConductedChestXrayOther", d.getReasonNotConductedChestXrayOther()); + m.put("digitalChestXrayResult", d.getDigitalChestXrayResult()); + m.put("isReferredForSputumCollection", d.getIsReferredForSputumCollection()); + m.put("reasonForDenialSputum", d.getReasonForDenialSputum()); + m.put("reasonForDenialSputumOther", d.getReasonForDenialSputumOther()); + m.put("sputumSubmittedAt", d.getSputumSubmittedAt()); + m.put("isTruenatConducted", d.getIsTruenatConducted()); + m.put("reasonNotConductedNaat", d.getReasonNotConductedNaat()); + m.put("reasonNotConductedNaatOther", d.getReasonNotConductedNaatOther()); + m.put("truenatResult", d.getTruenatResult()); + m.put("recommendedForLiquidCulture", d.getRecommendedForLiquidCulture()); + m.put("liquidCultureResult", d.getLiquidCultureResult()); + m.put("createdBy", d.getCreatedBy()); + m.put("createdDate", d.getCreatedDate()); + m.put("updateDate", d.getLastModDate()); + m.put("updatedBy", d.getModifiedBy()); + return m; + } + + // ── Standard table dual-writes ──────────────────────────────────────────── + + private Map getRegistrationExtras(Long beneficiaryRegID) { + try { + RMNCHMBeneficiarymapping mapping = beneficiaryRepo.getById(BigInteger.valueOf(beneficiaryRegID)); + RMNCHMBeneficiarydetail detail = (mapping != null && mapping.getBenDetailsId() != null) + ? beneficiaryRepo.getDetailsById(mapping.getBenDetailsId()) + : null; + if (detail != null && detail.getOtherFields() != null && !detail.getOtherFields().isEmpty()) { + return new ObjectMapper().readValue(detail.getOtherFields(), Map.class); + } + } catch (Exception e) { + logger.warn("Cannot read otherFields for benRegID: " + beneficiaryRegID); + } + return Collections.emptyMap(); + } + + private void dualWriteExamToStandardTables(StopTBGeneralExamination exam, Long beneficiaryRegID, + BenVisitDetail visit, String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + Map extras = getRegistrationExtras(beneficiaryRegID); + writeAnthropometry(extras, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + writeVitals(exam, extras, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + writePhyGeneralExam(exam, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + if (Boolean.TRUE.equals(exam.getReferralToHWCNeeded())) { + writeReferral(beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + } + } catch (Exception e) { + logger.error("Dual-write exam to standard tables failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writeAnthropometry(Map extras, Long beneficiaryRegID, + BenVisitDetail visit, String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + BenAnthropometryDetail a = new BenAnthropometryDetail(); + a.setBeneficiaryRegID(beneficiaryRegID); + a.setBenVisitID(visit.getBenVisitId()); + a.setVisitCode(visit.getVisitCode()); + a.setProviderServiceMapID(visit.getProviderServiceMapID()); + a.setCreatedBy(createdBy); + a.setVanID(vanID); + a.setParkingPlaceID(parkingPlaceID); + Object h = extras.get("height"); + Object w = extras.get("weight"); + Object b = extras.get("bmi"); + if (h instanceof Number) a.setHeightCm(((Number) h).doubleValue()); + if (w instanceof Number) a.setWeightKg(((Number) w).doubleValue()); + if (b instanceof Number) a.setBmi(((Number) b).doubleValue()); + benAnthropometryRepo.save(a); + } catch (Exception e) { + logger.error("writeAnthropometry failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writeVitals(StopTBGeneralExamination exam, Map extras, + Long beneficiaryRegID, BenVisitDetail visit, String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + BenPhysicalVitalDetail v = new BenPhysicalVitalDetail(); + v.setBeneficiaryRegID(beneficiaryRegID); + v.setBenVisitID(visit.getBenVisitId()); + v.setVisitCode(visit.getVisitCode()); + v.setProviderServiceMapID(visit.getProviderServiceMapID()); + v.setCreatedBy(createdBy); + v.setVanID(vanID); + v.setParkingPlaceID(parkingPlaceID); + Object t = extras.get("temperatureValue"); + if (t instanceof Number) v.setTemperature(((Number) t).doubleValue()); + if (exam.getPulseRate() != null) v.setPulseRate(exam.getPulseRate().shortValue()); + if (exam.getSystolicBP() != null) v.setSystolicBP(exam.getSystolicBP().shortValue()); + if (exam.getDiastolicBP() != null) v.setDiastolicBP(exam.getDiastolicBP().shortValue()); + if (exam.getRandomBloodSugar() != null) v.setBloodGlucoseRandom(exam.getRandomBloodSugar().shortValue()); + benPhysicalVitalRepo.save(v); + } catch (Exception e) { + logger.error("writeVitals failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writePhyGeneralExam(StopTBGeneralExamination exam, Long beneficiaryRegID, + BenVisitDetail visit, String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + PhyGeneralExamination g = new PhyGeneralExamination(); + g.setBeneficiaryRegID(beneficiaryRegID); + g.setBenVisitID(visit.getBenVisitId()); + g.setVisitCode(visit.getVisitCode()); + g.setProviderServiceMapID(visit.getProviderServiceMapID()); + g.setCreatedBy(createdBy); + g.setVanID(vanID); + g.setParkingPlaceID(parkingPlaceID); + g.setPallor(exam.getPallor()); + g.setJaundice(exam.getIcterus()); + g.setCyanosis(exam.getCyanosis()); + g.setClubbing(exam.getClubbing()); + g.setLymphadenopathy(exam.getLymphadenopathy()); + g.setEdema(exam.getOedema()); + phyGeneralExaminationRepo.save(g); + } catch (Exception e) { + logger.error("writePhyGeneralExam failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writeReferral(Long beneficiaryRegID, BenVisitDetail visit, + String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + BenReferDetails r = new BenReferDetails(); + r.setBeneficiaryRegID(beneficiaryRegID); + r.setBenVisitID(visit.getBenVisitId()); + r.setVisitCode(visit.getVisitCode()); + r.setProviderServiceMapID(visit.getProviderServiceMapID()); + r.setCreatedBy(createdBy); + r.setVanID(vanID); + r.setParkingPlaceID(parkingPlaceID); + r.setReferredToInstituteName("HWC"); + r.setReferralReason("Stop TB Referral"); + benReferDetailsRepo.save(r); + } catch (Exception e) { + logger.error("writeReferral failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void dualWriteOpdToStandardTables(StopTBGeneralOpd opd, Long beneficiaryRegID, + BenVisitDetail visit, String createdBy, Integer vanID, Integer parkingPlaceID) { + try { + writeChiefComplaint(opd.getChiefComplaint(), beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + writePrescription(opd, beneficiaryRegID, visit, createdBy, vanID, parkingPlaceID); + } catch (Exception e) { + logger.error("Dual-write OPD to standard tables failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writeChiefComplaint(String complaint, Long beneficiaryRegID, BenVisitDetail visit, + String createdBy, Integer vanID, Integer parkingPlaceID) { + if (complaint == null || complaint.isBlank()) return; + try { + BenChiefComplaint c = new BenChiefComplaint(); + c.setBeneficiaryRegID(beneficiaryRegID); + c.setBenVisitID(visit.getBenVisitId()); + c.setVisitCode(visit.getVisitCode()); + c.setProviderServiceMapID(visit.getProviderServiceMapID()); + c.setCreatedBy(createdBy); + c.setVanID(vanID); + c.setParkingPlaceID(parkingPlaceID); + c.setChiefComplaint(complaint); + benChiefComplaintRepo.save(c); + } catch (Exception e) { + logger.error("writeChiefComplaint failed for benRegID: " + beneficiaryRegID, e); + } + } + + private void writePrescription(StopTBGeneralOpd opd, Long beneficiaryRegID, BenVisitDetail visit, + String createdBy, Integer vanID, Integer parkingPlaceID) { + if (opd.getMedication() == null || opd.getMedication().isBlank()) return; + try { + PrescriptionDetail p = new PrescriptionDetail(); + p.setBeneficiaryRegID(beneficiaryRegID); + p.setBenVisitID(visit.getBenVisitId()); + p.setVisitCode(visit.getVisitCode()); + p.setProviderServiceMapID(visit.getProviderServiceMapID()); + p.setCreatedBy(createdBy); + p.setVanID(vanID); + p.setParkingPlaceID(parkingPlaceID); + p.setInstruction(opd.getNotes()); + p = prescriptionDetailRepo.save(p); + + PrescribedDrugDetail d = new PrescribedDrugDetail(); + d.setBeneficiaryRegID(beneficiaryRegID); + d.setBenVisitID(visit.getBenVisitId()); + d.setVisitCode(visit.getVisitCode()); + d.setProviderServiceMapID(visit.getProviderServiceMapID()); + d.setCreatedBy(createdBy); + d.setVanID(vanID); + d.setParkingPlaceID(parkingPlaceID); + d.setPrescriptionID(p.getPrescriptionID()); + d.setDrugName(opd.getMedication()); + d.setDose(opd.getDosage()); + d.setFrequency(opd.getFrequency()); + d.setDuration(opd.getDuration()); + prescribedDrugDetailRepo.save(d); + } catch (Exception e) { + logger.error("writePrescription failed for benRegID: " + beneficiaryRegID, e); + } + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + private String toJsonString(Object value) { + if (value == null) return null; + if (value instanceof String) return (String) value; + return new com.google.gson.Gson().toJson(value); + } + + private String getString(Map m, String key) { + Object v = m.get(key); + return v != null ? v.toString() : null; + } + + private Long getLong(Map m, String key) { + Object v = m.get(key); + if (v == null) return null; + if (v instanceof Number) return ((Number) v).longValue(); + try { return Long.parseLong(v.toString()); } catch (Exception e) { return null; } + } + + private Integer getInt(Map m, String key) { + Object v = m.get(key); + if (v == null) return null; + if (v instanceof Number) return ((Number) v).intValue(); + try { return Integer.parseInt(v.toString()); } catch (Exception e) { return null; } + } + + private Double getDouble(Map m, String key) { + Object v = m.get(key); + if (v == null) return null; + if (v instanceof Number) return ((Number) v).doubleValue(); + try { return Double.parseDouble(v.toString()); } catch (Exception e) { return null; } + } + + private Boolean getBool(Map m, String key) { + Object v = m.get(key); + if (v == null) return null; + if (v instanceof Boolean) return (Boolean) v; + return Boolean.parseBoolean(v.toString()); + } + + private Timestamp getTimestamp(Map m, String key) { + Object v = m.get(key); + if (v == null) return null; + if (v instanceof Number) return new Timestamp(((Number) v).longValue()); + try { return new Timestamp(Long.parseLong(v.toString())); } catch (Exception e) { return null; } + } + +} diff --git a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java index e89928def..f9240c5ca 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBConfirmedCaseServiceImpl.java @@ -2,12 +2,20 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.iemr.DynamicForm; import com.iemr.flw.domain.iemr.TBConfirmedCaseDTO; import com.iemr.flw.domain.iemr.TBConfirmedCase; +import com.iemr.flw.domain.iemr.BenVisitDetail; import com.iemr.flw.dto.iemr.TBConfirmedCasesResponseDTO; +import com.iemr.flw.repo.identity.BeneficiaryRepo; +import com.iemr.flw.repo.iemr.DynamicFormRepo; +import com.iemr.flw.repo.iemr.FormResponseRepo; import com.iemr.flw.repo.iemr.TBConfirmedTreatmentRepository; +import com.iemr.flw.seeder.TbCounsellingFormSeeder; import com.iemr.flw.service.IncentiveLogicService; +import com.iemr.flw.service.CampConfigService; import com.iemr.flw.service.TBConfirmedCaseService; +import com.iemr.flw.service.TBStopVisitService; import com.iemr.flw.utils.JwtUtil; import com.iemr.flw.utils.LocalDateAdapter; import com.iemr.flw.utils.response.OutputResponse; @@ -18,7 +26,12 @@ import java.sql.Timestamp; import java.time.LocalDate; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; @Service @@ -27,6 +40,8 @@ public class TBConfirmedCaseServiceImpl implements TBConfirmedCaseService { private static final Logger logger = LoggerFactory.getLogger(TBConfirmedCaseServiceImpl.class); private final TBConfirmedTreatmentRepository repository; + private final FormResponseRepo formResponseRepo; + private final DynamicFormRepo dynamicFormRepo; @Autowired private IncentiveLogicService incentiveLogicService; @@ -34,8 +49,22 @@ public class TBConfirmedCaseServiceImpl implements TBConfirmedCaseService { @Autowired private JwtUtil jwtUtil; - public TBConfirmedCaseServiceImpl(TBConfirmedTreatmentRepository repository) { + + @Autowired + private CampConfigService campConfigService; + + @Autowired + private TBStopVisitService tbStopVisitService; + + @Autowired + private BeneficiaryRepo beneficiaryRepo; + + public TBConfirmedCaseServiceImpl(TBConfirmedTreatmentRepository repository, + FormResponseRepo formResponseRepo, + DynamicFormRepo dynamicFormRepo) { this.repository = repository; + this.formResponseRepo = formResponseRepo; + this.dynamicFormRepo = dynamicFormRepo; } @Override @@ -45,11 +74,22 @@ public String save(List request, String authorisation) throw try { if (request != null) { logger.info("Saving TB confirmed case: " + request); + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); - TBConfirmedCase entity = new TBConfirmedCase(); for(TBConfirmedCaseDTO dto:request){ + String modifiedBy = jwtUtil.extractUsername(authorisation); + Long beneficiaryRegID = beneficiaryRepo.getRegIDFromBenId(dto.getBenId()); + BenVisitDetail visit = tbStopVisitService.getOrCreateVisitForToday(beneficiaryRegID, null, + modifiedBy, vanID, parkingPlaceID); + + List existing = repository.findByBenIdAndVisitCode(dto.getBenId(), visit.getVisitCode()); + boolean isNew = existing.isEmpty(); + TBConfirmedCase entity = isNew ? new TBConfirmedCase() : existing.get(0); entity.setBenId(dto.getBenId()); + entity.setVisitCode(visit.getVisitCode()); entity.setUserId(jwtUtil.extractUserId(authorisation)); + entity.setModifiedBy(modifiedBy); entity.setRegimenType(dto.getRegimenType()); entity.setTreatmentStartDate(dto.getTreatmentStartDate()); entity.setExpectedTreatmentCompletionDate(dto.getExpectedTreatmentCompletionDate()); @@ -64,10 +104,12 @@ public String save(List request, String authorisation) throw entity.setPlaceOfDeath(dto.getPlaceOfDeath()); entity.setReasonForDeath(dto.getReasonForDeath()); entity.setReasonForNotCompleting(dto.getReasonForNotCompleting()); + if (entity.getVanID() == null && vanID != null) { entity.setVanID(vanID); entity.setParkingPlaceID(parkingPlaceID); } + entity.setProcessed("N"); if(entity!=null){ - repository.save(entity); + TBConfirmedCase saved = repository.save(entity); + if (isNew) repository.updateVanSerialNo(saved.getId()); checkIncentive(entity); - } } @@ -144,22 +186,46 @@ public String getByBenId(Long benId, String authorisation) throws Exception { @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); + return buildTbConfirmedCasesResponse(userId, list); + } + + @Override + public String getByProviderServiceMapId(Integer providerServiceMapID, Integer villageID) throws Exception { + List list = repository.getByProviderServiceMapIdAndVillageId(providerServiceMapID, villageID); + return buildTbConfirmedCasesResponse(null, list); + } + + private String buildTbConfirmedCasesResponse(Integer userId, List list) { + List dtoList = list.stream().map(this::toDTO).collect(Collectors.toList()); + + List benIds = dtoList.stream().map(TBConfirmedCaseDTO::getBenId).collect(Collectors.toList()); + Set counselledBenIds = Collections.emptySet(); + if (!benIds.isEmpty()) { + Optional counsellingForm = dynamicFormRepo.findByFormUuid(TbCounsellingFormSeeder.FORM_UUID); + if (counsellingForm.isPresent()) { + counselledBenIds = new HashSet<>(formResponseRepo.findCounselledBenIds(benIds, counsellingForm.get().getFormId(), "COMPLETE")); + } + } + final Set counselled = counselledBenIds; + dtoList.forEach(dto -> dto.setCounselled(counselled.contains(dto.getBenId()))); + + Map response = new java.util.HashMap<>(); + response.put("userId", userId); + response.put("tbConfirmedCases", dtoList); Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) + .setDateFormat("MMM dd, yyyy h:mm:ss a") .create(); - - return gson.toJson(tbConfirmedCasesResponseDTO); + return gson.toJson(response); } // Utility: convert entity -> DTO private TBConfirmedCaseDTO toDTO(TBConfirmedCase entity) { TBConfirmedCaseDTO dto = new TBConfirmedCaseDTO(); + dto.setId(entity.getId()); dto.setBenId(entity.getBenId()); dto.setUserId(entity.getUserId()); dto.setRegimenType(entity.getRegimenType()); @@ -176,6 +242,8 @@ private TBConfirmedCaseDTO toDTO(TBConfirmedCase entity) { dto.setPlaceOfDeath(entity.getPlaceOfDeath()); dto.setReasonForDeath(entity.getReasonForDeath()); dto.setReasonForNotCompleting(entity.getReasonForNotCompleting()); + dto.setUpdateDate(entity.getLastModDate()); + dto.setUpdatedBy(entity.getModifiedBy()); return dto; } diff --git a/src/main/java/com/iemr/flw/service/impl/TBStopVisitServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBStopVisitServiceImpl.java new file mode 100644 index 000000000..4f36b8b4c --- /dev/null +++ b/src/main/java/com/iemr/flw/service/impl/TBStopVisitServiceImpl.java @@ -0,0 +1,61 @@ +package com.iemr.flw.service.impl; + +import com.iemr.flw.domain.iemr.BenVisitDetail; +import com.iemr.flw.repo.iemr.BenVisitDetailsRepo; +import com.iemr.flw.service.TBStopVisitService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Timestamp; +import java.time.LocalDate; + +@Service +public class TBStopVisitServiceImpl implements TBStopVisitService { + + @Autowired + private BenVisitDetailsRepo benVisitDetailsRepo; + + @Override + @Transactional + public BenVisitDetail getOrCreateVisitForToday(Long beneficiaryRegID, Integer providerServiceMapID, + String createdBy, Integer vanID, Integer parkingPlaceID) { + LocalDate today = LocalDate.now(); + Timestamp dayStart = Timestamp.valueOf(today.atStartOfDay()); + Timestamp dayEnd = Timestamp.valueOf(today.plusDays(1).atStartOfDay()); + + BenVisitDetail existing = benVisitDetailsRepo.findStopTBVisitForToday(beneficiaryRegID, dayStart, dayEnd); + if (existing != null) return existing; + + Integer visitCount = benVisitDetailsRepo.countStopTBVisits(beneficiaryRegID); + short visitNo = (short) ((visitCount != null ? visitCount : 0) + 1); + + BenVisitDetail visit = new BenVisitDetail(); + visit.setBeneficiaryRegId(beneficiaryRegID); + visit.setVisitNo(visitNo); + visit.setVisitCategory("Stop TB"); + visit.setVisitReason("Screening"); + visit.setVisitDateTime(new Timestamp(System.currentTimeMillis())); + visit.setProviderServiceMapID(providerServiceMapID); + visit.setCreatedBy(createdBy); + visit.setCreatedDate(new Timestamp(System.currentTimeMillis())); + visit.setVanId(vanID); + visit.setParkingPlaceId(parkingPlaceID); + visit.setDeleted(false); + visit.setProcessed("N"); + visit = benVisitDetailsRepo.save(visit); + + // VisitCode: sessionID(1) + vanID(5-digit) + benVisitId(8-digit) — MMU formula + long visitCode = generateVisitCode(visit.getBenVisitId(), vanID != null ? vanID : 1); + visit.setVisitCode(visitCode); + // saveAndFlush ensures the VisitCode UPDATE reaches DB before child tables (e.g. t_benchiefcomplaint) + // insert with FK on VisitCode — same transaction, lazy flush otherwise causes FK violation + return benVisitDetailsRepo.saveAndFlush(visit); + } + + private long generateVisitCode(long visitId, int vanID) { + String vanStr = String.format("%05d", vanID); + String visitStr = String.format("%08d", visitId); + return Long.parseLong("1" + vanStr + visitStr); + } +} diff --git a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java index 2a8c0eeb0..cc0abdd0c 100644 --- a/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/TBSuspectedServiceImpl.java @@ -2,12 +2,16 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.iemr.flw.domain.iemr.BenVisitDetail; import com.iemr.flw.domain.iemr.TBSuspected; import com.iemr.flw.dto.identity.GetBenRequestHandler; import com.iemr.flw.dto.iemr.TBSuspectedDTO; import com.iemr.flw.dto.iemr.TBSuspectedRequestDTO; +import com.iemr.flw.repo.identity.BeneficiaryRepo; import com.iemr.flw.repo.iemr.TBSuspectedRepo; import com.iemr.flw.service.IncentiveLogicService; +import com.iemr.flw.service.CampConfigService; +import com.iemr.flw.service.TBStopVisitService; import com.iemr.flw.service.TBSuspectedService; import org.modelmapper.ModelMapper; import org.slf4j.Logger; @@ -25,6 +29,12 @@ public class TBSuspectedServiceImpl implements TBSuspectedService { private final ModelMapper modelMapper = new ModelMapper(); @Autowired private TBSuspectedRepo tbSuspectedRepo; + @Autowired + private CampConfigService campConfigService; + @Autowired + private TBStopVisitService tbStopVisitService; + @Autowired + private BeneficiaryRepo beneficiaryRepo; @Autowired private IncentiveLogicService incentiveLogicService; @@ -36,10 +46,15 @@ public String getByBenId(Long benId, String authorisation) throws Exception { @Override public String save(TBSuspectedRequestDTO requestDTO) throws Exception { - requestDTO.getTbSuspectedList().forEach(tbSuspectedDTO -> - { + Integer vanID = campConfigService.getVanID(); + Integer parkingPlaceID = campConfigService.getParkingPlaceID(); + for (TBSuspectedDTO tbSuspectedDTO : requestDTO.getTbSuspectedList()) { + Long beneficiaryRegID = beneficiaryRepo.getRegIDFromBenId(tbSuspectedDTO.getBenId()); + BenVisitDetail visit = tbStopVisitService.getOrCreateVisitForToday(beneficiaryRegID, null, + requestDTO.getUserId() != null ? requestDTO.getUserId().toString() : null, vanID, parkingPlaceID); + TBSuspected tbSuspected = - tbSuspectedRepo.getByUserIdAndBenId(tbSuspectedDTO.getBenId(), requestDTO.getUserId()); + tbSuspectedRepo.getByUserIdAndBenIdAndVisitCode(tbSuspectedDTO.getBenId(), requestDTO.getUserId(), visit.getVisitCode()); if (tbSuspected == null) { tbSuspected = new TBSuspected(); @@ -52,7 +67,11 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { } tbSuspected.setUserId(requestDTO.getUserId()); + tbSuspected.setVisitCode(visit.getVisitCode()); + if (tbSuspected.getVanID() == null && vanID != null) { tbSuspected.setVanID(vanID); tbSuspected.setParkingPlaceID(parkingPlaceID); } + tbSuspected.setProcessed("N"); tbSuspectedRepo.save(tbSuspected); + tbSuspectedRepo.updateVanSerialNo(tbSuspected.getId()); if(tbSuspected!=null){ if(tbSuspected.getIsConfirmed()){ incentiveLogicService.incentiveForTbSuspected(tbSuspected.getBenId(),tbSuspected.getVisitDate(),tbSuspected.getVisitDate(),tbSuspected.getUserId()); @@ -60,17 +79,21 @@ public String save(TBSuspectedRequestDTO requestDTO) throws Exception { } } - - }); + } return "no of tb suspected items saved:" + requestDTO.getTbSuspectedList().size(); } @Override public String getByUserId(GetBenRequestHandler request) { List dtos = new ArrayList<>(); - List tbSuspectedList = tbSuspectedRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); - tbSuspectedList.forEach(tbSuspected -> { - dtos.add(modelMapper.map(tbSuspected, TBSuspectedDTO.class)); + List tbSuspectedList = request.getProviderServiceMapID() != null + ? tbSuspectedRepo.getByProviderServiceMapIdAndVillageId(request.getProviderServiceMapID(), request.getVillageID()) + : tbSuspectedRepo.getByUserId(request.getAshaId(), request.getFromDate(), request.getToDate()); + for (TBSuspected tbSuspected : tbSuspectedList) { + TBSuspectedDTO dto = modelMapper.map(tbSuspected, TBSuspectedDTO.class); + dto.setUpdateDate(tbSuspected.getLastModDate()); + dto.setUpdatedBy(tbSuspected.getModifiedBy()); + dtos.add(dto); if (tbSuspected != null && Boolean.TRUE.equals(tbSuspected.getIsConfirmed())) { incentiveLogicService.incentiveForTbSuspected( @@ -80,7 +103,7 @@ public String getByUserId(GetBenRequestHandler request) { tbSuspected.getUserId() ); } - }); + } TBSuspectedRequestDTO tbSuspectedRequestDTO = new TBSuspectedRequestDTO(); tbSuspectedRequestDTO.setTbSuspectedList(dtos); tbSuspectedRequestDTO.setUserId(request.getAshaId()); diff --git a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java index 60ae973e7..e0e5b76bd 100644 --- a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java @@ -23,6 +23,16 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { logger.info("calling getUserRole for userId: " + userId); UserServiceRoleDTO userRole = userServiceRoleRepo.getUserRole(userId).get(0); userRole.setFacilityData(facilityDataService.buildFacilityData(userId, userRole.getRoleName())); + if (userRole.getWorkingDistrictId() == null && userRole.getBlockId() != null) { + java.util.List districtResults = userServiceRoleRepo.getDistrictByBlockId(userRole.getBlockId()); + if (districtResults != null && !districtResults.isEmpty()) { + Object[] district = districtResults.get(0); + if (district != null && district.length == 2) { + userRole.setWorkingDistrictId(((Number) district[0]).intValue()); + userRole.setWorkingDistrictName((String) district[1]); + } + } + } return userRole; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 034fbcc4a..84cca4815 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -62,7 +62,7 @@ spring.jpa.defer-datasource-initialization=true fhir-url= # TM Config -tm-url= +tm-url=https://amritdemo.piramalswasthya.org/tm-api springdoc.api-docs.enabled=true springdoc.swagger-ui.enabled=true From f9fb50ffc2f7a8cae55e4bb75312a49a1ba5f2f3 Mon Sep 17 00:00:00 2001 From: vishwab1 Date: Tue, 28 Jul 2026 11:37:47 +0530 Subject: [PATCH 449/450] fix(nikshay): add Stop TB TU/Facility/District scope to getUserDetail release-3.8.2 predates the Nikshay TU/Facility/Village work done on release-3.8.3, so getUserDetail had no way to tell Stop TB users apart and was patching their district from the wrong source (BlockId holds a Nikshay TU ID for Stop TB, not an AMRIT BlockID). Ports the getUserDetail-side fix from vb/release-3.8.3-nikshay-fix onto 3.8.2 as an additive change, keeping the existing facilityData/ FacilityDataService wiring intact for every other service line. Co-Authored-By: Claude Sonnet 5 --- .../iemr/flw/dto/iemr/UserServiceRoleDTO.java | 8 ++++ .../flw/repo/iemr/UserServiceRoleRepo.java | 32 ++++++++++++++++ .../flw/service/impl/UserServiceImpl.java | 37 ++++++++++++++++++- 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java b/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java index ead3ddc06..c336e1c98 100644 --- a/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java +++ b/src/main/java/com/iemr/flw/dto/iemr/UserServiceRoleDTO.java @@ -27,6 +27,14 @@ public class UserServiceRoleDTO { private String villageName; private Map facilityData; + // Stop TB / Nikshay location scope — populated only when serviceName = "Stop TB". + // Set via setters after construction (additive, not part of the base constructor + // so every other service line's DTO construction stays exactly as it is today). + private String tuId; + private String tuName; + private String healthFacilityId; + private String healthFacilityName; + public UserServiceRoleDTO(Integer userId, String name, String userName, Integer stateId, String stateName, Integer workingDistrictId, String workingDistrictName, Short serviceProviderId, Integer roleId, String roleName, Integer providerServiceMapId, Integer blockId, String blockName, String villageId, String villageName) { this.userId = userId; this.name = name; 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 f09602491..f9e10e651 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -41,4 +41,36 @@ public interface UserServiceRoleRepo extends JpaRepository getDistrictByBlockId(@Param("blockId") Integer blockId); + // Stop TB / Nikshay — additive only. Reads m_userservicerolemapping directly + // (NOT the shared v_userservicerolemapping view) so the view stays untouched + // and no other service line's query is affected. Returns nothing for any + // user whose rows don't have NikshayTUID set (i.e. every non-Stop-TB user). + // NikshayTUID/NikshayFacilityID are TEXT columns holding a comma-joined + // list of IDs per row (e.g. "12,45,78"), not a single ID, so the TU/Facility + // master tables are joined with FIND_IN_SET rather than plain equality — + // an equality join here would silently match only the first ID in the list + // (MySQL casts "12,45" to 12 for numeric comparison) and drop the rest. + // + // DistrictID on this row is a Nikshay district ID, not an AMRIT one (see + // setWorkLocationObject in Admin-UI) - resolving its name against + // m_nikshay_district (the same ID space) is safe, unlike joining it + // against AMRIT's own m_district, which would silently match whatever + // AMRIT district happens to share that same numeric ID by coincidence. + @Query(value = "SELECT " + + "GROUP_CONCAT(DISTINCT usrm.NikshayTUID ORDER BY usrm.NikshayTUID), " + + "GROUP_CONCAT(DISTINCT nt.TUName ORDER BY nt.NikshayTUID), " + + "GROUP_CONCAT(DISTINCT usrm.NikshayFacilityID ORDER BY usrm.NikshayFacilityID), " + + "GROUP_CONCAT(DISTINCT nf.FacilityName ORDER BY nf.NikshayFacilityID), " + + "usrm.DistrictID, nd.DistrictName " + + "FROM m_userservicerolemapping usrm " + + "LEFT JOIN m_nikshay_tu nt ON FIND_IN_SET(nt.NikshayTUID, usrm.NikshayTUID) > 0 " + + "LEFT JOIN m_nikshay_facility nf ON FIND_IN_SET(nf.NikshayFacilityID, usrm.NikshayFacilityID) > 0 " + + "LEFT JOIN m_nikshay_district nd ON nd.NikshayDistrictID = usrm.DistrictID " + + "WHERE usrm.UserID = :userId AND usrm.ProviderServiceMapID = :providerServiceMapId " + + "AND usrm.Deleted = false AND usrm.NikshayTUID IS NOT NULL " + + "GROUP BY usrm.DistrictID, nd.DistrictName", + nativeQuery = true) + List getNikshayLocationScope(@Param("userId") Integer userId, + @Param("providerServiceMapId") Integer providerServiceMapId); + } diff --git a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java index e0e5b76bd..bd2d3e7c7 100644 --- a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java @@ -23,7 +23,22 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { logger.info("calling getUserRole for userId: " + userId); UserServiceRoleDTO userRole = userServiceRoleRepo.getUserRole(userId).get(0); userRole.setFacilityData(facilityDataService.buildFacilityData(userId, userRole.getRoleName())); - if (userRole.getWorkingDistrictId() == null && userRole.getBlockId() != null) { + + // Stop TB / Nikshay — additive only. This naturally returns nothing for + // any user whose rows don't have NikshayTUID set, i.e. every non-Stop-TB + // user. Fetched first so the district-by-block patch below can tell + // Stop TB users apart and skip them. + java.util.List nikshayResults = userServiceRoleRepo.getNikshayLocationScope(userId, userRole.getProviderServiceMapId()); + boolean isStopTBUser = nikshayResults != null && !nikshayResults.isEmpty() + && nikshayResults.get(0) != null && nikshayResults.get(0).length == 6 + && nikshayResults.get(0)[0] != null; + + // Stop TB's BlockId holds a Nikshay TU ID, not an AMRIT BlockID - + // joining it against m_districtblock/m_district (what + // getDistrictByBlockId does) would resolve to whatever AMRIT + // district happens to share that same numeric ID by coincidence, + // not real data. Skip this patch for Stop TB users. + if (!isStopTBUser && userRole.getWorkingDistrictId() == null && userRole.getBlockId() != null) { java.util.List districtResults = userServiceRoleRepo.getDistrictByBlockId(userRole.getBlockId()); if (districtResults != null && !districtResults.isEmpty()) { Object[] district = districtResults.get(0); @@ -33,6 +48,26 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { } } } + + if (isStopTBUser) { + Object[] nikshay = nikshayResults.get(0); + userRole.setTuId((String) nikshay[0]); + userRole.setTuName((String) nikshay[1]); + userRole.setHealthFacilityId((String) nikshay[2]); + userRole.setHealthFacilityName((String) nikshay[3]); + // Stop TB never sets WorkingLocationID, so workingDistrictId/Name + // (derived from it) are always null. DistrictID sits directly on + // the mapping row instead - Stop TB has no "work location" + // indirection layer the way other servicelines do, so read it + // straight from there rather than trying to derive it. + if (nikshay[4] != null) { + userRole.setWorkingDistrictId(((Number) nikshay[4]).intValue()); + } + if (nikshay[5] != null) { + userRole.setWorkingDistrictName((String) nikshay[5]); + } + } + return userRole; } } From a7b44d5eddf43bbcc9484293cfb8798673cfbc4c Mon Sep 17 00:00:00 2001 From: vishwab1 Date: Wed, 29 Jul 2026 14:00:46 +0530 Subject: [PATCH 450/450] fix(nikshay): replace FIND_IN_SET master-table scan with indexed lookups in getUserDetail getNikshayLocationScope joined m_nikshay_tu/m_nikshay_facility with FIND_IN_SET(masterId, usrm.csvColumn) > 0, which can't use an index on either side and forces a full table scan per login. Measured ~60s for a Stop TB user with ~100 mapped facilities against m_nikshay_facility's 300k+ rows. Replace with a plain fetch of the raw CSV columns off m_userservicerolemapping (indexed by UserID+ProviderServiceMapID), then resolve TU/Facility/District names via IN(...) lookups on their primary keys, reassembling the same comma-joined tuId/tuName/ healthFacilityId/healthFacilityName strings in Java. Measured ~3s for the same user after the change. Co-Authored-By: Claude Sonnet 5 --- .../flw/repo/iemr/UserServiceRoleRepo.java | 49 ++++++------ .../flw/service/impl/UserServiceImpl.java | 78 +++++++++++++++---- 2 files changed, 88 insertions(+), 39 deletions(-) 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 f9e10e651..b94550a28 100644 --- a/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java +++ b/src/main/java/com/iemr/flw/repo/iemr/UserServiceRoleRepo.java @@ -45,32 +45,33 @@ public interface UserServiceRoleRepo extends JpaRepository 0 " + - "LEFT JOIN m_nikshay_facility nf ON FIND_IN_SET(nf.NikshayFacilityID, usrm.NikshayFacilityID) > 0 " + - "LEFT JOIN m_nikshay_district nd ON nd.NikshayDistrictID = usrm.DistrictID " + "WHERE usrm.UserID = :userId AND usrm.ProviderServiceMapID = :providerServiceMapId " + - "AND usrm.Deleted = false AND usrm.NikshayTUID IS NOT NULL " + - "GROUP BY usrm.DistrictID, nd.DistrictName", + "AND usrm.Deleted = false AND usrm.NikshayTUID IS NOT NULL", nativeQuery = true) - List getNikshayLocationScope(@Param("userId") Integer userId, - @Param("providerServiceMapId") Integer providerServiceMapId); + List getNikshayMappingRows(@Param("userId") Integer userId, + @Param("providerServiceMapId") Integer providerServiceMapId); + + @Query(value = "SELECT NikshayTUID, TUName FROM m_nikshay_tu WHERE NikshayTUID IN (:ids)", nativeQuery = true) + List findNikshayTuNames(@Param("ids") java.util.Collection ids); + + @Query(value = "SELECT NikshayFacilityID, FacilityName FROM m_nikshay_facility WHERE NikshayFacilityID IN (:ids)", nativeQuery = true) + List findNikshayFacilityNames(@Param("ids") java.util.Collection ids); + + // DistrictID on m_userservicerolemapping is a Nikshay district ID, not an + // AMRIT one (see setWorkLocationObject in Admin-UI) - resolving its name + // against m_nikshay_district (the same ID space) is safe, unlike joining it + // against AMRIT's own m_district, which would silently match whatever AMRIT + // district happens to share that same numeric ID by coincidence. + @Query(value = "SELECT DistrictName FROM m_nikshay_district WHERE NikshayDistrictID = :id", nativeQuery = true) + String findNikshayDistrictName(@Param("id") Integer id); } diff --git a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java index bd2d3e7c7..52d3eefb1 100644 --- a/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java +++ b/src/main/java/com/iemr/flw/service/impl/UserServiceImpl.java @@ -8,6 +8,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.stream.Collectors; + @Service public class UserServiceImpl implements UserService { @@ -28,10 +35,8 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { // any user whose rows don't have NikshayTUID set, i.e. every non-Stop-TB // user. Fetched first so the district-by-block patch below can tell // Stop TB users apart and skip them. - java.util.List nikshayResults = userServiceRoleRepo.getNikshayLocationScope(userId, userRole.getProviderServiceMapId()); - boolean isStopTBUser = nikshayResults != null && !nikshayResults.isEmpty() - && nikshayResults.get(0) != null && nikshayResults.get(0).length == 6 - && nikshayResults.get(0)[0] != null; + List nikshayRows = userServiceRoleRepo.getNikshayMappingRows(userId, userRole.getProviderServiceMapId()); + boolean isStopTBUser = nikshayRows != null && !nikshayRows.isEmpty(); // Stop TB's BlockId holds a Nikshay TU ID, not an AMRIT BlockID - // joining it against m_districtblock/m_district (what @@ -39,7 +44,7 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { // district happens to share that same numeric ID by coincidence, // not real data. Skip this patch for Stop TB users. if (!isStopTBUser && userRole.getWorkingDistrictId() == null && userRole.getBlockId() != null) { - java.util.List districtResults = userServiceRoleRepo.getDistrictByBlockId(userRole.getBlockId()); + List districtResults = userServiceRoleRepo.getDistrictByBlockId(userRole.getBlockId()); if (districtResults != null && !districtResults.isEmpty()) { Object[] district = districtResults.get(0); if (district != null && district.length == 2) { @@ -50,24 +55,67 @@ public UserServiceRoleDTO getUserDetail(Integer userId) { } if (isStopTBUser) { - Object[] nikshay = nikshayResults.get(0); - userRole.setTuId((String) nikshay[0]); - userRole.setTuName((String) nikshay[1]); - userRole.setHealthFacilityId((String) nikshay[2]); - userRole.setHealthFacilityName((String) nikshay[3]); + TreeSet tuIds = new TreeSet<>(); + TreeSet facilityIds = new TreeSet<>(); + Integer districtId = null; + for (Object[] row : nikshayRows) { + addCsvIds((String) row[0], tuIds); + addCsvIds((String) row[1], facilityIds); + if (districtId == null && row[2] != null) { + districtId = ((Number) row[2]).intValue(); + } + } + + Map tuNames = tuIds.isEmpty() ? Map.of() + : toIdNameMap(userServiceRoleRepo.findNikshayTuNames(tuIds)); + Map facilityNames = facilityIds.isEmpty() ? Map.of() + : toIdNameMap(userServiceRoleRepo.findNikshayFacilityNames(facilityIds)); + + userRole.setTuId(joinIds(tuIds)); + userRole.setTuName(joinNames(tuIds, tuNames)); + userRole.setHealthFacilityId(joinIds(facilityIds)); + userRole.setHealthFacilityName(joinNames(facilityIds, facilityNames)); + // Stop TB never sets WorkingLocationID, so workingDistrictId/Name // (derived from it) are always null. DistrictID sits directly on // the mapping row instead - Stop TB has no "work location" // indirection layer the way other servicelines do, so read it // straight from there rather than trying to derive it. - if (nikshay[4] != null) { - userRole.setWorkingDistrictId(((Number) nikshay[4]).intValue()); - } - if (nikshay[5] != null) { - userRole.setWorkingDistrictName((String) nikshay[5]); + if (districtId != null) { + userRole.setWorkingDistrictId(districtId); + userRole.setWorkingDistrictName(userServiceRoleRepo.findNikshayDistrictName(districtId)); } } return userRole; } + + private void addCsvIds(String csv, Collection target) { + if (csv == null || csv.isBlank()) { + return; + } + for (String id : csv.split(",")) { + try { + target.add(Integer.valueOf(id.trim())); + } catch (NumberFormatException ignored) { + // skip malformed entries rather than fail the whole login + } + } + } + + private Map toIdNameMap(List rows) { + Map map = new HashMap<>(); + for (Object[] row : rows) { + map.put(((Number) row[0]).intValue(), (String) row[1]); + } + return map; + } + + private String joinIds(Collection ids) { + return ids.stream().map(String::valueOf).collect(Collectors.joining(",")); + } + + private String joinNames(Collection ids, Map names) { + return ids.stream().map(id -> names.getOrDefault(id, "")).collect(Collectors.joining(",")); + } }