diff --git a/pom.xml b/pom.xml
index 84eb1596..563ff4d8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -5,7 +5,7 @@
4.0.0
com.iemr.common.identity
identity-api
- 3.6.0
+ 3.6.1
war
@@ -73,6 +73,16 @@
1.3.2
+ org.springframework.boot
+ spring-boot-starter-data-elasticsearch
+
+
+ co.elastic.clients
+ elasticsearch-java
+ 8.11.0
+
+
+
org.springframework.boot
spring-boot-devtools
runtime
@@ -281,31 +291,29 @@
3.3.0
- pl.project13.maven
- git-commit-id-plugin
- 4.9.10
+ io.github.git-commit-id
+ git-commit-id-maven-plugin
+ 9.0.2
get-the-git-infos
revision
+ initialize
- ${project.basedir}/.git
- git
- false
true
-
- ${project.build.outputDirectory}/git.properties
-
- json
-
- false
- false
- -dirty
-
+ ${project.build.outputDirectory}/git.properties
+
+ ^git.branch$
+ ^git.commit.id.abbrev$
+ ^git.build.version$
+ ^git.build.time$
+
+ false
+ false
diff --git a/src/main/environment/common_ci.properties b/src/main/environment/common_ci.properties
index 75ad8759..98736180 100644
--- a/src/main/environment/common_ci.properties
+++ b/src/main/environment/common_ci.properties
@@ -23,3 +23,13 @@ fhir-url=@env.FHIR_API@
spring.redis.host=@env.REDIS_HOST@
cors.allowed-origins=@env.CORS_ALLOWED_ORIGINS@
+
+# Elasticsearch Configuration
+elasticsearch.host=@env.ELASTICSEARCH_HOST@
+elasticsearch.port=@env.ELASTICSEARCH_PORT@
+elasticsearch.username=@env.ELASTICSEARCH_USERNAME@
+elasticsearch.password=@env.ELASTICSEARCH_PASSWORD@
+elasticsearch.index.beneficiary=@env.ELASTICSEARCH_INDEX_BENEFICIARY@
+
+# Enable/Disable ES (for gradual rollout)
+elasticsearch.enabled=@env.ELASTICSEARCH_ENABLED@
diff --git a/src/main/environment/common_docker.properties b/src/main/environment/common_docker.properties
index 90942c28..8f66c5b0 100644
--- a/src/main/environment/common_docker.properties
+++ b/src/main/environment/common_docker.properties
@@ -23,3 +23,13 @@ fhir-url=${FHIR_API}
spring.redis.host=${REDIS_HOST}
cors.allowed-origins=${CORS_ALLOWED_ORIGINS}
+
+# Elasticsearch Configuration
+elasticsearch.host=${ELASTICSEARCH_HOST}
+elasticsearch.port=${ELASTICSEARCH_PORT}
+elasticsearch.username=${ELASTICSEARCH_USERNAME}
+elasticsearch.password=${ELASTICSEARCH_PASSWORD}
+elasticsearch.index.beneficiary=${ELASTICSEARCH_INDEX_BENEFICIARY}
+
+# Enable/Disable ES (for gradual rollout)
+elasticsearch.enabled=${ELASTICSEARCH_ENABLED}
\ No newline at end of file
diff --git a/src/main/environment/common_example.properties b/src/main/environment/common_example.properties
index ad15db00..45018aa6 100644
--- a/src/main/environment/common_example.properties
+++ b/src/main/environment/common_example.properties
@@ -18,3 +18,14 @@ fhir-url=http://localhost:8093/
# Redis Config
spring.redis.host=localhost
cors.allowed-origins=http://localhost:*
+
+# Elasticsearch Configuration
+elasticsearch.host=localhost
+elasticsearch.port=9200
+elasticsearch.username=elastic
+elasticsearch.password=piramalES
+elasticsearch.index.beneficiary=beneficiary_index
+
+# Enable/Disable ES (for gradual rollout)
+elasticsearch.enabled=true
+
diff --git a/src/main/java/com/iemr/common/identity/IdentityApplication.java b/src/main/java/com/iemr/common/identity/IdentityApplication.java
index 2b6ac32c..462c1866 100644
--- a/src/main/java/com/iemr/common/identity/IdentityApplication.java
+++ b/src/main/java/com/iemr/common/identity/IdentityApplication.java
@@ -26,10 +26,12 @@
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
import com.iemr.common.identity.utils.IEMRApplBeans;
@SpringBootApplication
+@ComponentScan(basePackages = {"com.iemr.common.identity"})
public class IdentityApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
diff --git a/src/main/java/com/iemr/common/identity/config/ElasticsearchConfig.java b/src/main/java/com/iemr/common/identity/config/ElasticsearchConfig.java
new file mode 100644
index 00000000..5eec312d
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/config/ElasticsearchConfig.java
@@ -0,0 +1,85 @@
+/*
+* 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.common.identity.config;
+
+import java.io.IOException;
+
+import co.elastic.clients.elasticsearch.ElasticsearchClient;
+import co.elastic.clients.json.jackson.JacksonJsonpMapper;
+import co.elastic.clients.transport.ElasticsearchTransport;
+import co.elastic.clients.transport.rest_client.RestClientTransport;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.http.HttpHost;
+import org.apache.http.auth.AuthScope;
+import org.apache.http.auth.UsernamePasswordCredentials;
+import org.apache.http.impl.client.BasicCredentialsProvider;
+import org.elasticsearch.client.RestClient;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ElasticsearchConfig {
+
+ private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfig.class);
+
+ @Value("${elasticsearch.host}")
+ private String esHost;
+
+ @Value("${elasticsearch.port}")
+ private int esPort;
+
+ @Value("${elasticsearch.username}")
+ private String esUsername;
+
+ @Value("${elasticsearch.password}")
+ private String esPassword;
+
+ @Value("${elasticsearch.index.beneficiary}")
+ private String indexName;
+
+ @Bean
+ public ElasticsearchClient elasticsearchClient() {
+ BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
+ credentialsProvider.setCredentials(
+ AuthScope.ANY,
+ new UsernamePasswordCredentials(esUsername, esPassword)
+ );
+
+ RestClient restClient = RestClient.builder(
+ new HttpHost(esHost, esPort, "http")
+ ).setHttpClientConfigCallback(httpClientBuilder ->
+ httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
+ ).build();
+
+ ElasticsearchTransport transport = new RestClientTransport(
+ restClient,
+ new JacksonJsonpMapper()
+ );
+
+ return new ElasticsearchClient(transport);
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/config/ElasticsearchSyncConfig.java b/src/main/java/com/iemr/common/identity/config/ElasticsearchSyncConfig.java
new file mode 100644
index 00000000..74ef9d2b
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/config/ElasticsearchSyncConfig.java
@@ -0,0 +1,79 @@
+/*
+* 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.common.identity.config;
+
+import java.util.concurrent.Executor;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+/**
+ * Configuration for async processing and scheduling
+ */
+@Configuration
+@EnableAsync
+@EnableScheduling
+public class ElasticsearchSyncConfig {
+
+ /**
+ * Thread pool for Elasticsearch sync operations
+ * Configured for long-running background jobs
+ */
+ @Bean(name = "elasticsearchSyncExecutor")
+ public Executor elasticsearchSyncExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+
+ // Only 1-2 sync jobs should run at a time to avoid overwhelming DB/ES
+ executor.setCorePoolSize(2);
+ executor.setMaxPoolSize(4);
+ executor.setQueueCapacity(100);
+ executor.setThreadNamePrefix("es-sync-");
+ executor.setKeepAliveSeconds(60);
+ executor.setWaitForTasksToCompleteOnShutdown(true);
+ executor.setAwaitTerminationSeconds(60);
+
+ // Handle rejected tasks
+ executor.setRejectedExecutionHandler((r, executor1) -> {
+ throw new RuntimeException("Elasticsearch sync queue is full. Please wait for current job to complete.");
+ });
+
+ executor.initialize();
+ return executor;
+ }
+
+ /**
+ * General purpose async executor
+ */
+ @Bean(name = "taskExecutor")
+ public Executor taskExecutor() {
+ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
+ executor.setCorePoolSize(5);
+ executor.setMaxPoolSize(10);
+ executor.setQueueCapacity(100);
+ executor.setThreadNamePrefix("async-");
+ executor.initialize();
+ return executor;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/controller/IdentityESController.java b/src/main/java/com/iemr/common/identity/controller/IdentityESController.java
new file mode 100644
index 00000000..1d671b5b
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/controller/IdentityESController.java
@@ -0,0 +1,221 @@
+/*
+* 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.common.identity.controller;
+
+import java.text.SimpleDateFormat;
+import java.util.*;
+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 com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.iemr.common.identity.service.IdentityService;
+import com.iemr.common.identity.service.elasticsearch.ElasticsearchService;
+import com.iemr.common.identity.utils.CookieUtil;
+import com.iemr.common.identity.utils.JwtUtil;
+
+import io.swagger.v3.oas.annotations.Operation;
+import jakarta.servlet.http.HttpServletRequest;
+
+/**
+ * Elasticsearch-enabled Beneficiary Search Controller
+ * All search endpoints with ES support
+ */
+@RestController
+@RequestMapping("/beneficiary")
+public class IdentityESController {
+
+ private static final Logger logger = LoggerFactory.getLogger(IdentityESController.class);
+
+ @Autowired
+ private ElasticsearchService elasticsearchService;
+
+ @Autowired
+ private JwtUtil jwtUtil;
+
+ @Autowired
+ private IdentityService idService;
+
+ /**
+ * MAIN UNIVERSAL SEARCH ENDPOINT
+ * Searches across all fields - name, phone, ID, etc.
+ *
+ * Usage: GET /beneficiary/search?query=vani
+ * Usage: GET /beneficiary/search?query=9876543210
+ */
+ @GetMapping("/search")
+ public ResponseEntity> search(@RequestParam String query, HttpServletRequest request) {
+ try {
+ String jwtToken = CookieUtil.getJwtTokenFromCookie(request);
+ String userId = jwtUtil.getUserIdFromToken(jwtToken);
+ int userID = Integer.parseInt(userId);
+ List> results = elasticsearchService.universalSearch(query, userID);
+
+ Map response = new HashMap<>();
+ response.put("data", results);
+ response.put("statusCode", 200);
+ response.put("errorMessage", "Success");
+ response.put("status", "Success");
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ Map errorResponse = new HashMap<>();
+ errorResponse.put("data", new ArrayList<>());
+ errorResponse.put("statusCode", 500);
+ errorResponse.put("errorMessage", e.getMessage());
+ errorResponse.put("status", "Error");
+
+ return ResponseEntity.status(500).body(errorResponse);
+ }
+ }
+
+ /**
+ * Elasticsearch-based advance search
+ */
+
+ @Operation(summary = "Get beneficiaries by advance search using Elasticsearch")
+ @PostMapping(path = "/advancedSearchES", headers = "Authorization")
+ public ResponseEntity> advanceSearchBeneficiariesES(
+ @RequestBody String searchFilter,
+ HttpServletRequest request) {
+
+ logger.info("IdentityESController.advanceSearchBeneficiariesES - start {}", searchFilter);
+ Map response = new HashMap<>();
+
+ try {
+ JsonObject searchParams = JsonParser.parseString(searchFilter).getAsJsonObject();
+ logger.info("Search params = {}", searchParams);
+
+ String firstName = getString(searchParams, "firstName");
+ String middleName = getString(searchParams, "middleName");
+ String maritalStatus = getString(searchParams, "maritalStatus");
+ String lastName = getString(searchParams, "lastName");
+ Integer genderId = getInteger(searchParams, "genderId");
+ Date dob = getDate(searchParams, "dob");
+ String fatherName = getString(searchParams, "fatherName");
+ String spouseName = getString(searchParams, "spouseName");
+ String phoneNumber = getString(searchParams, "phoneNumber");
+ String beneficiaryId = getString(searchParams, "beneficiaryId");
+ String healthId = getString(searchParams, "healthId");
+ String aadharNo = getString(searchParams, "aadharNo");
+ Boolean is1097 = getBoolean(searchParams, "is1097");
+
+ Integer stateId = getLocationInt(searchParams, "stateId");
+ Integer districtId = getLocationInt(searchParams, "districtId");
+ Integer blockId = getLocationInt(searchParams, "blockId");
+ Integer villageId = getLocationInt(searchParams, "villageId");
+
+ String jwtToken = CookieUtil.getJwtTokenFromCookie(request);
+ Integer userID = Integer.parseInt(jwtUtil.getUserIdFromToken(jwtToken));
+
+ logger.info(
+ "ES Advance search - firstName={}, genderId={}, stateId={}, districtId={}, userId={}",
+ firstName, genderId, stateId, districtId, userID);
+
+ Map searchResults = idService.advancedSearchBeneficiariesES(
+ firstName, middleName, lastName, genderId, dob,
+ stateId, districtId, blockId, villageId,
+ fatherName, spouseName, maritalStatus, phoneNumber,
+ beneficiaryId, healthId, aadharNo,
+ userID, null, is1097);
+
+ response.put("data", searchResults.get("data"));
+ response.put("count", searchResults.get("count"));
+ response.put("source", searchResults.get("source"));
+ response.put("statusCode", 200);
+ response.put("errorMessage", "Success");
+ response.put("status", "Success");
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error in beneficiary ES advance search", e);
+ response.put("data", Collections.emptyList());
+ response.put("count", 0);
+ response.put("source", "error");
+ response.put("statusCode", 500);
+ response.put("errorMessage", e.getMessage());
+ response.put("status", "Error");
+ return ResponseEntity.status(500).body(response);
+ }
+ }
+
+ // Helper methods to extract values from JsonObject
+
+ private String getString(JsonObject json, String key) {
+ return json.has(key) && !json.get(key).isJsonNull()
+ ? json.get(key).getAsString()
+ : null;
+ }
+
+ private Integer getInteger(JsonObject json, String key) {
+ return json.has(key) && !json.get(key).isJsonNull()
+ ? json.get(key).getAsInt()
+ : null;
+ }
+
+ private Boolean getBoolean(JsonObject json, String key) {
+ return json.has(key) && !json.get(key).isJsonNull()
+ ? json.get(key).getAsBoolean()
+ : null;
+ }
+
+ private Date getDate(JsonObject json, String key) {
+ if (json.has(key) && !json.get(key).isJsonNull()) {
+ try {
+ return new SimpleDateFormat("yyyy-MM-dd")
+ .parse(json.get(key).getAsString());
+ } catch (Exception e) {
+ logger.error("Invalid date format for {} ", key, e);
+ }
+ }
+ return null;
+ }
+
+ private Integer getLocationInt(JsonObject root, String field) {
+
+ if (root.has(field) && !root.get(field).isJsonNull()) {
+ return root.get(field).getAsInt();
+ }
+
+ String[] addressKeys = {
+ "currentAddress",
+ "permanentAddress",
+ "emergencyAddress"
+ };
+
+ for (String addressKey : addressKeys) {
+ if (root.has(addressKey) && root.get(addressKey).isJsonObject()) {
+ JsonObject addr = root.getAsJsonObject(addressKey);
+ if (addr.has(field) && !addr.get(field).isJsonNull()) {
+ return addr.get(field).getAsInt();
+ }
+ }
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/controller/elasticsearch/ElasticsearchSyncController.java b/src/main/java/com/iemr/common/identity/controller/elasticsearch/ElasticsearchSyncController.java
new file mode 100644
index 00000000..7d8f1877
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/controller/elasticsearch/ElasticsearchSyncController.java
@@ -0,0 +1,484 @@
+/*
+* 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.common.identity.controller.elasticsearch;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.*;
+
+import com.iemr.common.identity.data.elasticsearch.ElasticsearchSyncJob;
+import com.iemr.common.identity.repo.BenMappingRepo;
+import com.iemr.common.identity.service.elasticsearch.ElasticsearchSyncService;
+import com.iemr.common.identity.service.elasticsearch.SyncJobService;
+import com.iemr.common.identity.service.elasticsearch.ElasticsearchSyncService.SyncStatus;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.springframework.http.ResponseEntity;
+import com.iemr.common.identity.utils.response.OutputResponse;
+
+import co.elastic.clients.elasticsearch.ElasticsearchClient;
+
+import com.iemr.common.identity.domain.MBeneficiarymapping;
+import com.iemr.common.identity.service.elasticsearch.ElasticsearchIndexingService;
+
+/**
+ * Controller to manage Elasticsearch synchronization operations
+ * Supports both synchronous and asynchronous sync jobs
+ */
+@RestController
+@RequestMapping("/elasticsearch")
+public class ElasticsearchSyncController {
+
+ private static final Logger logger = LoggerFactory.getLogger(ElasticsearchSyncController.class);
+
+ @Autowired
+ private ElasticsearchSyncService syncService;
+
+ @Autowired
+ private SyncJobService syncJobService;
+
+ @Autowired
+ private BenMappingRepo mappingRepo;
+
+ @Autowired
+ private ElasticsearchIndexingService indexingService;
+
+ @Autowired
+ private ElasticsearchClient esClient;
+
+ @Value("${elasticsearch.index.beneficiary}")
+ private String beneficiaryIndex;
+
+ /**
+ * Start async full sync (RECOMMENDED for millions of records)
+ * Returns immediately with job ID for tracking
+ *
+ * Usage: POST http://localhost:8094/elasticsearch/start
+ */
+ @PostMapping("/start")
+ public ResponseEntity> startAsyncFullSync(
+ @RequestParam(required = false, defaultValue = "API") String triggeredBy) {
+
+ logger.info("Received request to start ASYNC full sync");
+
+ Map response = new HashMap<>();
+
+ try {
+ ElasticsearchSyncJob job = syncJobService.startFullSyncJob(triggeredBy);
+
+ response.put("status", "success");
+ response.put("message", "Sync job started in background");
+ response.put("jobId", job.getJobId());
+ response.put("jobStatus", job.getStatus());
+ response.put("checkStatusUrl", "/elasticsearch/status/" + job.getJobId());
+
+ return ResponseEntity.ok(response);
+
+ } catch (RuntimeException e) {
+ logger.error("Error starting async sync: {}", e.getMessage());
+ response.put("status", "error");
+ response.put("message", e.getMessage());
+ return ResponseEntity.status(HttpStatus.CONFLICT).body(response);
+
+ } catch (Exception e) {
+ logger.error("Unexpected error: {}", e.getMessage(), e);
+ response.put("status", "error");
+ response.put("message", "Unexpected error: " + e.getMessage());
+ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
+ }
+ }
+
+ /**
+ * Get job status by ID
+ *
+ * Usage: GET http://localhost:8094/elasticsearch/status/{jobid}
+ */
+ @GetMapping("/status/{jobId}")
+ public ResponseEntity> getAsyncJobStatus(@PathVariable Long jobId) {
+ logger.info("Checking status for job: {}", jobId);
+
+ try {
+ ElasticsearchSyncJob job = syncJobService.getJobStatus(jobId);
+
+ Map response = new HashMap<>();
+ response.put("jobId", job.getJobId());
+ response.put("jobType", job.getJobType());
+ response.put("status", job.getStatus());
+ response.put("totalRecords", job.getTotalRecords());
+ response.put("processedRecords", job.getProcessedRecords());
+ response.put("successCount", job.getSuccessCount());
+ response.put("failureCount", job.getFailureCount());
+ response.put("progressPercentage", String.format("%.2f", job.getProgressPercentage()));
+ response.put("processingSpeed", job.getProcessingSpeed());
+ response.put("estimatedTimeRemaining", job.getEstimatedTimeRemaining());
+ response.put("startedAt", job.getStartedAt());
+ response.put("completedAt", job.getCompletedAt());
+ response.put("errorMessage", job.getErrorMessage());
+
+ return ResponseEntity.ok(response);
+
+ } catch (RuntimeException e) {
+ Map response = new HashMap<>();
+ response.put("status", "error");
+ response.put("message", e.getMessage());
+ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
+ }
+ }
+
+ /**
+ * Get all active jobs
+ *
+ * Usage: GET http://localhost:8094/elasticsearch/active
+ */
+ @GetMapping("/active")
+ public ResponseEntity> getActiveJobs() {
+ logger.info("Fetching active jobs");
+ return ResponseEntity.ok(syncJobService.getActiveJobs());
+ }
+
+ /**
+ * Get recent jobs
+ *
+ * Usage: GET http://localhost:8080/elasticsearch/recent
+ */
+ @GetMapping("/recent")
+ public ResponseEntity> getRecentJobs() {
+ logger.info("Fetching recent jobs");
+ return ResponseEntity.ok(syncJobService.getRecentJobs());
+ }
+
+ /**
+ * Resume a failed job
+ *
+ * Usage: POST http://localhost:8094/elasticsearch/resume/{jobid}
+ */
+ @PostMapping("/resume/{jobId}")
+ public ResponseEntity> resumeJob(
+ @PathVariable Long jobId,
+ @RequestParam(required = false, defaultValue = "API") String triggeredBy) {
+
+ logger.info("Resuming job: {}", jobId);
+
+ Map response = new HashMap<>();
+
+ try {
+ ElasticsearchSyncJob job = syncJobService.resumeJob(jobId, triggeredBy);
+
+ response.put("status", "success");
+ response.put("message", "Job resumed");
+ response.put("jobId", job.getJobId());
+ response.put("resumedFromOffset", job.getCurrentOffset());
+
+ return ResponseEntity.ok(response);
+
+ } catch (RuntimeException e) {
+ response.put("status", "error");
+ response.put("message", e.getMessage());
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
+ }
+ }
+
+ /**
+ * Cancel a running job
+ *
+ * Usage: POST http://localhost:8094/elasticsearch/cancel/{jobid}
+ */
+ @PostMapping("/cancel/{jobId}")
+ public ResponseEntity> cancelJob(@PathVariable Long jobId) {
+ logger.info("Cancelling job: {}", jobId);
+
+ Map response = new HashMap<>();
+ boolean cancelled = syncJobService.cancelJob(jobId);
+
+ if (cancelled) {
+ response.put("status", "success");
+ response.put("message", "Job cancelled");
+ return ResponseEntity.ok(response);
+ } else {
+ response.put("status", "error");
+ response.put("message", "Could not cancel job. It may not be active.");
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
+ }
+ }
+
+ /**
+ * LEGACY: Synchronous full sync(NOT recommended for large datasets)
+ * Use /start instead
+ *
+ * Usage: POST http://localhost:8094/elasticsearch/all
+ */
+ @PostMapping("/all")
+ public ResponseEntity> syncAllBeneficiaries() {
+ logger.warn("LEGACY sync endpoint called. Consider using /start instead.");
+ logger.info("Received request to sync all beneficiaries (BLOCKING)");
+
+ Map response = new HashMap<>();
+
+ try {
+ ElasticsearchSyncService.SyncResult result = syncService.syncAllBeneficiaries();
+
+ response.put("status", "completed");
+ response.put("successCount", result.getSuccessCount());
+ response.put("failureCount", result.getFailureCount());
+ response.put("error", result.getError());
+ response.put("warning", "This is a blocking operation. For large datasets, use /start");
+
+ if (result.getError() != null) {
+ return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT).body(response);
+ }
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error in sync all endpoint: {}", e.getMessage(), e);
+ response.put("status", "error");
+ response.put("message", e.getMessage());
+ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
+ }
+ }
+
+ /**
+ * Sync a single beneficiary by BenRegId
+ *
+ * Usage: POST http://localhost:8094/elasticsearch/single/123456
+ */
+ @PostMapping("/single/{benRegId}")
+ public ResponseEntity> syncSingleBeneficiary(
+ @PathVariable String benRegId) {
+
+ Map response = new HashMap<>();
+
+ try {
+ boolean success = syncService.syncSingleBeneficiary(benRegId);
+
+ response.put("status", success ? "success" : "failed");
+ response.put("benRegId", benRegId);
+ response.put("synced", success);
+
+ if (!success) {
+ response.put("message", "Beneficiary not found in database or sync failed. Check logs for details.");
+ } else {
+ response.put("message", "Beneficiary successfully synced to Elasticsearch");
+ }
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error syncing single beneficiary: {}", e.getMessage(), e);
+ response.put("status", "error");
+ response.put("benRegId", benRegId);
+ response.put("synced", false);
+ response.put("message", "Exception occurred: " + e.getMessage());
+ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
+ }
+ }
+
+ /**
+ * Check sync status - compare DB count vs ES count
+ *
+ * Usage: GET http://localhost:8094/elasticsearch/status
+ */
+ @GetMapping("/status")
+ public ResponseEntity checkSyncStatus() {
+ logger.info("Received request to check sync status");
+
+ try {
+ SyncStatus status = syncService.checkSyncStatus();
+ return ResponseEntity.ok(status);
+
+ } catch (Exception e) {
+ logger.error("Error checking sync status: {}", e.getMessage(), e);
+ SyncStatus errorStatus = new SyncStatus();
+ errorStatus.setError(e.getMessage());
+ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorStatus);
+ }
+ }
+
+ /**
+ * Health check endpoint
+ *
+ * Usage: GET http://localhost:8094/elasticsearch/health
+ */
+ @GetMapping("/health")
+ public ResponseEntity> healthCheck() {
+ Map response = new HashMap<>();
+ response.put("status", "UP");
+ response.put("service", "Elasticsearch Sync Service");
+ response.put("asyncJobsRunning", syncJobService.isFullSyncRunning());
+ response.put("activeJobs", syncJobService.getActiveJobs().size());
+ return ResponseEntity.ok(response);
+ }
+
+ /**
+ * Debug endpoint to check if a beneficiary exists in database
+ *
+ * Usage: GET http://localhost:8094/elasticsearch/debug/check/123456
+ */
+ @GetMapping("/debug/check/{benRegId}")
+ public ResponseEntity> checkBeneficiaryExists(
+ @PathVariable String benRegId) {
+
+ Map response = new HashMap<>();
+
+ try {
+ java.math.BigInteger benRegIdBig = new java.math.BigInteger(benRegId);
+
+ boolean exists = mappingRepo.existsByBenRegId(benRegIdBig);
+
+ response.put("benRegId", benRegId);
+ response.put("existsInDatabase", exists);
+
+ if (exists) {
+ response.put("message", "Beneficiary found in database");
+
+ MBeneficiarymapping mapping =
+ mappingRepo.findByBenRegId(benRegIdBig);
+
+ if (mapping != null) {
+ response.put("benMapId", mapping.getBenMapId());
+ response.put("deleted", mapping.getDeleted());
+ response.put("hasDetails", mapping.getMBeneficiarydetail() != null);
+ response.put("hasContact", mapping.getMBeneficiarycontact() != null);
+ }
+ } else {
+ response.put("message", "Beneficiary NOT found in database");
+ }
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error checking beneficiary: {}", e.getMessage(), e);
+ response.put("status", "error");
+ response.put("message", e.getMessage());
+ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
+ }
+ }
+
+ /**
+ * Create or recreate the Elasticsearch index with proper mapping
+ * This will DELETE the existing index and create a new one
+ *
+ * POST /elasticsearch/index/create
+ */
+ @PostMapping("/index/create")
+ public ResponseEntity createIndex() {
+ logger.info("API: Create Elasticsearch index request received");
+ OutputResponse response = new OutputResponse();
+
+ try {
+ indexingService.createIndexWithMapping();
+
+ response.setResponse("Index created successfully. Ready for data sync.");
+ logger.info("Index created successfully");
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error creating index: {}", e.getMessage(), e);
+ response.setError(5000, "Error creating index: " + e.getMessage());
+ return ResponseEntity.status(500).body(response);
+ }
+ }
+
+ /**
+ * Recreate index and immediately start syncing data
+ * This is a convenience endpoint that does both operations
+ *
+ * POST /elasticsearch/index/recreate-and-sync
+ */
+ @PostMapping("/index/recreate-and-sync")
+ public ResponseEntity recreateAndSync() {
+ logger.info("API: Recreate index and sync request received");
+ OutputResponse response = new OutputResponse();
+
+ try {
+ // Step 1: Recreate index
+ logger.info("Step 1: Recreating index...");
+ indexingService.createIndexWithMapping();
+ logger.info("Index recreated successfully");
+
+ // Step 2: Start sync
+ logger.info("Step 2: Starting data sync...");
+ Map syncResult = indexingService.indexAllBeneficiaries();
+
+ response.setResponse("Index recreated and sync started. Success: " +
+ syncResult.get("success") + ", Failed: " + syncResult.get("failed"));
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error in recreate and sync: {}", e.getMessage(), e);
+ response.setError(5000, "Error: " + e.getMessage());
+ return ResponseEntity.status(500).body(response);
+ }
+ }
+
+ /**
+ * Get information about the current index
+ * Shows mapping, document count, etc.
+ *
+ * GET /elasticsearch/index/info
+ */
+ @GetMapping("/index/info")
+ public ResponseEntity getIndexInfo() {
+ logger.info("API: Get index info request received");
+ OutputResponse response = new OutputResponse();
+
+ try {
+ // You can add code here to get index stats using esClient
+ response.setResponse("Index info endpoint - implementation pending");
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Error getting index info: {}", e.getMessage(), e);
+ response.setError(5000, "Error: " + e.getMessage());
+ return ResponseEntity.status(500).body(response);
+ }
+ }
+
+ @PostMapping("/refresh")
+public ResponseEntity> refreshIndex() {
+ Map response = new HashMap<>();
+
+ try {
+ logger.info("Manual refresh requested");
+
+ esClient.indices().refresh(r -> r.index(beneficiaryIndex));
+
+ response.put("status", "success");
+ response.put("message", "Index refreshed - all data is now searchable");
+
+ return ResponseEntity.ok(response);
+
+ } catch (Exception e) {
+ logger.error("Refresh failed: {}", e.getMessage(), e);
+ response.put("status", "error");
+ response.put("message", "Refresh failed: " + 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/common/identity/controller/health/HealthController.java b/src/main/java/com/iemr/common/identity/controller/health/HealthController.java
new file mode 100644
index 00000000..b7cc3641
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/controller/health/HealthController.java
@@ -0,0 +1,90 @@
+/*
+* 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.common.identity.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 jakarta.servlet.http.Cookie;
+import jakarta.servlet.http.HttpServletRequest;
+import com.iemr.common.identity.service.health.HealthService;
+import com.iemr.common.identity.utils.JwtAuthenticationUtil;
+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;
+ private final JwtAuthenticationUtil jwtAuthenticationUtil;
+
+ public HealthController(HealthService healthService, JwtAuthenticationUtil jwtAuthenticationUtil) {
+ this.healthService = healthService;
+ this.jwtAuthenticationUtil = jwtAuthenticationUtil;
+ }
+ @GetMapping
+ @Operation(summary = "Check infrastructure health",
+ description = "Returns the health status of MySQL, Redis, Elasticsearch, 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.info("Health check endpoint called");
+
+ try {
+ Map healthStatus = healthService.checkHealth();
+ String overallStatus = (String) healthStatus.get("status");
+
+ // Return 503 only if DOWN; 200 for both UP and DEGRADED (DEGRADED = operational with warnings)
+ 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);
+
+ // Return sanitized error response
+ 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/common/identity/controller/version/VersionController.java b/src/main/java/com/iemr/common/identity/controller/version/VersionController.java
index 4435c3db..39eee9f1 100644
--- a/src/main/java/com/iemr/common/identity/controller/version/VersionController.java
+++ b/src/main/java/com/iemr/common/identity/controller/version/VersionController.java
@@ -21,54 +21,59 @@
*/
package com.iemr.common.identity.controller.version;
-import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
-import java.io.InputStreamReader;
+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 com.iemr.common.identity.utils.response.OutputResponse;
-
import io.swagger.v3.oas.annotations.Operation;
@RestController
public class VersionController {
- private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
+ private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
+ private static final String UNKNOWN_VALUE = "unknown";
+
@Operation(summary = "Get version information")
- @GetMapping(value = "/version",consumes = "application/json", produces = "application/json")
- public String versionInformation() {
- OutputResponse output = new OutputResponse();
+ @GetMapping(value = "/version", produces = MediaType.APPLICATION_JSON_VALUE)
+ public ResponseEntity> versionInformation() {
+ Map response = new LinkedHashMap<>();
try {
logger.info("version Controller Start");
- output.setResponse(readGitProperties());
- } catch (Exception e) {
- output.setError(e);
- }
-
+ 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 output.toString();
+ return ResponseEntity.ok(response);
}
- private String readGitProperties() throws Exception {
- ClassLoader classLoader = getClass().getClassLoader();
- InputStream inputStream = classLoader.getResourceAsStream("git.properties");
-
- return readFromInputStream(inputStream);
- }
- private String readFromInputStream(InputStream inputStream)
- throws IOException {
- StringBuilder resultStringBuilder = new StringBuilder();
- try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
- String line;
- while ((line = br.readLine()) != null) {
- resultStringBuilder.append(line).append("\n");
- }
- }
- return resultStringBuilder.toString();
+
+ 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/common/identity/data/elasticsearch/BeneficiaryDocument.java b/src/main/java/com/iemr/common/identity/data/elasticsearch/BeneficiaryDocument.java
new file mode 100644
index 00000000..acd66c1c
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/data/elasticsearch/BeneficiaryDocument.java
@@ -0,0 +1,172 @@
+/*
+* 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.common.identity.data.elasticsearch;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import lombok.Data;
+import java.util.Date;
+
+@Data
+public class BeneficiaryDocument {
+
+ @JsonProperty("benId")
+ private String benId;
+
+ @JsonProperty("benRegId")
+ private Long benRegId;
+
+ @JsonProperty("beneficiaryID")
+ private String beneficiaryID;
+
+ @JsonProperty("firstName")
+ private String firstName;
+
+ @JsonProperty("middleName")
+ private String middleName;
+
+ @JsonProperty("lastName")
+ private String lastName;
+
+ @JsonProperty("fatherName")
+ private String fatherName;
+
+ @JsonProperty("spouseName")
+ private String spouseName;
+
+ @JsonProperty("maritalStatusID")
+ private Integer maritalStatusID;
+
+ @JsonProperty("maritalStatusName")
+ private String maritalStatusName;
+
+ @JsonProperty("age")
+ private Integer age;
+
+ @JsonProperty("dOB")
+ private Date dOB;
+
+ @JsonProperty("gender")
+ private String gender;
+
+ @JsonProperty("genderID")
+ private Integer genderID;
+
+ @JsonProperty("genderName")
+ private String genderName;
+
+ @JsonProperty("phoneNum")
+ private String phoneNum;
+
+ @JsonProperty("aadharNo")
+ private String aadharNo;
+
+ @JsonProperty("govtIdentityNo")
+ private String govtIdentityNo;
+
+ @JsonProperty("healthID")
+ private String healthID;
+
+ @JsonProperty("abhaID")
+ private String abhaID;
+
+ @JsonProperty("abhaCreatedDate")
+ private String abhaCreatedDate;
+
+ @JsonProperty("familyID")
+ private String familyID;
+
+ @JsonProperty("stateID")
+ private Integer stateID;
+
+ @JsonProperty("stateName")
+ private String stateName;
+
+ @JsonProperty("districtID")
+ private Integer districtID;
+
+ @JsonProperty("districtName")
+ private String districtName;
+
+ @JsonProperty("blockID")
+ private Integer blockID;
+
+ @JsonProperty("blockName")
+ private String blockName;
+
+ @JsonProperty("villageID")
+ private Integer villageID;
+
+ @JsonProperty("villageName")
+ private String villageName;
+
+ @JsonProperty("pinCode")
+ private String pinCode;
+
+ @JsonProperty("servicePointID")
+ private Integer servicePointID;
+
+ @JsonProperty("servicePointName")
+ private String servicePointName;
+
+ @JsonProperty("parkingPlaceID")
+ private Integer parkingPlaceID;
+
+ @JsonProperty("permStateID")
+ private Integer permStateID;
+
+ @JsonProperty("permStateName")
+ private String permStateName;
+
+ @JsonProperty("permDistrictID")
+ private Integer permDistrictID;
+
+ @JsonProperty("permDistrictName")
+ private String permDistrictName;
+
+ @JsonProperty("permBlockID")
+ private Integer permBlockID;
+
+ @JsonProperty("permBlockName")
+ private String permBlockName;
+
+ @JsonProperty("permVillageID")
+ private Integer permVillageID;
+
+ @JsonProperty("permVillageName")
+ private String permVillageName;
+
+ @JsonProperty("createdBy")
+ private String createdBy;
+
+ @JsonProperty("createdDate")
+ private Date createdDate;
+
+ @JsonProperty("lastModDate")
+ private Long lastModDate;
+
+ @JsonProperty("benAccountID")
+ private Long benAccountID;
+
+ @JsonProperty("isHIVPos")
+ private String isHIVPos;
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/data/elasticsearch/ElasticsearchSyncJob.java b/src/main/java/com/iemr/common/identity/data/elasticsearch/ElasticsearchSyncJob.java
new file mode 100644
index 00000000..c2f5c2f0
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/data/elasticsearch/ElasticsearchSyncJob.java
@@ -0,0 +1,116 @@
+/*
+* 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.common.identity.data.elasticsearch;
+
+import java.sql.Timestamp;
+import jakarta.persistence.*;
+import lombok.Data;
+
+/**
+ * Entity to track Elasticsearch sync job status
+ */
+@Entity
+@Table(name = "t_elasticsearch_sync_job")
+@Data
+public class ElasticsearchSyncJob {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "job_id")
+ private Long jobId;
+
+ @Column(name = "job_type", length = 50, nullable = false)
+ private String jobType; // FULL_SYNC, INCREMENTAL_SYNC, SINGLE_BENEFICIARY
+
+ @Column(name = "status", length = 50, nullable = false)
+ private String status; // PENDING, RUNNING, COMPLETED, FAILED, CANCELLED
+
+ @Column(name = "total_records")
+ private Long totalRecords;
+
+ @Column(name = "processed_records")
+ private Long processedRecords;
+
+ @Column(name = "success_count")
+ private Long successCount;
+
+ @Column(name = "failure_count")
+ private Long failureCount;
+
+ @Column(name = "current_offset")
+ private Integer currentOffset;
+
+ @Column(name = "started_at")
+ private Timestamp startedAt;
+
+ @Column(name = "completed_at")
+ private Timestamp completedAt;
+
+ @Column(name = "error_message", columnDefinition = "TEXT")
+ private String errorMessage;
+
+ @Column(name = "triggered_by", length = 100)
+ private String triggeredBy; // User who triggered the job
+
+ @Column(name = "created_date", nullable = false, updatable = false)
+ private Timestamp createdDate;
+
+ @Column(name = "last_updated")
+ private Timestamp lastUpdated;
+
+ @Column(name = "estimated_time_remaining")
+ private Long estimatedTimeRemaining; // in seconds
+
+ @Column(name = "processing_speed")
+ private Double processingSpeed; // records per second
+
+ @PrePersist
+ protected void onCreate() {
+ createdDate = new Timestamp(System.currentTimeMillis());
+ lastUpdated = createdDate;
+ }
+
+ @PreUpdate
+ protected void onUpdate() {
+ lastUpdated = new Timestamp(System.currentTimeMillis());
+ }
+
+ /**
+ * Calculate progress percentage
+ */
+ @Transient
+ public double getProgressPercentage() {
+ if (totalRecords == null || totalRecords == 0) {
+ return 0.0;
+ }
+ return (processedRecords * 100.0) / totalRecords;
+ }
+
+ /**
+ * Check if job is active (running)
+ */
+ @Transient
+ public boolean isActive() {
+ return "RUNNING".equals(status) || "PENDING".equals(status);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java
index e477ea5d..4cab210c 100644
--- a/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java
+++ b/src/main/java/com/iemr/common/identity/data/rmnch/RMNCHBeneficiaryDetailsRmnch.java
@@ -499,4 +499,55 @@ public class RMNCHBeneficiaryDetailsRmnch {
@Column(name = "noOfDaysForDelivery")
private Integer noOfDaysForDelivery;
+
+ @Expose
+ private Boolean isDeath;
+
+ @Expose
+ private String isDeathValue;
+
+ @Expose
+ private String dateOfDeath;
+
+ @Expose
+ private String timeOfDeath;
+
+ @Expose
+ private String reasonOfDeath;
+
+ @Expose
+ private Integer reasonOfDeathId;
+
+ @Expose
+ private String placeOfDeath;
+
+ @Expose
+ private Integer placeOfDeathId;
+
+ @Expose
+ private String otherPlaceOfDeath;
+
+ @Expose
+ private Boolean isSpouseAdded;
+
+
+ @Expose
+ private Boolean isChildrenAdded;
+
+ @Expose
+ private Boolean isMarried;
+
+ @Expose
+ private Boolean doYouHavechildren;
+
+
+ @Expose
+ private Integer noofAlivechildren;
+
+ @Expose
+ private Integer noOfchildren;
+
+ @Expose
+ private Boolean isDeactivate;
+
}
diff --git a/src/main/java/com/iemr/common/identity/domain/User.java b/src/main/java/com/iemr/common/identity/domain/User.java
index 2a88b2e1..38fca023 100644
--- a/src/main/java/com/iemr/common/identity/domain/User.java
+++ b/src/main/java/com/iemr/common/identity/domain/User.java
@@ -15,7 +15,7 @@
import jakarta.persistence.Table;
import lombok.Data;
@Entity
-@Table(name = "m_User",schema = "db_iemr")
+@Table(schema = "db_iemr", name = "m_user")
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
diff --git a/src/main/java/com/iemr/common/identity/dto/BeneficiariesESDTO.java b/src/main/java/com/iemr/common/identity/dto/BeneficiariesESDTO.java
new file mode 100644
index 00000000..e7de32f8
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/dto/BeneficiariesESDTO.java
@@ -0,0 +1,209 @@
+/*
+* 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.common.identity.dto;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+import lombok.AllArgsConstructor;
+import java.util.Date;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class BeneficiariesESDTO {
+
+ @JsonProperty("benRegId")
+ private Long benRegId;
+
+ @JsonProperty("beneficiaryID")
+ private String beneficiaryID;
+
+ @JsonProperty("firstName")
+ private String firstName;
+
+ @JsonProperty("middleName")
+ private String middleName;
+
+ @JsonProperty("lastName")
+ private String lastName;
+
+ @JsonProperty("genderID")
+ private Integer genderID;
+
+ @JsonProperty("genderName")
+ private String genderName;
+
+ @JsonProperty("dOB")
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "UTC")
+ private Date dOB;
+
+ @JsonProperty("age")
+ private Integer age;
+
+ @JsonProperty("phoneNum")
+ private String phoneNum;
+
+ // @JsonProperty("aadharNo")
+ // private String aadharNo;
+
+ // @JsonProperty("govtIdentityNo")
+ // private String govtIdentityNo;
+
+ @JsonProperty("fatherName")
+ private String fatherName;
+
+ @JsonProperty("spouseName")
+ private String spouseName;
+
+ @JsonProperty("maritalStatusID")
+ private Integer maritalStatusID;
+
+ @JsonProperty("maritalStatusName")
+ private String maritalStatusName;
+
+ @JsonProperty("createdBy")
+ private String createdBy;
+
+ @JsonProperty("createdDate")
+ private Date createdDate;
+
+ @JsonProperty("lastModDate")
+ private Long lastModDate;
+
+ @JsonProperty("benAccountID")
+ private Long benAccountID;
+
+ @JsonProperty("isHIVPos")
+ private String isHIVPos;
+
+ @JsonProperty("healthID")
+ private String healthID;
+
+ @JsonProperty("abhaID")
+ private String abhaID;
+
+ @JsonProperty("abhaCreatedDate")
+ private String abhaCreatedDate;
+
+ @JsonProperty("familyID")
+ private String familyID;
+
+ @JsonProperty("stateID")
+ private Integer stateID;
+
+ @JsonProperty("stateName")
+ private String stateName;
+
+ @JsonProperty("stateCode")
+ private String stateCode;
+
+ @JsonProperty("districtID")
+ private Integer districtID;
+
+ @JsonProperty("districtName")
+ private String districtName;
+
+ @JsonProperty("blockID")
+ private Integer blockID;
+
+ @JsonProperty("blockName")
+ private String blockName;
+
+ @JsonProperty("villageID")
+ private Integer villageID;
+
+ @JsonProperty("villageName")
+ private String villageName;
+
+ @JsonProperty("districtBranchID")
+ private Integer districtBranchID;
+
+ @JsonProperty("districtBranchName")
+ private String districtBranchName;
+
+ @JsonProperty("parkingPlaceID")
+ private Integer parkingPlaceID;
+
+ @JsonProperty("servicePointID")
+ private Integer servicePointID;
+
+ @JsonProperty("servicePointName")
+ private String servicePointName;
+
+ @JsonProperty("pinCode")
+ private String pinCode;
+
+ @JsonProperty("permStateID")
+ private Integer permStateID;
+
+ @JsonProperty("permStateName")
+ private String permStateName;
+
+ @JsonProperty("permDistrictID")
+ private Integer permDistrictID;
+
+ @JsonProperty("permDistrictName")
+ private String permDistrictName;
+
+ @JsonProperty("permBlockID")
+ private Integer permBlockID;
+
+ @JsonProperty("permBlockName")
+ private String permBlockName;
+
+ @JsonProperty("permVillageID")
+ private Integer permVillageID;
+
+ @JsonProperty("permVillageName")
+ private String permVillageName;
+
+ @JsonProperty("phoneNumbers")
+ private List phoneNumbers;
+
+ @Data
+ @NoArgsConstructor
+ @AllArgsConstructor
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public static class PhoneNumberDTO {
+ @JsonProperty("benPhMapID")
+ private Long benPhMapID;
+
+ @JsonProperty("phoneNo")
+ private String phoneNo;
+
+ @JsonProperty("parentBenRegID")
+ private Long parentBenRegID;
+
+ @JsonProperty("benRelationshipID")
+ private Integer benRelationshipID;
+
+ @JsonProperty("benRelationshipType")
+ private String benRelationshipType;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/mapper/BeneficiaryESMapper.java b/src/main/java/com/iemr/common/identity/mapper/BeneficiaryESMapper.java
new file mode 100644
index 00000000..412b0f09
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/mapper/BeneficiaryESMapper.java
@@ -0,0 +1,158 @@
+/*
+* 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.common.identity.mapper;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.stereotype.Component;
+
+import java.util.*;
+
+@Component
+public class BeneficiaryESMapper {
+
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ public Map transformESResponse(List> esResults) {
+ List> transformedData = new ArrayList<>();
+
+ for (Map esDoc : esResults) {
+ Map beneficiary = new HashMap<>();
+
+ beneficiary.put("beneficiaryRegID", esDoc.get("beneficiaryRegID"));
+ beneficiary.put("beneficiaryID", esDoc.get("beneficiaryID"));
+ beneficiary.put("firstName", esDoc.get("firstName"));
+ beneficiary.put("lastName", esDoc.get("lastName"));
+ beneficiary.put("genderID", esDoc.get("genderID"));
+ beneficiary.put("genderName", esDoc.get("genderName"));
+ beneficiary.put("dOB", esDoc.get("dOB"));
+ beneficiary.put("dob", esDoc.get("dOB"));
+ beneficiary.put("age", esDoc.get("age"));
+ beneficiary.put("actualAge", esDoc.get("age"));
+ beneficiary.put("ageUnits", "Years");
+ beneficiary.put("fatherName", esDoc.getOrDefault("fatherName", ""));
+ beneficiary.put("spouseName", esDoc.getOrDefault("spouseName", ""));
+ beneficiary.put("isHIVPos", esDoc.getOrDefault("isHIVPos", ""));
+ beneficiary.put("createdBy", esDoc.get("createdBy"));
+ beneficiary.put("createdDate", esDoc.get("createdDate"));
+ beneficiary.put("lastModDate", esDoc.get("lastModDate"));
+ beneficiary.put("benAccountID", esDoc.get("benAccountID"));
+
+ Map mGender = new HashMap<>();
+ mGender.put("genderID", esDoc.get("genderID"));
+ mGender.put("genderName", esDoc.get("genderName"));
+ beneficiary.put("m_gender", mGender);
+
+ Map demographics = (Map) esDoc.get("demographics");
+ if (demographics != null) {
+ Map benDemographics = new HashMap<>(demographics);
+ benDemographics.put("beneficiaryRegID", esDoc.get("beneficiaryRegID"));
+
+ benDemographics.put("m_state", createStateObject(demographics));
+ benDemographics.put("m_district", createDistrictObject(demographics));
+ benDemographics.put("m_districtblock", createBlockObject(demographics));
+ benDemographics.put("m_districtbranchmapping", createBranchObject(demographics));
+
+ beneficiary.put("i_bendemographics", benDemographics);
+ }
+
+ List> phoneMaps = new ArrayList<>();
+ List> phoneNumbers = (List>) esDoc.get("phoneNumbers");
+ if (phoneNumbers != null && !phoneNumbers.isEmpty()) {
+ for (Map phone : phoneNumbers) {
+ Map phoneMap = new HashMap<>(phone);
+ phoneMap.put("benificiaryRegID", esDoc.get("beneficiaryRegID"));
+
+ Map relationType = new HashMap<>();
+ relationType.put("benRelationshipID", phone.get("benRelationshipID"));
+ relationType.put("benRelationshipType", phone.get("benRelationshipType"));
+ phoneMap.put("benRelationshipType", relationType);
+
+ phoneMaps.add(phoneMap);
+ }
+ }
+ beneficiary.put("benPhoneMaps", phoneMaps);
+
+ beneficiary.put("isConsent", false);
+ beneficiary.put("m_title", new HashMap<>());
+ beneficiary.put("maritalStatus", new HashMap<>());
+ beneficiary.put("changeInSelfDetails", false);
+ beneficiary.put("changeInAddress", false);
+ beneficiary.put("changeInContacts", false);
+ beneficiary.put("changeInIdentities", false);
+ beneficiary.put("changeInOtherDetails", false);
+ beneficiary.put("changeInFamilyDetails", false);
+ beneficiary.put("changeInAssociations", false);
+ beneficiary.put("changeInBankDetails", false);
+ beneficiary.put("changeInBenImage", false);
+ beneficiary.put("is1097", false);
+ beneficiary.put("emergencyRegistration", false);
+ beneficiary.put("passToNurse", false);
+ beneficiary.put("beneficiaryIdentities", new ArrayList<>());
+
+ transformedData.add(beneficiary);
+ }
+
+ Map response = new HashMap<>();
+ response.put("data", transformedData);
+ response.put("statusCode", 200);
+ response.put("errorMessage", "Success");
+ response.put("status", "Success");
+
+ return response;
+ }
+
+ private Map createStateObject(Map demographics) {
+ Map state = new HashMap<>();
+ state.put("stateID", demographics.get("stateID"));
+ state.put("stateName", demographics.get("stateName"));
+ state.put("stateCode", demographics.get("stateCode"));
+ state.put("countryID", 1);
+ return state;
+ }
+
+ private Map createDistrictObject(Map demographics) {
+ Map district = new HashMap<>();
+ district.put("districtID", demographics.get("districtID"));
+ district.put("districtName", demographics.get("districtName"));
+ district.put("stateID", demographics.get("stateID"));
+ return district;
+ }
+
+ private Map createBlockObject(Map demographics) {
+ Map block = new HashMap<>();
+ block.put("blockID", demographics.get("blockID"));
+ block.put("blockName", demographics.get("blockName"));
+ block.put("districtID", demographics.get("districtID"));
+ block.put("stateID", demographics.get("stateID"));
+ return block;
+ }
+
+ private Map createBranchObject(Map demographics) {
+ Map branch = new HashMap<>();
+ branch.put("districtBranchID", demographics.get("districtBranchID"));
+ branch.put("blockID", demographics.get("blockID"));
+ branch.put("villageName", demographics.get("districtBranchName"));
+ branch.put("pinCode", demographics.get("pinCode"));
+ return branch;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/repo/BenAddressRepo.java b/src/main/java/com/iemr/common/identity/repo/BenAddressRepo.java
index d9339ab2..5d79f8ae 100644
--- a/src/main/java/com/iemr/common/identity/repo/BenAddressRepo.java
+++ b/src/main/java/com/iemr/common/identity/repo/BenAddressRepo.java
@@ -18,7 +18,7 @@
*
* 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.common.identity.repo;
import java.math.BigInteger;
@@ -36,42 +36,59 @@
@Repository
public interface BenAddressRepo extends CrudRepository {
- List findByBenAddressIDOrderByBenAddressIDAsc(BigInteger benAddressID);
- List findByCurrPinCodeOrderByBenAddressIDAsc(String currPinCode);
+ List findByBenAddressIDOrderByBenAddressIDAsc(BigInteger benAddressID);
- List findByPermPinCodeOrderByBenAddressIDAsc(String permPinCode);
+ List findByCurrPinCodeOrderByBenAddressIDAsc(String currPinCode);
- List findByCurrStateAndCurrDistrictOrderByBenAddressIDAsc(String currState, String currDist);
+ List findByPermPinCodeOrderByBenAddressIDAsc(String permPinCode);
- List findByCurrStateIdAndCurrDistrictIdOrderByBenAddressIDAsc(Integer currStateID,
- Integer currDistID);
+ List findByCurrStateAndCurrDistrictOrderByBenAddressIDAsc(String currState, String currDist);
- List findByPermStateAndPermDistrictOrderByBenAddressIDAsc(String permState, String permDist);
+ List findByCurrStateIdAndCurrDistrictIdOrderByBenAddressIDAsc(Integer currStateID,
+ Integer currDistID);
- List findByPermStateIdAndPermDistrictIdOrderByBenAddressIDAsc(Integer permStateID,
- Integer permDistID);
+ List findByPermStateAndPermDistrictOrderByBenAddressIDAsc(String permState, String permDist);
- List findByEmerStateAndEmerDistrictOrderByBenAddressIDAsc(String emerState, String emerDist);
+ List findByPermStateIdAndPermDistrictIdOrderByBenAddressIDAsc(Integer permStateID,
+ Integer permDistID);
- List findByEmerStateIdAndEmerDistrictIdOrderByBenAddressIDAsc(Integer emerStateID,
- Integer emerDistID);
+ List findByEmerStateAndEmerDistrictOrderByBenAddressIDAsc(String emerState, String emerDist);
- List findByCreatedDateBetweenOrderByBenAddressIDAsc(Timestamp fromDate, Timestamp toDate);
+ List findByEmerStateIdAndEmerDistrictIdOrderByBenAddressIDAsc(Integer emerStateID,
+ Integer emerDistID);
- @Query("select a from MBeneficiaryaddress a where a.currAddressValue = :address or "
- + "a.emerAddressValue = :address or a.permAddressValue = :address order by a.benAddressID asc")
- List findByAddress(String address);
+ List findByCreatedDateBetweenOrderByBenAddressIDAsc(Timestamp fromDate, Timestamp toDate);
- @Transactional
- @Modifying
- @Query(" UPDATE MBeneficiaryaddress set vanSerialNo = :benAddressID WHERE benAddressID = :benAddressID")
- int updateVanSerialNo(@Param("benAddressID") BigInteger benAddressID);
+ @Query("select a from MBeneficiaryaddress a where a.currAddressValue = :address or "
+ + "a.emerAddressValue = :address or a.permAddressValue = :address order by a.benAddressID asc")
+ List findByAddress(String address);
- @Query("SELECT benAddressID FROM MBeneficiaryaddress WHERE vanSerialNo =:vanSerialNo AND vanID =:vanID ")
- BigInteger findIdByVanSerialNoAndVanID(@Param("vanSerialNo") BigInteger vanSerialNo, @Param("vanID") Integer vanID);
+ @Transactional
+ @Modifying
+ @Query(" UPDATE MBeneficiaryaddress set vanSerialNo = :benAddressID WHERE benAddressID = :benAddressID")
+ int updateVanSerialNo(@Param("benAddressID") BigInteger benAddressID);
+
+ @Query("SELECT benAddressID FROM MBeneficiaryaddress WHERE vanSerialNo =:vanSerialNo AND vanID =:vanID ")
+ BigInteger findIdByVanSerialNoAndVanID(@Param("vanSerialNo") BigInteger vanSerialNo, @Param("vanID") Integer vanID);
+
+ @Query("SELECT a FROM MBeneficiaryaddress a WHERE a.vanSerialNo =:vanSerialNo AND a.vanID =:vanID ")
+ MBeneficiaryaddress getWithVanSerialNoVanID(@Param("vanSerialNo") BigInteger vanSerialNo,
+ @Param("vanID") Integer vanID);
+
+ /**
+ * Get user location details from m_userservicerolemapping
+ */
+ @Query(value = "SELECT "
+ + "ProviderServiceMapID, " +
+ "Blockid, " +
+ "Villageid, " +
+ "WorkingLocationID " +
+ "FROM db_iemr.m_userservicerolemapping "
+ + "WHERE UserID = :userId "
+ + "AND Deleted = false "
+ + "LIMIT 1",
+ nativeQuery = true)
+ List getUserLocation(@Param("userId") Integer userId);
- @Query("SELECT a FROM MBeneficiaryaddress a WHERE a.vanSerialNo =:vanSerialNo AND a.vanID =:vanID ")
- MBeneficiaryaddress getWithVanSerialNoVanID(@Param("vanSerialNo") BigInteger vanSerialNo,
- @Param("vanID") Integer vanID);
}
diff --git a/src/main/java/com/iemr/common/identity/repo/BenDetailRepo.java b/src/main/java/com/iemr/common/identity/repo/BenDetailRepo.java
index 3a8be24f..4e8bcc01 100644
--- a/src/main/java/com/iemr/common/identity/repo/BenDetailRepo.java
+++ b/src/main/java/com/iemr/common/identity/repo/BenDetailRepo.java
@@ -23,6 +23,7 @@
import java.math.BigInteger;
import java.sql.Timestamp;
+import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
@@ -147,4 +148,237 @@ int untagFamily(@Param("modifiedBy") String modifiedBy, @Param("vanSerialNo") Bi
@Query("SELECT b FROM MBeneficiarydetail b WHERE b.familyId =:familyid ")
List searchByFamilyId(@Param("familyid") String familyid);
+ /**
+ * Find complete beneficiary data by IDs from Elasticsearch
+ */
+ @Query(value = "SELECT " +
+ "m.BenRegId, " + // 0
+ "brm.beneficiaryID, " + // 1
+ "d.FirstName, " + // 2
+ "d.MiddleName, " + // 3
+ "d.LastName, " + // 4
+ "d.GenderID, " + // 5
+ "g.GenderName, " + // 6
+ "d.DOB, " + // 7
+ "TIMESTAMPDIFF(YEAR, d.DOB, CURDATE()) as Age, " + // 8
+ "d.FatherName, " + // 9
+ "d.SpouseName, " + // 10
+ "d.MaritalStatusID, " + // 11
+ "ms.Status as MaritalStatusName, " + // 12
+ "d.IsHIVPositive, " + // 13
+ "m.CreatedBy, " + // 14
+ "m.CreatedDate, " + // 15
+ "UNIX_TIMESTAMP(m.LastModDate) * 1000, " + // 16
+ "m.BenAccountID, " + // 17
+ "addr.CurrStateId, " + // 18
+ "addr.CurrState, " + // 19
+ "addr.CurrDistrictId, " + // 20
+ "addr.CurrDistrict, " + // 21
+ "addr.CurrSubDistrictId, " + // 22
+ "addr.CurrSubDistrict, " + // 23
+ "addr.CurrPinCode, " + // 24
+ "addr.CurrServicePointId, " + // 25
+ "addr.CurrServicePoint, " + // 26
+ "addr.ParkingPlaceID, " + // 27
+ "contact.PreferredPhoneNum, " + // 28
+ "addr.CurrVillageId, " + // 29
+ "addr.CurrVillage " + // 30
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarydetails d ON m.BenDetailsId = d.BeneficiaryDetailsID " +
+ "LEFT JOIN m_beneficiaryregidmapping brm ON brm.BenRegId = m.BenRegId " +
+ "LEFT JOIN db_iemr.m_gender g ON d.GenderID = g.GenderID " +
+ "LEFT JOIN db_iemr.m_maritalstatus ms ON d.MaritalStatusID = ms.StatusID " +
+ "LEFT JOIN i_beneficiaryaddress addr ON m.BenAddressId = addr.BenAddressID " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId IN (:ids) AND m.Deleted = false",
+ nativeQuery = true)
+ List findCompleteDataByIds(@Param("ids") List ids);
+
+ /**
+ * Direct search in database (fallback)
+ */
+ @Query(value = "SELECT " +
+ "m.BenRegId, " +
+ "brm.beneficiaryID, " +
+ "d.FirstName, " +
+ "d.MiddleName, " +
+ "d.LastName, " +
+ "d.GenderID, " +
+ "g.GenderName, " +
+ "d.DOB, " +
+ "TIMESTAMPDIFF(YEAR, d.DOB, CURDATE()) as Age, " +
+ "d.FatherName, " +
+ "d.SpouseName, " +
+ "d.MaritalStatusID, " +
+ "ms.Status as MaritalStatusName, " +
+ "d.IsHIVPositive, " +
+ "m.CreatedBy, " +
+ "m.CreatedDate, " +
+ "UNIX_TIMESTAMP(m.LastModDate) * 1000, " +
+ "m.BenAccountID, " +
+ "addr.CurrStateId, " +
+ "addr.CurrState, " +
+ "addr.CurrDistrictId, " +
+ "addr.CurrDistrict, " +
+ "addr.CurrSubDistrictId, " +
+ "addr.CurrSubDistrict, " +
+ "addr.CurrPinCode, " +
+ "addr.CurrServicePointId, " +
+ "addr.CurrServicePoint, " +
+ "addr.ParkingPlaceID, " +
+ "contact.PreferredPhoneNum, " +
+ "addr.CurrVillageId, " +
+ "addr.CurrVillage " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarydetails d ON m.BenDetailsId = d.BeneficiaryDetailsID " +
+ "LEFT JOIN db_iemr.m_gender g ON d.GenderID = g.GenderID " +
+ "LEFT JOIN m_beneficiaryregidmapping brm ON brm.BenRegId = m.BenRegId " +
+ "LEFT JOIN db_iemr.m_maritalstatus ms ON d.MaritalStatusID = ms.StatusID " +
+ "LEFT JOIN i_beneficiaryaddress addr ON m.BenAddressId = addr.BenAddressID " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE (d.FirstName LIKE CONCAT('%', :query, '%') " +
+ " OR d.MiddleName LIKE CONCAT('%', :query, '%') " +
+ " OR d.LastName LIKE CONCAT('%', :query, '%') " +
+ " OR d.FatherName LIKE CONCAT('%', :query, '%') " +
+ " OR d.BeneficiaryRegID = :query " +
+ " OR contact.PreferredPhoneNum = :query " +
+ " OR contact.PhoneNum1 = :query " +
+ " OR contact.PhoneNum2 = :query " +
+ " OR contact.PhoneNum3 = :query " +
+ " OR contact.PhoneNum4 = :query " +
+ " OR contact.PhoneNum5 = :query) " +
+ "AND m.Deleted = false " +
+ "LIMIT 20",
+ nativeQuery = true)
+ List searchBeneficiaries(@Param("query") String query);
+
+ /**
+ * Get all phone numbers for a beneficiary
+ */
+ @Query(value = "SELECT " +
+ "contact.PreferredPhoneNum as phoneNo, " +
+ "'Preferred' as phoneType, " +
+ "1 as priority " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PreferredPhoneNum IS NOT NULL " +
+ "UNION ALL " +
+ "SELECT contact.PhoneNum1, contact.PhoneTyp1, 2 " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PhoneNum1 IS NOT NULL " +
+ "UNION ALL " +
+ "SELECT contact.PhoneNum2, contact.PhoneTyp2, 3 " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PhoneNum2 IS NOT NULL " +
+ "UNION ALL " +
+ "SELECT contact.PhoneNum3, contact.PhoneTyp3, 4 " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PhoneNum3 IS NOT NULL " +
+ "UNION ALL " +
+ "SELECT contact.PhoneNum4, contact.PhoneTyp4, 5 " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PhoneNum4 IS NOT NULL " +
+ "UNION ALL " +
+ "SELECT contact.PhoneNum5, contact.PhoneTyp5, 6 " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "WHERE m.BenRegId = :beneficiaryId AND contact.PhoneNum5 IS NOT NULL " +
+ "ORDER BY priority",
+ nativeQuery = true)
+ List findPhoneNumbersByBeneficiaryId(@Param("beneficiaryId") Long beneficiaryId);
+
+// Advance Search ES
+@Query(value =
+ "SELECT DISTINCT " +
+ "m.BenRegId, " + // 0
+ "brm.beneficiaryID, " + // 1
+ "d.FirstName, " + // 2
+ "d.MiddleName, " + // 3
+ "d.LastName, " + // 4
+ "d.GenderID, " + // 5
+ "g.GenderName, " + // 6
+ "d.DOB, " + // 7
+ "TIMESTAMPDIFF(YEAR, d.DOB, CURDATE()) AS Age, "+
+ "d.FatherName, " + // 9
+ "d.SpouseName, " + // 10
+ "d.MaritalStatusID, " + // 11
+ "ms.Status AS MaritalStatusName, " + // 12
+ "d.IsHIVPositive, " + // 13
+ "m.CreatedBy, " + // 14
+ "m.CreatedDate, " + // 15
+ "UNIX_TIMESTAMP(m.LastModDate) * 1000, " + // 16
+ "m.BenAccountID, " + // 17
+ "addr.CurrStateId, " + // 18
+ "addr.CurrState, " + // 19
+ "addr.CurrDistrictId, " + // 20
+ "addr.CurrDistrict, " + // 21
+ "addr.CurrSubDistrictId, " + // 22
+ "addr.CurrSubDistrict, " + // 23
+ "addr.CurrPinCode, " + // 24
+ "addr.CurrServicePointId, " + // 25
+ "addr.CurrServicePoint, " + // 26
+ "addr.ParkingPlaceID, " + // 27
+ "contact.PreferredPhoneNum, " + // 28
+ "addr.CurrVillageId, " +
+ "addr.CurrVillage " +
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarydetails d " +
+ " ON m.BenDetailsId = d.BeneficiaryDetailsID " +
+ "LEFT JOIN db_iemr.m_gender g " +
+ " ON d.GenderID = g.GenderID " +
+ "LEFT JOIN db_iemr.m_maritalstatus ms ON d.MaritalStatusID = ms.StatusID " +
+ "LEFT JOIN i_beneficiaryaddress addr " +
+ " ON m.BenAddressId = addr.BenAddressID " +
+ "LEFT JOIN i_beneficiarycontacts contact " +
+ " ON m.BenContactsId = contact.BenContactsID " +
+ "LEFT JOIN m_beneficiaryregidmapping brm ON brm.BenRegId = m.BenRegId " +
+ "WHERE m.Deleted = false " +
+
+ "AND (:firstName IS NULL OR d.FirstName LIKE CONCAT('%', :firstName, '%')) " +
+ "AND (:middleName IS NULL OR d.MiddleName LIKE CONCAT('%', :middleName, '%')) " +
+ "AND (:lastName IS NULL OR d.LastName LIKE CONCAT('%', :lastName, '%')) " +
+ "AND (:genderId IS NULL OR d.GenderID = :genderId) " +
+ "AND (:dob IS NULL OR DATE(d.DOB) = DATE(:dob)) " +
+
+ "AND (:stateId IS NULL OR addr.CurrStateId = :stateId) " +
+ "AND (:districtId IS NULL OR addr.CurrDistrictId = :districtId) " +
+ "AND (:blockId IS NULL OR addr.CurrSubDistrictId = :blockId) " +
+
+ "AND (:fatherName IS NULL OR d.FatherName LIKE CONCAT('%', :fatherName, '%')) " +
+ "AND (:spouseName IS NULL OR d.SpouseName LIKE CONCAT('%', :spouseName, '%')) " +
+ "AND (:maritalStatus IS NULL OR d.MaritalStatusID = :maritalStatus) " +
+ "AND (:phoneNumber IS NULL OR " +
+ " contact.PreferredPhoneNum LIKE CONCAT('%', :phoneNumber, '%') OR " +
+ " contact.PhoneNum1 LIKE CONCAT('%', :phoneNumber, '%') OR " +
+ " contact.PhoneNum2 LIKE CONCAT('%', :phoneNumber, '%') OR " +
+ " contact.PhoneNum3 LIKE CONCAT('%', :phoneNumber, '%') OR " +
+ " contact.PhoneNum4 LIKE CONCAT('%', :phoneNumber, '%') OR " +
+ " contact.PhoneNum5 LIKE CONCAT('%', :phoneNumber, '%')) " +
+
+ "AND (:beneficiaryId IS NULL OR d.BeneficiaryRegID = :beneficiaryId) " +
+
+ "ORDER BY m.CreatedDate DESC " +
+ "LIMIT 100",
+ nativeQuery = true)
+List advancedSearchBeneficiaries(
+ @Param("firstName") String firstName,
+ @Param("middleName") String middleName,
+ @Param("lastName") String lastName,
+ @Param("genderId") Integer genderId,
+ @Param("dob") Date dob,
+ @Param("stateId") Integer stateId,
+ @Param("districtId") Integer districtId,
+ @Param("blockId") Integer blockId,
+ @Param("fatherName") String fatherName,
+ @Param("spouseName") String spouseName,
+ @Param("maritalStatus") String maritalStatus,
+ @Param("phoneNumber") String phoneNumber,
+ @Param("beneficiaryId") String beneficiaryId
+);
+
+
}
diff --git a/src/main/java/com/iemr/common/identity/repo/BenMappingRepo.java b/src/main/java/com/iemr/common/identity/repo/BenMappingRepo.java
index e3080a5d..fd781922 100644
--- a/src/main/java/com/iemr/common/identity/repo/BenMappingRepo.java
+++ b/src/main/java/com/iemr/common/identity/repo/BenMappingRepo.java
@@ -142,4 +142,106 @@ Long getBeneficiaryCountsByVillageIDAndLastModifyDate(@Param("villageIDs") List<
@Query("SELECT a FROM MBeneficiarymapping a WHERE a.vanSerialNo =:vanSerialNo AND a.vanID =:vanID ")
MBeneficiarymapping getWithVanSerialNoVanID(@Param("vanSerialNo") BigInteger vanSerialNo,
@Param("vanID") Integer vanID);
+
+ @Query("SELECT b.benRegId, b.benMapId FROM MBeneficiarymapping b WHERE benRegId IS NOT NULL AND deleted = false")
+ List getAllBeneficiaryIds();
+
+ /**
+ * Get beneficiary IDs in batches for efficient processing
+ */
+ @Query(value = "SELECT BenRegId FROM i_beneficiarymapping " +
+ "WHERE Deleted = false ORDER BY BenRegId LIMIT :limit OFFSET :offset",
+ nativeQuery = true)
+ List getBeneficiaryIdsBatch(@Param("offset") int offset, @Param("limit") int limit);
+
+ /**
+ * Count total non-deleted beneficiaries
+ */
+ @Query(value = "SELECT COUNT(*) FROM i_beneficiarymapping WHERE Deleted = false", nativeQuery = true)
+ long countActiveBeneficiaries();
+ /**
+ * COMPLETE DATA FETCH - Single query with all joins
+ * This is the key query that fetches everything needed for ES indexing
+ */
+ @Query(value = "SELECT " +
+ "m.BenRegId, " + // 0
+ "brm.BeneficiaryId, " + // 1
+ "d.FirstName, " + // 2
+ "d.MiddleName, " + // 3
+ "d.LastName, " + // 4
+ "d.GenderID, " + // 5
+ "g.GenderName, " + // 6
+ "d.DOB, " + // 7
+ "TIMESTAMPDIFF(YEAR, d.DOB, CURDATE()), " + // 8 - age
+ "d.FatherName, " + // 9
+ "d.SpouseName, " + // 10
+ "d.MaritalStatusID, " + // 11
+ "ms.Status as MaritalStatusName, " + // 12 - MaritalStatusName
+ "d.IsHIVPositive, " + // 13
+ "m.CreatedBy, " + // 14
+ "m.CreatedDate, " + // 15
+ "UNIX_TIMESTAMP(m.LastModDate) * 1000, " + // 16
+ "m.BenAccountID, " + // 17
+ "contact.PreferredPhoneNum, " + // 18
+ "fam.BenFamilyMapId, " + // 19
+ "addr.CurrStateId, " + // 20
+ "addr.CurrState, " + // 21
+ "addr.CurrDistrictId, " + // 22
+ "addr.CurrDistrict, " + // 23
+ "addr.CurrSubDistrictId, " + // 24
+ "addr.CurrSubDistrict, " + // 25
+ "addr.CurrVillageId, " + // 26
+ "addr.CurrVillage, " + // 27
+ "addr.CurrPinCode, " + // 28
+ "addr.CurrServicePointId, " + // 29
+ "addr.CurrServicePoint, " + // 30
+ "addr.ParkingPlaceID, " + // 31
+ "addr.PermStateId, " + // 32
+ "addr.PermState, " + // 33
+ "addr.PermDistrictId, " + // 34
+ "addr.PermDistrict, " + // 35
+ "addr.PermSubDistrictId, " + // 36
+ "addr.PermSubDistrict, " + // 37
+ "addr.PermVillageId, " + // 38
+ "addr.PermVillage " + // 39
+ "FROM i_beneficiarymapping m " +
+ "LEFT JOIN i_beneficiarydetails d ON m.BenDetailsId = d.BeneficiaryDetailsID " +
+ "LEFT JOIN db_iemr.m_gender g ON d.GenderID = g.GenderID " +
+ "LEFT JOIN db_iemr.m_maritalstatus ms ON d.MaritalStatusID = ms.MaritalStatusID " +
+ "LEFT JOIN i_beneficiaryaddress addr ON m.BenAddressId = addr.BenAddressID " +
+ "LEFT JOIN i_beneficiarycontacts contact ON m.BenContactsId = contact.BenContactsID " +
+ "LEFT JOIN m_beneficiaryregidmapping brm ON brm.BenRegId = m.BenRegId " +
+ "LEFT JOIN db_iemr.m_benhealthidmapping h ON m.BenRegId = h.BeneficiaryRegID " +
+ "LEFT JOIN i_beneficiaryfamilymapping fam " +
+ " ON m.BenRegId = fam.AssociatedBenRegID " +
+ " AND fam.Deleted = false " +
+ "WHERE m.BenRegId IN :benRegIds " +
+ "AND m.Deleted = false",
+ nativeQuery = true)
+
+ List findCompleteDataByBenRegIds(@Param("benRegIds") List benRegIds);
+
+ /**
+ * Find with all details (JPA approach - for single beneficiary)
+ */
+ @Query("SELECT m FROM MBeneficiarymapping m " +
+ "LEFT JOIN FETCH m.mBeneficiarydetail " +
+ "LEFT JOIN FETCH m.mBeneficiarycontact " +
+ "LEFT JOIN FETCH m.mBeneficiaryaddress " +
+ "WHERE m.benRegId = :benRegId AND m.deleted = false")
+ MBeneficiarymapping findByBenRegIdWithDetails(@Param("benRegId") BigInteger benRegId);
+
+ /**
+ * Simple find by benRegId
+ */
+ @Query("SELECT m FROM MBeneficiarymapping m WHERE m.benRegId = :benRegId AND m.deleted = false")
+ MBeneficiarymapping findByBenRegId(@Param("benRegId") BigInteger benRegId);
+
+ /**
+ * Check if beneficiary exists
+ */
+ @Query(value = "SELECT COUNT(*) > 0 FROM i_beneficiarymapping WHERE BenRegId = :benRegId AND Deleted = false", nativeQuery = true)
+ boolean existsByBenRegId(@Param("benRegId") BigInteger benRegId);
+
+
}
diff --git a/src/main/java/com/iemr/common/identity/repo/V_BenAdvanceSearchRepo.java b/src/main/java/com/iemr/common/identity/repo/V_BenAdvanceSearchRepo.java
index 0be61bb0..a7fd5f27 100644
--- a/src/main/java/com/iemr/common/identity/repo/V_BenAdvanceSearchRepo.java
+++ b/src/main/java/com/iemr/common/identity/repo/V_BenAdvanceSearchRepo.java
@@ -46,4 +46,9 @@ public interface V_BenAdvanceSearchRepo extends CrudRepository getBenRegIDByHealthIDNoAbhaIdNo(@Param("healthIDNo") String healthIDNo);
+ //Batch fetch ABHA details for multiple beneficiaries
+ @Query(nativeQuery = true, value = "SELECT BeneficiaryRegID, HealthID, HealthIDNumber, AuthenticationMode, CreatedDate"
+ + " FROM db_iemr.m_benhealthidmapping WHERE BeneficiaryRegID IN :benRegIDs ORDER BY BeneficiaryRegID, CreatedDate DESC")
+ List getBenAbhaDetailsByBenRegIDs(@Param("benRegIDs") List benRegIDs);
+
}
diff --git a/src/main/java/com/iemr/common/identity/repo/elasticsearch/SyncJobRepo.java b/src/main/java/com/iemr/common/identity/repo/elasticsearch/SyncJobRepo.java
new file mode 100644
index 00000000..62f9eadb
--- /dev/null
+++ b/src/main/java/com/iemr/common/identity/repo/elasticsearch/SyncJobRepo.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.common.identity.repo.elasticsearch;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.stereotype.Repository;
+
+import com.iemr.common.identity.data.elasticsearch.ElasticsearchSyncJob;
+
+@Repository
+public interface SyncJobRepo extends JpaRepository {
+
+ /**
+ * Find all active (running or pending) jobs
+ */
+ @Query("SELECT j FROM ElasticsearchSyncJob j WHERE j.status IN ('RUNNING', 'PENDING') ORDER BY j.createdDate DESC")
+ List findActiveJobs();
+
+ /**
+ * Check if there's any active full sync job
+ */
+ @Query("SELECT COUNT(j) > 0 FROM ElasticsearchSyncJob j WHERE j.jobType = 'FULL_SYNC' AND j.status IN ('RUNNING', 'PENDING')")
+ boolean hasActiveFullSyncJob();
+
+ /**
+ * Find latest job of a specific type
+ */
+ @Query("SELECT j FROM ElasticsearchSyncJob j WHERE j.jobType = :jobType ORDER BY j.createdDate DESC")
+ List findLatestJobsByType(String jobType);
+
+ /**
+ * Find recent jobs (last 10)
+ */
+ @Query("SELECT j FROM ElasticsearchSyncJob j ORDER BY j.createdDate DESC")
+ List findRecentJobs();
+
+ /**
+ * Find job by ID
+ */
+ Optional findByJobId(Long jobId);
+}
\ No newline at end of file
diff --git a/src/main/java/com/iemr/common/identity/service/IdentityService.java b/src/main/java/com/iemr/common/identity/service/IdentityService.java
index 029b60a4..08b9fbbe 100644
--- a/src/main/java/com/iemr/common/identity/service/IdentityService.java
+++ b/src/main/java/com/iemr/common/identity/service/IdentityService.java
@@ -18,7 +18,7 @@
*
* 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.common.identity.service;
import java.math.BigDecimal;
@@ -32,6 +32,7 @@
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
+import java.util.stream.Collectors;
import javax.sql.DataSource;
@@ -49,6 +50,7 @@
import com.google.gson.JsonParser;
import com.google.gson.LongSerializationPolicy;
import com.iemr.common.identity.data.rmnch.RMNCHBeneficiaryDetailsRmnch;
+import com.iemr.common.identity.domain.Address;
import com.iemr.common.identity.domain.MBeneficiaryAccount;
import com.iemr.common.identity.domain.MBeneficiaryImage;
import com.iemr.common.identity.domain.MBeneficiaryaddress;
@@ -90,673 +92,954 @@
import com.iemr.common.identity.repo.MBeneficiaryImageRepo;
import com.iemr.common.identity.repo.V_BenAdvanceSearchRepo;
import com.iemr.common.identity.repo.rmnch.RMNCHBeneficiaryDetailsRmnchRepo;
+import com.iemr.common.identity.service.elasticsearch.ElasticsearchService;
import com.iemr.common.identity.utils.mapper.OutputMapper;
import com.iemr.common.identity.utils.response.OutputResponse;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.beans.factory.annotation.Value;
+
+import com.iemr.common.identity.service.elasticsearch.BeneficiaryElasticsearchIndexUpdater;
import jakarta.persistence.NoResultException;
import jakarta.persistence.QueryTimeoutException;
-
@Service
public class IdentityService {
- private static final Logger logger = LoggerFactory.getLogger(IdentityService.class);
- public static final String CREATED_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
- @Autowired
- private DataSource dataSource;
-
- private JdbcTemplate jdbcTemplate;
-
- private JdbcTemplate getJdbcTemplate() {
- return new JdbcTemplate(dataSource);
-
- }
-
- @Autowired
- private RMNCHBeneficiaryDetailsRmnchRepo rMNCHBeneficiaryDetailsRmnchRepo;
-
- @Autowired
- IdentityMapper mapper;
- @Autowired
- IdentityEditMapper editMapper;
- @Autowired
- IdentitySearchMapper searchMapper;
- @Autowired
- private IdentityPartialMapper partialMapper;
- @Autowired
- BenAddressRepo addressRepo;
- @Autowired
- BenConsentRepo consentRepo;
- @Autowired
- BenContactRepo contactRepo;
- @Autowired
- BenDataAccessRepo accessRepo;
- @Autowired
- BenDetailRepo detailRepo;
- @Autowired
- BenFamilyMappingRepo familyMapRepo;
- @Autowired
- BenIdentityRepo identityRepo;
- @Autowired
- BenMappingRepo mappingRepo;
- @Autowired
- BenRegIdMappingRepo regIdRepo;
- @Autowired
- BenServiceMappingRepo serviceMapRepo;
- @Autowired
- MBeneficiaryAccountRepo accountRepo;
- @Autowired
- MBeneficiaryImageRepo imageRepo;
- @Autowired
- private BenIdImportMapper benIdImportMapper;
- @Autowired
- private V_BenAdvanceSearchRepo v_BenAdvanceSearchRepo;
-
- public void getBenAdress() {
- logger.debug("Address count: " + addressRepo.count());
- logger.debug(
- "Address By Address: " + addressRepo.findByBenAddressIDOrderByBenAddressIDAsc(new BigInteger("12")));
- logger.debug("Consent count: " + consentRepo.count());
- logger.debug("Consent By Id: " + consentRepo.findByBenConsentIDOrderByBenConsentIDAsc(new BigInteger("12")));
- logger.debug("Contact count: " + contactRepo.count());
- logger.debug("Contact By Id: " + contactRepo.findByBenContactsIDOrderByBenContactsIDAsc(new BigInteger("12")));
- logger.debug("Data Access count: " + accessRepo.count());
- logger.debug("Data Access By Id: " + accessRepo.findByAccessIdOrderByAccessIdAsc(new BigInteger("12")));
- logger.debug("Detail count: " + detailRepo.count());
- logger.debug("Detail By Address: "
- + detailRepo.findByBeneficiaryDetailsIdOrderByBeneficiaryDetailsIdAsc(new BigInteger("12")));
- logger.debug("FamilyMap count: " + familyMapRepo.count());
- logger.debug(
- "FamilyMap By Id: " + familyMapRepo.findByBenFamilyMapIdOrderByBenFamilyMapIdAsc(new BigInteger("12")));
- logger.debug("Identity count: " + identityRepo.count());
- logger.debug("Identity By Id: " + identityRepo.findByBenIdentityId(new BigInteger("12")));
- logger.debug("Mapping count: " + mappingRepo.count());
- logger.debug("Mapping By Id: " + mappingRepo.findByBenMapIdOrderByBenMapIdAsc(new BigInteger("12")));
- }
-
- /**
- *
- * @param searchDTO
- * @return
- */
- public List getBeneficiaries(IdentitySearchDTO searchDTO)
- throws NoResultException, QueryTimeoutException, Exception {
- List list = new ArrayList();
-
- /**
- * if beneficiary Id present
- */
- if (searchDTO.getBeneficiaryId() != null) {
- logger.info("getting beneficiaries by ID for " + searchDTO.getBeneficiaryId());
- return this.getBeneficiariesByBenId(searchDTO.getBeneficiaryId());
- }
-
- /**
- * if beneficiary Reg Id present
- */
- if (searchDTO.getBeneficiaryRegId() != null) {
- logger.info("getting beneficiaries by reg ID for " + searchDTO.getBeneficiaryRegId());
- return this.getBeneficiariesByBenRegId(searchDTO.getBeneficiaryRegId());
- }
-
- /**
- * if beneficiary Reg Id present
- */
- if (searchDTO.getContactNumber() != null) {
- logger.info("getting beneficiaries by contact no for " + searchDTO.getContactNumber());
- List list3 = this.getBeneficiariesByPhoneNum(searchDTO.getContactNumber());
- if (!list3.isEmpty() && searchDTO.getIsD2D() != null && Boolean.TRUE.equals(searchDTO.getIsD2D())) {
-
- for (int i = 0; i < list3.size(); i++) {
- if (searchDTO.getFirstName() != null) {
- if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
- || list3.get(i).getBeneficiaryDetails().getFirstName() == null
- || !list3.get(i).getBeneficiaryDetails().getFirstName()
- .equalsIgnoreCase(searchDTO.getFirstName())) {
- list3.remove(i);
- i--;
-
- continue;
- }
-
- }
- if (searchDTO.getLastName() != null) {
- if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
- || list3.get(i).getBeneficiaryDetails().getLastName() == null
- || !list3.get(i).getBeneficiaryDetails().getLastName()
- .equalsIgnoreCase(searchDTO.getLastName())) {
- list3.remove(i);
- i--;
-
- continue;
- }
- }
-
- if (searchDTO.getGenderId() != null) {
- if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
- || list3.get(i).getBeneficiaryDetails().getGenderId() == null || !list3.get(i)
- .getBeneficiaryDetails().getGenderId().equals(searchDTO.getGenderId())) {
-
- list3.remove(i);
- i--;
- continue;
- }
- }
- if (searchDTO.getHouseHoldID() != null) {
- if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
- || list3.get(i).getBeneficiaryDetails().getHouseHoldID() == null || !list3.get(i)
- .getBeneficiaryDetails().getHouseHoldID().equals(searchDTO.getHouseHoldID())) {
-
- list3.remove(i);
- i--;
- continue;
- }
- }
-
- if (searchDTO.getCurrentAddress().getStateId() != null) {
- if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
- || list3.get(i).getCurrentAddress().getStateId() == null
- || !list3.get(i).getCurrentAddress().getStateId()
- .equals(searchDTO.getCurrentAddress().getStateId())) {
-
- list3.remove(i);
- i--;
- continue;
- }
- }
-
- if (searchDTO.getCurrentAddress().getDistrictId() != null) {
- if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
- || list3.get(i).getCurrentAddress().getDistrictId() == null
- || !list3.get(i).getCurrentAddress().getDistrictId()
- .equals(searchDTO.getCurrentAddress().getDistrictId())) {
-
- list3.remove(i);
- i--;
- continue;
- }
- }
-
- if (searchDTO.getCurrentAddress().getVillageId() != null) {
- if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
- || list3.get(i).getCurrentAddress().getVillageId() == null
- || !list3.get(i).getCurrentAddress().getVillageId()
- .equals(searchDTO.getCurrentAddress().getVillageId())) {
-
- list3.remove(i);
- i--;
- continue;
- }
- }
-
- }
- }
- return list3;
- }
-
- /**
- * New logic for advance search, 03-10-2018
- */
- List tmpList = mappingRepo.dynamicFilterSearchNew(searchDTO);
- for (VBenAdvanceSearch obj : tmpList) {
- list.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew1(obj)));
- logger.debug("benMapId: " + obj.getBenMapID());
- }
- /**
- * End
- */
-
- return list;
- }
-
- /**
- *
- * Check which parameters available Get BenMapID based on the parameter/set of
- * parameters Use BenMapID to retrieve all data for a Beneficiary
- *
- * @param benId
- * @return
- */
- public List getBeneficiariesByBenId(BigInteger benId)
- throws NoResultException, QueryTimeoutException, Exception {
- logger.info("IdentityService.getBeneficiariesByBenId - start, beneficiaryID : " + benId);
- List list = new ArrayList();
-
- MBeneficiaryregidmapping regId = regIdRepo.findByBeneficiaryID(benId);
- if (regId != null && regId.getBenRegId() != null) {
- List benMapObjArr = mappingRepo.getBenMappingByRegID(regId.getBenRegId());
-
- // new logic, 27-08-2018
- if (benMapObjArr != null && benMapObjArr.size() > 0) {
- MBeneficiarymapping benMap = this.getBeneficiariesDTONew(benMapObjArr.get(0));
- list.add(this.getBeneficiariesDTO(benMap));
- }
- }
- logger.info("benMap size " + (list.size() == 0 ? "No Beneficiary Found" : list.size()));
- // end new logic
-
- logger.info("IdentityService.getBeneficiariesByBenId - end - beneficiaryID : " + benId);
-
- return list;
- }
-
- /**
- *
- * @param BenRegId
- * @return
- */
- public List getBeneficiariesByBenRegId(BigInteger benRegId)
- throws NoResultException, QueryTimeoutException, Exception {
- List list = new ArrayList();
- logger.info("IdentityService.getBeneficiariesByBenRegId - start for benRegId " + benRegId);
- try {
- // new logic, 27-09-2018
- List benMapObjArr = mappingRepo.getBenMappingByRegID(benRegId);
-
- // new logic, 27-08-2018
- if (benMapObjArr != null && !benMapObjArr.isEmpty()) {
- MBeneficiarymapping benMap = this.getBeneficiariesDTONew(benMapObjArr.get(0));
- list.add(this.getBeneficiariesDTO(benMap));
- }
- logger.info("benMap size" + (list.isEmpty() ? "No Beneficiary Found" : list.size()));
- // end new logic
-
- logger.info("IdentityService.getBeneficiariesByBenRegId - end for benRegId " + benRegId);
- } catch (Exception e) {
- logger.error("error in beneficiary search for beneficiary reg id : " + benRegId + " error : "
- + e.getLocalizedMessage());
- }
-
- return list;
- }
-
- /**
- *
- * Check which parameters available Get BenMapID based on the parameter/set of
- * parameters Use BenMapID to retrieve all data for a Beneficiary
- *
- * @param phoneNum
- * @return
- */
-
- public List getBeneficiariesByPhoneNum(String phoneNum)
- throws NoResultException, QueryTimeoutException {
- // new logic, 27-09-2018
- List list = new ArrayList<>();
- try {
- List benContact = contactRepo.findByAnyPhoneNum(phoneNum);
-
- logger.info(benContact.size() + " contacts found for phone number " + phoneNum);
-
- List benMapObjArr = new ArrayList<>();
-
- for (MBeneficiarycontact benContactOBJ : benContact) {
- benMapObjArr.addAll(mappingRepo.getBenMappingByBenContactIdListNew(benContactOBJ.getVanSerialNo(),
- benContactOBJ.getVanID()));
- }
-
- for (Object[] benMapOBJ : benMapObjArr) {
- list.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
- }
-
- } catch (Exception e) {
- logger.error(
- "error in beneficiary search for phone no : " + phoneNum + " error : " + e.getLocalizedMessage());
- }
-
- logger.info("IdentityService.getBeneficiariesByPhoneNum - end");
- // end
- return list;
- }
-
- /***
- *
- * Search beneficiary by healthID / ABHA address
- *
- * @param healthID
- * @return
- * @throws NoResultException
- * @throws QueryTimeoutException
- * @throws Exception
- */
-
- public List getBeneficiaryByHealthIDAbhaAddress(String healthID)
- throws NoResultException, QueryTimeoutException, Exception {
- List beneficiaryList = new ArrayList<>();
- try {
- List regIDList = v_BenAdvanceSearchRepo.getBenRegIDByHealthIDAbhaAddress(healthID);
- if (regIDList != null && !regIDList.isEmpty()) {
- for (BigInteger benRegID : regIDList) {
- if (benRegID != null) {
- List searchList = this.getBeneficiariesByBenRegId(benRegID);
- beneficiaryList.addAll(searchList);
- }
- }
- }
- } catch (Exception e) {
- logger.error("error in beneficiary search for health ID / ABHA Address : " + healthID + " error : "
- + e.getLocalizedMessage());
- }
- return beneficiaryList;
- }
-
- /***
- *
- * Search beneficiary by healthIDNo / ABHA ID No
- *
- * @param healthIDNo
- * @return
- * @throws NoResultException
- * @throws QueryTimeoutException
- * @throws Exception
- */
-
- public List getBeneficiaryByHealthIDNoAbhaIdNo(String healthIDNo)
- throws NoResultException, QueryTimeoutException, Exception {
- List beneficiaryList = new ArrayList<>();
- try {
- List regIDList = v_BenAdvanceSearchRepo.getBenRegIDByHealthIDNoAbhaIdNo(healthIDNo);
- if (regIDList != null && !regIDList.isEmpty()) {
- for (BigInteger benRegID : regIDList) {
- if (benRegID != null) {
- List searchList = this.getBeneficiariesByBenRegId(benRegID);
- beneficiaryList.addAll(searchList);
- }
- }
- }
- } catch (Exception e) {
- logger.error("error in beneficiary search for health ID No / ABHA ID No : " + healthIDNo + " error : "
- + e.getLocalizedMessage());
- }
- return beneficiaryList;
- }
-
- public List searhBeneficiaryByFamilyId(String familyId)
- throws NoResultException, QueryTimeoutException {
- List beneficiaryList = new ArrayList<>();
- try {
-
- // find benmap ids
- List benMapObjArr = null;
- List benDetailsVanSerialNoList = new ArrayList<>();
- int vanID = 0;
-
- List benDetailsList = detailRepo.searchByFamilyId(familyId);
-
- if (benDetailsList == null || benDetailsList.isEmpty())
- return beneficiaryList;
- else {
- // considering as of now family creation is possible through facility modules
- // only
- vanID = benDetailsList.get(0).getVanID();
-
- for (MBeneficiarydetail benDetails : benDetailsList) {
- benDetailsVanSerialNoList.add(benDetails.getVanSerialNo());
- }
-
- benMapObjArr = mappingRepo.getBenMappingByBenDetailsIds(benDetailsVanSerialNoList, vanID);
-
- for (Object[] benMapOBJ : benMapObjArr) {
- beneficiaryList.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
- }
-
- }
-
- } catch (Exception e) {
- logger.error(
- "error in beneficiary search for familyId : " + familyId + " error : " + e.getLocalizedMessage());
- }
- return beneficiaryList;
- }
-
- public List searchBeneficiaryByVillageIdAndLastModifyDate(List villageIDs,
- Timestamp lastModifiedDate) {
-
- List beneficiaryList = new ArrayList<>();
- try {
- // find benmap ids
- List benMappingsList = mappingRepo
- .findByBeneficiaryDetailsByVillageIDAndLastModifyDate(villageIDs, lastModifiedDate);
- if (benMappingsList != null && !benMappingsList.isEmpty()) {
- for (MBeneficiarymapping benMapOBJ : benMappingsList) {
- beneficiaryList.add(this.getBeneficiariesDTO(benMapOBJ));
- }
- }
-
- } catch (Exception e) {
- logger.error("error in beneficiary search to sync to CHO App with villageIDs: {} ",
- villageIDs + " error : " + e.getLocalizedMessage());
- }
- return beneficiaryList;
- }
-
- public Long countBeneficiaryByVillageIdAndLastModifyDate(List villageIDs, Timestamp lastModifiedDate) {
- Long beneficiaryCount = 0L;
- try {
- beneficiaryCount = mappingRepo.getBeneficiaryCountsByVillageIDAndLastModifyDate(villageIDs,
- lastModifiedDate);
- } catch (Exception e) {
- logger.error("error in getting beneficiary count to sync to CHO App with villageIDs: {},error :{} ",
- villageIDs, e.getLocalizedMessage());
- }
- return beneficiaryCount;
- }
-
- public List searhBeneficiaryByGovIdentity(String identity)
- throws NoResultException, QueryTimeoutException {
- List beneficiaryList = new ArrayList<>();
- try {
-
- List benMapObjArr = new ArrayList<>();
-
- // find identity no
- List benIdentityList = identityRepo.searchByIdentityNo(identity);
-
- // find benmap ids
- if (benIdentityList == null || benIdentityList.isEmpty())
- return beneficiaryList;
- else {
- for (MBeneficiaryidentity identityObj : benIdentityList) {
- benMapObjArr.addAll(
- mappingRepo.getBenMappingByVanSerialNo(identityObj.getBenMapId(), identityObj.getVanID()));
- }
-
- for (Object[] benMapOBJ : benMapObjArr) {
- beneficiaryList.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
- }
-
- }
-
- } catch (Exception e) {
- logger.error("error in beneficiary search for gov identity : " + identity + " error : "
- + e.getLocalizedMessage());
- }
- return beneficiaryList;
- }
-
- private MBeneficiarymapping getBeneficiariesDTONew(Object[] benMapArr) {
- MBeneficiarymapping mapping = new MBeneficiarymapping();
- if (benMapArr != null && benMapArr.length == 12 && benMapArr[8] != null && benMapArr[9] != null) {
- mapping.setBenMapId(getBigIntegerValueFromObject(benMapArr[0]));
- mapping.setCreatedBy(String.valueOf(benMapArr[10]));
- mapping.setCreatedDate((Timestamp) benMapArr[11]);
- mapping = mappingRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[9]), (Integer) benMapArr[8]);
- MBeneficiaryaddress address = addressRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[1]), (Integer) benMapArr[8]);
- MBeneficiaryconsent consent = consentRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[2]), (Integer) benMapArr[8]);
- MBeneficiarycontact contact = contactRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[3]), (Integer) benMapArr[8]);
- MBeneficiarydetail details = detailRepo.getWith_vanSerialNo_vanID(getBigIntegerValueFromObject(benMapArr[4]), (Integer) benMapArr[8]);
- MBeneficiaryregidmapping regidmapping = regIdRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[5]), (Integer) benMapArr[8]);
- MBeneficiaryAccount account = accountRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[7]), (Integer) benMapArr[8]);
- MBeneficiaryImage image = imageRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[6]), (Integer) benMapArr[8]);
- List servicemap = serviceMapRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
- List identity = identityRepo.findByBenMapIdAndVanID(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
- List familymapping = familyMapRepo.findByBenMapIdAndVanIDOrderByBenFamilyMapIdAsc(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
-
- mapping.setMBeneficiaryaddress(address);
- mapping.setMBeneficiaryconsent(consent);
- mapping.setMBeneficiarycontact(contact);
- mapping.setMBeneficiarydetail(details);
- mapping.setMBeneficiaryfamilymappings(familymapping);
- mapping.setMBeneficiaryidentities(identity);
- mapping.setMBeneficiaryImage(image);
- mapping.setMBeneficiaryregidmapping(regidmapping);
- mapping.setMBeneficiaryservicemappings(servicemap);
- mapping.setMBeneficiaryAccount(account);
- //benMapOBJ = mappingRepo.getMapping(getBigIntegerValueFromObject(benMapArr[9]), (Integer) benMapArr[8]);
-
-
-
- BigInteger benRegId = new BigInteger(benMapArr[5].toString());
- RMNCHBeneficiaryDetailsRmnch obj = rMNCHBeneficiaryDetailsRmnchRepo
- .getByRegID(benRegId);
-
- if (obj != null) {
- if (obj.getHouseoldId() != null)
- mapping.setHouseHoldID(obj.getHouseoldId());
- if (obj.getGuidelineId() != null)
- mapping.setGuideLineID(obj.getGuidelineId());
- if (obj.getRchid() != null)
- mapping.setRchID(obj.getRchid());
- }
-
- }
- return mapping;
- }
- private MBeneficiarymapping getBeneficiariesDTONewPartial(Object[] benMapArr) {
- MBeneficiarymapping benMapOBJ = new MBeneficiarymapping();
-
- benMapOBJ.setBenMapId(getBigIntegerValueFromObject(benMapArr[0]));
- benMapOBJ.setCreatedBy(String.valueOf(benMapArr[10]));
- benMapOBJ.setCreatedDate((Timestamp) benMapArr[11]);
-
- if (benMapArr.length == 12 && benMapArr[8] != null && benMapArr[9] != null) {
-
- benMapOBJ.setMBeneficiarydetail(detailRepo
- .getWith_vanSerialNo_vanID(getBigIntegerValueFromObject(benMapArr[4]), (Integer) benMapArr[8]));
- benMapOBJ.setMBeneficiaryregidmapping(regIdRepo
- .getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[5]), (Integer) benMapArr[8]));
- }
- return benMapOBJ;
- }
-
- // 03-10-2018
- // get ben mapping object from v_benadvancesearch
- private MBeneficiarymapping getBeneficiariesDTONew1(VBenAdvanceSearch benAdvanceSearchOBJ) {
- MBeneficiarymapping benMapOBJ = new MBeneficiarymapping();
-
- // for createdBy & createdDate
- if (benAdvanceSearchOBJ != null) {
- MBeneficiarydetail benDetailsOBJ = detailRepo
- .getWith_vanSerialNo_vanID(benAdvanceSearchOBJ.getBenDetailsID(), benAdvanceSearchOBJ.getVanID());
-
- if (benAdvanceSearchOBJ.getHouseHoldID() != null)
- benMapOBJ.setHouseHoldID(benAdvanceSearchOBJ.getHouseHoldID());
- if (benAdvanceSearchOBJ.getGuideLineID() != null)
- benMapOBJ.setGuideLineID(benAdvanceSearchOBJ.getGuideLineID());
- if (benAdvanceSearchOBJ.getRchID() != null)
- benMapOBJ.setRchID(benAdvanceSearchOBJ.getRchID());
-
- benMapOBJ.setBenMapId(benAdvanceSearchOBJ.getBenMapID());
- benMapOBJ.setCreatedBy(benDetailsOBJ.getCreatedBy());
- benMapOBJ.setCreatedDate(benDetailsOBJ.getCreatedDate());
-
- benMapOBJ.setMBeneficiaryaddress(addressRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenAddressID(),
- benAdvanceSearchOBJ.getVanID()));
- benMapOBJ.setMBeneficiaryconsent(consentRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenConsentID(),
- benAdvanceSearchOBJ.getVanID()));
- benMapOBJ.setMBeneficiarycontact(contactRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenContactID(),
- benAdvanceSearchOBJ.getVanID()));
- benMapOBJ.setMBeneficiarydetail(benDetailsOBJ);
- benMapOBJ.setMBeneficiaryregidmapping(regIdRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenRegID(),
- benAdvanceSearchOBJ.getVanID()));
- benMapOBJ.setMBeneficiaryImage(imageRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenImageID(),
- benAdvanceSearchOBJ.getVanID()));
- benMapOBJ.setMBeneficiaryAccount(accountRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenAccountID(),
- benAdvanceSearchOBJ.getVanID()));
-
- benMapOBJ.setMBeneficiaryfamilymappings(
- familyMapRepo.findByBenMapIdOrderByBenFamilyMapIdAsc(benAdvanceSearchOBJ.getVanSerialNo()));
- benMapOBJ.setMBeneficiaryidentities(identityRepo.findByBenMapId(benAdvanceSearchOBJ.getVanSerialNo()));
- }
-
- return benMapOBJ;
- }
-
- private BigInteger getBigIntegerValueFromObject(Object value) {
- BigInteger ret = null;
- if (value != null) {
- if (value instanceof BigInteger) {
- ret = (BigInteger) value;
- } else if (value instanceof String) {
- ret = new BigInteger((String) value);
- } else if (value instanceof BigDecimal) {
- ret = ((BigDecimal) value).toBigInteger();
- } else if (value instanceof Number) {
- ret = BigInteger.valueOf(((Number) value).longValue());
- } else {
- throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
- + " into a BigInteger.");
- }
- } else
- throw new ClassCastException("given value is null");
- return ret;
- }
-
- /**
- * The following parameters can be changed/edited once created: - First Name -
- * Middle Name - Last Name - DOB/Age - Address (Current, Permanent, Emergency) -
- * Contact Numbers/Email Ids - Spouse Name - Preferred Num - Preferred SMS Num -
- * Email Id - Identity
- *
- * Following changes need Additional Authorization - First Name - Middle Name -
- * Last Name - Father Name - Spouse Name - Identity
- *
- * @param identity
- * @return
- * @throws MissingMandatoryFieldsException
- */
- public void editIdentity(IdentityEditDTO identity) throws MissingMandatoryFieldsException {
- logger.info("IdentityService.editIdentity - start");
- if (identity.getBeneficiaryRegId() == null && null == identity.getBeneficaryId()) {
- throw new MissingMandatoryFieldsException("Either of BeneficiaryID or Beneficiary Reg Id is mandatory.");
- }
-
- MBeneficiarymapping benMapping = mappingRepo.findByBenRegIdOrderByBenMapIdAsc(identity.getBeneficiaryRegId());
-
- // change in self details is implement here and other details here
- logger.debug("identity.getChangeInSelfDetails = " + identity.getChangeInSelfDetails());
- logger.debug("identity.getChangeInOtherDetails = " + identity.getChangeInOtherDetails());
- logger.debug("identity.getChangeInAssociations = " + identity.getChangeInAssociations());
- if (Boolean.TRUE.equals(identity.getChangeInSelfDetails())
- || Boolean.TRUE.equals(identity.getChangeInOtherDetails())
- || Boolean.TRUE.equals(identity.getChangeInAssociations())) {
-
- // MBeneficiarydetail mbDetl =
- // editMapper.identityEditDTOToMBeneficiarydetail(identity);
- // MBeneficiarydetail mbDetl =
- // convertIdentityEditDTOToMBeneficiarydetail(identity);
- /**
- * new logic for data sync, 26-09-2018
- */
- // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
- MBeneficiarydetail benDetails = detailRepo.findBenDetailsByVanSerialNoAndVanID(
- benMapping.getMBeneficiarydetail().getBeneficiaryDetailsId(), benMapping.getVanID());
- // next statement is new one, setting correct beneficiaryDetailsId
- if (benDetails != null) {
- // Create a new instance of MBeneficiarydetail or use the existing one
- MBeneficiarydetail mbDetl = convertIdentityEditDTOToMBeneficiarydetail(identity);
-
- // Set fields from the existing benDetails to mbDetl
- mbDetl.setBeneficiaryDetailsId(benDetails.getBeneficiaryDetailsId());
- if (benDetails.getFamilyId() != null)
- mbDetl.setFamilyId(benDetails.getFamilyId());
- if (benDetails.getHeadOfFamily_RelationID() != null)
- mbDetl.setHeadOfFamily_RelationID(benDetails.getHeadOfFamily_RelationID());
- if (benDetails.getHeadOfFamily_Relation() != null)
- mbDetl.setHeadOfFamily_Relation(benDetails.getHeadOfFamily_Relation());
- if (benDetails.getOther() != null)
- mbDetl.setOther(benDetails.getOther());
-
- // Extract and set extra fields
+
+ private static final Logger logger = LoggerFactory.getLogger(IdentityService.class);
+ public static final String CREATED_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
+ @Autowired
+ private DataSource dataSource;
+
+ private JdbcTemplate jdbcTemplate;
+
+ private JdbcTemplate getJdbcTemplate() {
+ return new JdbcTemplate(dataSource);
+
+ }
+
+ @Autowired
+ private RMNCHBeneficiaryDetailsRmnchRepo rMNCHBeneficiaryDetailsRmnchRepo;
+
+ @Autowired
+ private ElasticsearchService elasticsearchService;
+
+ @Autowired
+ private BeneficiaryElasticsearchIndexUpdater syncService;
+
+ @Autowired
+ IdentityMapper mapper;
+ @Autowired
+ IdentityEditMapper editMapper;
+ @Autowired
+ IdentitySearchMapper searchMapper;
+ @Autowired
+ private IdentityPartialMapper partialMapper;
+ @Autowired
+ BenAddressRepo addressRepo;
+ @Autowired
+ BenConsentRepo consentRepo;
+ @Autowired
+ BenContactRepo contactRepo;
+ @Autowired
+ BenDataAccessRepo accessRepo;
+ @Autowired
+ BenDetailRepo detailRepo;
+ @Autowired
+ BenFamilyMappingRepo familyMapRepo;
+ @Autowired
+ BenIdentityRepo identityRepo;
+ @Autowired
+ BenMappingRepo mappingRepo;
+ @Autowired
+ BenRegIdMappingRepo regIdRepo;
+ @Autowired
+ BenServiceMappingRepo serviceMapRepo;
+ @Autowired
+ MBeneficiaryAccountRepo accountRepo;
+ @Autowired
+ MBeneficiaryImageRepo imageRepo;
+ @Autowired
+ private BenIdImportMapper benIdImportMapper;
+ @Autowired
+ private V_BenAdvanceSearchRepo v_BenAdvanceSearchRepo;
+
+ @Value("${elasticsearch.enabled}")
+ private boolean esEnabled;
+
+ public void getBenAdress() {
+ logger.debug("Address count: " + addressRepo.count());
+ logger.debug(
+ "Address By Address: " + addressRepo.findByBenAddressIDOrderByBenAddressIDAsc(new BigInteger("12")));
+ logger.debug("Consent count: " + consentRepo.count());
+ logger.debug("Consent By Id: " + consentRepo.findByBenConsentIDOrderByBenConsentIDAsc(new BigInteger("12")));
+ logger.debug("Contact count: " + contactRepo.count());
+ logger.debug("Contact By Id: " + contactRepo.findByBenContactsIDOrderByBenContactsIDAsc(new BigInteger("12")));
+ logger.debug("Data Access count: " + accessRepo.count());
+ logger.debug("Data Access By Id: " + accessRepo.findByAccessIdOrderByAccessIdAsc(new BigInteger("12")));
+ logger.debug("Detail count: " + detailRepo.count());
+ logger.debug("Detail By Address: "
+ + detailRepo.findByBeneficiaryDetailsIdOrderByBeneficiaryDetailsIdAsc(new BigInteger("12")));
+ logger.debug("FamilyMap count: " + familyMapRepo.count());
+ logger.debug(
+ "FamilyMap By Id: " + familyMapRepo.findByBenFamilyMapIdOrderByBenFamilyMapIdAsc(new BigInteger("12")));
+ logger.debug("Identity count: " + identityRepo.count());
+ logger.debug("Identity By Id: " + identityRepo.findByBenIdentityId(new BigInteger("12")));
+ logger.debug("Mapping count: " + mappingRepo.count());
+ logger.debug("Mapping By Id: " + mappingRepo.findByBenMapIdOrderByBenMapIdAsc(new BigInteger("12")));
+ }
+
+ /**
+ *
+ * @param searchDTO
+ * @return
+ */
+ public List getBeneficiaries(IdentitySearchDTO searchDTO)
+ throws NoResultException, QueryTimeoutException, Exception {
+ List list = new ArrayList();
+
+ /**
+ * if beneficiary Id present
+ */
+ if (searchDTO.getBeneficiaryId() != null) {
+ logger.info("getting beneficiaries by ID for " + searchDTO.getBeneficiaryId());
+ return this.getBeneficiariesByBenId(searchDTO.getBeneficiaryId());
+ }
+
+ /**
+ * if beneficiary Reg Id present
+ */
+ if (searchDTO.getBeneficiaryRegId() != null) {
+ logger.info("getting beneficiaries by reg ID for " + searchDTO.getBeneficiaryRegId());
+ return this.getBeneficiariesByBenRegId(searchDTO.getBeneficiaryRegId());
+ }
+
+ /**
+ * if beneficiary Reg Id present
+ */
+ if (searchDTO.getContactNumber() != null) {
+ logger.info("getting beneficiaries by contact no for " + searchDTO.getContactNumber());
+ List list3 = this.getBeneficiariesByPhoneNum(searchDTO.getContactNumber());
+ if (!list3.isEmpty() && searchDTO.getIsD2D() != null && Boolean.TRUE.equals(searchDTO.getIsD2D())) {
+
+ for (int i = 0; i < list3.size(); i++) {
+ if (searchDTO.getFirstName() != null) {
+ if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
+ || list3.get(i).getBeneficiaryDetails().getFirstName() == null
+ || !list3.get(i).getBeneficiaryDetails().getFirstName()
+ .equalsIgnoreCase(searchDTO.getFirstName())) {
+ list3.remove(i);
+ i--;
+
+ continue;
+ }
+
+ }
+ if (searchDTO.getLastName() != null) {
+ if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
+ || list3.get(i).getBeneficiaryDetails().getLastName() == null
+ || !list3.get(i).getBeneficiaryDetails().getLastName()
+ .equalsIgnoreCase(searchDTO.getLastName())) {
+ list3.remove(i);
+ i--;
+
+ continue;
+ }
+ }
+
+ if (searchDTO.getGenderId() != null) {
+ if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
+ || list3.get(i).getBeneficiaryDetails().getGenderId() == null || !list3.get(i)
+ .getBeneficiaryDetails().getGenderId().equals(searchDTO.getGenderId())) {
+
+ list3.remove(i);
+ i--;
+ continue;
+ }
+ }
+ if (searchDTO.getHouseHoldID() != null) {
+ if (list3.get(i) == null || list3.get(i).getBeneficiaryDetails() == null
+ || list3.get(i).getBeneficiaryDetails().getHouseHoldID() == null || !list3.get(i)
+ .getBeneficiaryDetails().getHouseHoldID().equals(searchDTO.getHouseHoldID())) {
+
+ list3.remove(i);
+ i--;
+ continue;
+ }
+ }
+
+ if (searchDTO.getCurrentAddress().getStateId() != null) {
+ if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
+ || list3.get(i).getCurrentAddress().getStateId() == null
+ || !list3.get(i).getCurrentAddress().getStateId()
+ .equals(searchDTO.getCurrentAddress().getStateId())) {
+
+ list3.remove(i);
+ i--;
+ continue;
+ }
+ }
+
+ if (searchDTO.getCurrentAddress().getDistrictId() != null) {
+ if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
+ || list3.get(i).getCurrentAddress().getDistrictId() == null
+ || !list3.get(i).getCurrentAddress().getDistrictId()
+ .equals(searchDTO.getCurrentAddress().getDistrictId())) {
+
+ list3.remove(i);
+ i--;
+ continue;
+ }
+ }
+
+ if (searchDTO.getCurrentAddress().getVillageId() != null) {
+ if (list3.get(i) == null || list3.get(i).getCurrentAddress() == null
+ || list3.get(i).getCurrentAddress().getVillageId() == null
+ || !list3.get(i).getCurrentAddress().getVillageId()
+ .equals(searchDTO.getCurrentAddress().getVillageId())) {
+
+ list3.remove(i);
+ i--;
+ continue;
+ }
+ }
+
+ }
+ }
+ return list3;
+ }
+
+ /**
+ * New logic for advance search, 03-10-2018
+ */
+ List tmpList = mappingRepo.dynamicFilterSearchNew(searchDTO);
+ for (VBenAdvanceSearch obj : tmpList) {
+ list.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew1(obj)));
+ logger.debug("benMapId: " + obj.getBenMapID());
+ }
+ /**
+ * End
+ */
+
+ return list;
+ }
+
+ public List getBeneficiarieswithES(IdentitySearchDTO searchDTO)
+ throws NoResultException, QueryTimeoutException, Exception {
+ List list = new ArrayList();
+ // if beneficiary Id present
+ if (searchDTO.getBeneficiaryId() != null) {
+ logger.info("getting beneficiaries by ID for " + searchDTO.getBeneficiaryId());
+ return this.getBeneficiariesByBenId(searchDTO.getBeneficiaryId());
+ }
+
+ // if beneficiary Reg Id present
+ if (searchDTO.getBeneficiaryRegId() != null) {
+ logger.info("getting beneficiaries by reg ID for " + searchDTO.getBeneficiaryRegId());
+ return this.getBeneficiariesByBenRegId(searchDTO.getBeneficiaryRegId());
+ }
+
+ // if beneficiary Reg Id present
+ if (searchDTO.getContactNumber() != null) {
+ logger.info("getting beneficiaries by contact no for " + searchDTO.getContactNumber());
+ List list3 = this.getBeneficiariesByPhoneNum(searchDTO.getContactNumber());
+ if (!list3.isEmpty() && searchDTO.getIsD2D() != null && Boolean.TRUE.equals(searchDTO.getIsD2D())) {
+ list3 = applyD2DFilters(list3, searchDTO);
+ }
+ return list3;
+ }
+
+ // Advanced search from database
+ List tmpList = mappingRepo.dynamicFilterSearchNew(searchDTO);
+ for (VBenAdvanceSearch obj : tmpList) {
+ list.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew1(obj)));
+ logger.debug("benMapId: " + obj.getBenMapID());
+ }
+
+ return list;
+ }
+
+ /**
+ * Check if search has multiple criteria (for advanced search)
+ */
+ private boolean hasMultipleCriteria(IdentitySearchDTO searchDTO) {
+ int criteriaCount = 0;
+
+ if (searchDTO.getFirstName() != null && !searchDTO.getFirstName().trim().isEmpty()) {
+ criteriaCount++;
+ }
+ if (searchDTO.getLastName() != null && !searchDTO.getLastName().trim().isEmpty()) {
+ criteriaCount++;
+ }
+ if (searchDTO.getContactNumber() != null && !searchDTO.getContactNumber().trim().isEmpty()) {
+ criteriaCount++;
+ }
+
+ return criteriaCount >= 2;
+ }
+
+ /**
+ * Enrich Elasticsearch results with complete data from database ES returns
+ * only basic fields, fetch complete data from DB
+ */
+ private List enrichBeneficiariesFromDatabase(List esResults) {
+ List enrichedList = new ArrayList<>();
+
+ for (BeneficiariesDTO esResult : esResults) {
+ try {
+ if (esResult.getBenRegId() != null) {
+ // Fetch complete data from database
+ List fullData = this.getBeneficiariesByBenRegId(esResult.getBenRegId());
+ if (!fullData.isEmpty()) {
+ enrichedList.add(fullData.get(0));
+ } else {
+ // If not in DB anymore, return ES data
+ enrichedList.add(esResult);
+ }
+ }
+ } catch (Exception e) {
+ logger.error("Error enriching beneficiary data: {}", e.getMessage());
+ // Return ES data if enrichment fails
+ enrichedList.add(esResult);
+ }
+ }
+
+ return enrichedList;
+ }
+
+ /**
+ * Apply D2D filters to search results
+ */
+ private List applyD2DFilters(List list, IdentitySearchDTO searchDTO) {
+ List filtered = new ArrayList<>();
+
+ for (BeneficiariesDTO dto : list) {
+ boolean matches = true;
+
+ if (searchDTO.getFirstName() != null) {
+ if (dto.getBeneficiaryDetails() == null
+ || dto.getBeneficiaryDetails().getFirstName() == null
+ || !dto.getBeneficiaryDetails().getFirstName().equalsIgnoreCase(searchDTO.getFirstName())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getLastName() != null) {
+ if (dto.getBeneficiaryDetails() == null
+ || dto.getBeneficiaryDetails().getLastName() == null
+ || !dto.getBeneficiaryDetails().getLastName().equalsIgnoreCase(searchDTO.getLastName())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getGenderId() != null) {
+ if (dto.getBeneficiaryDetails() == null
+ || dto.getBeneficiaryDetails().getGenderId() == null
+ || !dto.getBeneficiaryDetails().getGenderId().equals(searchDTO.getGenderId())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getHouseHoldID() != null) {
+ if (dto.getBeneficiaryDetails() == null
+ || dto.getBeneficiaryDetails().getHouseHoldID() == null
+ || !dto.getBeneficiaryDetails().getHouseHoldID().equals(searchDTO.getHouseHoldID())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getCurrentAddress() != null && searchDTO.getCurrentAddress().getStateId() != null) {
+ if (dto.getCurrentAddress() == null
+ || dto.getCurrentAddress().getStateId() == null
+ || !dto.getCurrentAddress().getStateId().equals(searchDTO.getCurrentAddress().getStateId())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getCurrentAddress() != null && searchDTO.getCurrentAddress().getDistrictId() != null) {
+ if (dto.getCurrentAddress() == null
+ || dto.getCurrentAddress().getDistrictId() == null
+ || !dto.getCurrentAddress().getDistrictId().equals(searchDTO.getCurrentAddress().getDistrictId())) {
+ matches = false;
+ }
+ }
+
+ if (matches && searchDTO.getCurrentAddress() != null && searchDTO.getCurrentAddress().getVillageId() != null) {
+ if (dto.getCurrentAddress() == null
+ || dto.getCurrentAddress().getVillageId() == null
+ || !dto.getCurrentAddress().getVillageId().equals(searchDTO.getCurrentAddress().getVillageId())) {
+ matches = false;
+ }
+ }
+
+ if (matches) {
+ filtered.add(dto);
+ }
+ }
+
+ return filtered;
+ }
+
+ /**
+ *
+ * Check which parameters available Get BenMapID based on the parameter/set
+ * of parameters Use BenMapID to retrieve all data for a Beneficiary
+ *
+ * @param benId
+ * @return
+ */
+ public List getBeneficiariesByBenId(BigInteger benId)
+ throws NoResultException, QueryTimeoutException, Exception {
+ logger.info("IdentityService.getBeneficiariesByBenId - start, beneficiaryID : " + benId);
+ List list = new ArrayList();
+
+ MBeneficiaryregidmapping regId = regIdRepo.findByBeneficiaryID(benId);
+ if (regId != null && regId.getBenRegId() != null) {
+ List benMapObjArr = mappingRepo.getBenMappingByRegID(regId.getBenRegId());
+
+ // new logic, 27-08-2018
+ if (benMapObjArr != null && benMapObjArr.size() > 0) {
+ MBeneficiarymapping benMap = this.getBeneficiariesDTONew(benMapObjArr.get(0));
+ list.add(this.getBeneficiariesDTO(benMap));
+ }
+ }
+ logger.info("benMap size " + (list.size() == 0 ? "No Beneficiary Found" : list.size()));
+ // end new logic
+
+ logger.info("IdentityService.getBeneficiariesByBenId - end - beneficiaryID : " + benId);
+
+ return list;
+ }
+
+ /**
+ *
+ * @param BenRegId
+ * @return
+ */
+ public List getBeneficiariesByBenRegId(BigInteger benRegId)
+ throws NoResultException, QueryTimeoutException, Exception {
+ List list = new ArrayList();
+ logger.info("IdentityService.getBeneficiariesByBenRegId - start for benRegId " + benRegId);
+ try {
+ // new logic, 27-09-2018
+ List benMapObjArr = mappingRepo.getBenMappingByRegID(benRegId);
+
+ // new logic, 27-08-2018
+ if (benMapObjArr != null && !benMapObjArr.isEmpty()) {
+ MBeneficiarymapping benMap = this.getBeneficiariesDTONew(benMapObjArr.get(0));
+ list.add(this.getBeneficiariesDTO(benMap));
+ }
+ logger.info("benMap size" + (list.isEmpty() ? "No Beneficiary Found" : list.size()));
+ // end new logic
+
+ logger.info("IdentityService.getBeneficiariesByBenRegId - end for benRegId " + benRegId);
+ } catch (Exception e) {
+ logger.error("error in beneficiary search for beneficiary reg id : " + benRegId + " error : "
+ + e.getLocalizedMessage());
+ }
+
+ return list;
+ }
+
+ /**
+ *
+ * Check which parameters available Get BenMapID based on the parameter/set
+ * of parameters Use BenMapID to retrieve all data for a Beneficiary
+ *
+ * @param phoneNum
+ * @return
+ */
+ public List getBeneficiariesByPhoneNum(String phoneNum)
+ throws NoResultException, QueryTimeoutException {
+ // new logic, 27-09-2018
+ List list = new ArrayList<>();
+
+ try {
+ List benContact = contactRepo.findByAnyPhoneNum(phoneNum);
+
+ logger.info(benContact.size() + " contacts found for phone number " + phoneNum);
+
+ List benMapObjArr = new ArrayList<>();
+
+ for (MBeneficiarycontact benContactOBJ : benContact) {
+ benMapObjArr.addAll(mappingRepo.getBenMappingByBenContactIdListNew(benContactOBJ.getVanSerialNo(),
+ benContactOBJ.getVanID()));
+ }
+
+ for (Object[] benMapOBJ : benMapObjArr) {
+ list.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
+ }
+
+ } catch (Exception e) {
+ logger.error(
+ "error in beneficiary search for phone no : " + phoneNum + " error : " + e.getLocalizedMessage());
+ }
+
+ logger.info("IdentityService.getBeneficiariesByPhoneNum - end");
+ // end
+ return list;
+ }
+
+
+/**
+ * Advanced search using Elasticsearch with fallback to database
+ */
+public Map advancedSearchBeneficiariesES(
+ String firstName, String middleName, String lastName, Integer genderId, java.util.Date dob,
+ Integer stateId, Integer districtId, Integer blockId, Integer villageId,
+ String fatherName, String spouseName, String maritalStatus, String phoneNumber,
+ String beneficiaryId, String healthId, String aadharNo,
+ Integer userId, String auth, Boolean is1097) throws Exception {
+
+ try {
+ logger.info("IdentityService.advancedSearchBeneficiariesES - start");
+ logger.info("ES enabled: {}", esEnabled);
+
+ Map response = new HashMap<>();
+
+ if (esEnabled) {
+ logger.info("Using Elasticsearch for advanced search");
+
+ // Call Elasticsearch service
+ List> esResults = elasticsearchService.advancedSearch(
+ firstName, middleName, lastName, genderId, dob, stateId, districtId,
+ blockId, villageId, fatherName, spouseName, maritalStatus, phoneNumber,
+ beneficiaryId, healthId, aadharNo, userId
+ );
+
+ response.put("data", esResults);
+ response.put("count", esResults.size());
+ response.put("source", "elasticsearch");
+
+ logger.info("ES returned {} results", esResults.size());
+
+ } else {
+ logger.info("ES disabled - using database for advanced search");
+
+ IdentitySearchDTO searchDTO = new IdentitySearchDTO();
+ searchDTO.setFirstName(firstName);
+ searchDTO.setLastName(lastName);
+ searchDTO.setGenderId(genderId);
+ searchDTO.setDob(dob != null ? new Timestamp(dob.getTime()) : null);
+ searchDTO.setFatherName(fatherName);
+ searchDTO.setSpouseName(spouseName);
+ searchDTO.setContactNumber(phoneNumber);
+
+ if (beneficiaryId != null && !beneficiaryId.trim().isEmpty()) {
+ try {
+ searchDTO.setBeneficiaryId(new BigInteger(beneficiaryId));
+ } catch (NumberFormatException e) {
+ logger.warn("Invalid beneficiaryId format: {}", beneficiaryId);
+ }
+ }
+
+ if (stateId != null || districtId != null || blockId != null || villageId != null) {
+ Address addressDTO = new Address();
+ addressDTO.setStateId(stateId);
+ addressDTO.setDistrictId(districtId);
+ addressDTO.setSubDistrictId(blockId);
+ addressDTO.setVillageId(villageId);
+ searchDTO.setCurrentAddress(addressDTO);
+ }
+
+ List dbResults = this.getBeneficiaries(searchDTO);
+
+ List> formattedResults = dbResults.stream()
+ .map(this::convertBeneficiaryDTOToMap)
+ .collect(Collectors.toList());
+
+ response.put("data", formattedResults);
+ response.put("count", formattedResults.size());
+ response.put("source", "database");
+
+ logger.info("Database returned {} results", formattedResults.size());
+ }
+
+ logger.info("IdentityService.advancedSearchBeneficiariesES - end");
+ return response;
+
+ } catch (Exception e) {
+ logger.error("Advanced search failed: {}", e.getMessage(), e);
+ throw new Exception("Error in advanced search: " + e.getMessage(), e);
+ }
+}/**
+ * Convert BeneficiariesDTO to Map format
+ */
+private Map convertBeneficiaryDTOToMap(BeneficiariesDTO dto) {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(dto);
+ return mapper.readValue(json, Map.class);
+ } catch (Exception e) {
+ logger.error("Error converting DTO to map", e);
+ return new HashMap<>();
+ }
+}
+
+
+
+ /**
+ * *
+ *
+ * Search beneficiary by healthID / ABHA address
+ *
+ * @param healthID
+ * @return
+ * @throws NoResultException
+ * @throws QueryTimeoutException
+ * @throws Exception
+ */
+ public List getBeneficiaryByHealthIDAbhaAddress(String healthID)
+ throws NoResultException, QueryTimeoutException, Exception {
+ List beneficiaryList = new ArrayList<>();
+ try {
+ List regIDList = v_BenAdvanceSearchRepo.getBenRegIDByHealthIDAbhaAddress(healthID);
+ if (regIDList != null && !regIDList.isEmpty()) {
+ for (BigInteger benRegID : regIDList) {
+ if (benRegID != null) {
+ List searchList = this.getBeneficiariesByBenRegId(benRegID);
+ beneficiaryList.addAll(searchList);
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("error in beneficiary search for health ID / ABHA Address : " + healthID + " error : "
+ + e.getLocalizedMessage());
+ }
+ return beneficiaryList;
+ }
+
+ /**
+ * *
+ *
+ * Search beneficiary by healthIDNo / ABHA ID No
+ *
+ * @param healthIDNo
+ * @return
+ * @throws NoResultException
+ * @throws QueryTimeoutException
+ * @throws Exception
+ */
+ public List getBeneficiaryByHealthIDNoAbhaIdNo(String healthIDNo)
+ throws NoResultException, QueryTimeoutException, Exception {
+ List beneficiaryList = new ArrayList<>();
+ try {
+ List regIDList = v_BenAdvanceSearchRepo.getBenRegIDByHealthIDNoAbhaIdNo(healthIDNo);
+ if (regIDList != null && !regIDList.isEmpty()) {
+ for (BigInteger benRegID : regIDList) {
+ if (benRegID != null) {
+ List searchList = this.getBeneficiariesByBenRegId(benRegID);
+ beneficiaryList.addAll(searchList);
+ }
+ }
+ }
+ } catch (Exception e) {
+ logger.error("error in beneficiary search for health ID No / ABHA ID No : " + healthIDNo + " error : "
+ + e.getLocalizedMessage());
+ }
+ return beneficiaryList;
+ }
+
+ public List searhBeneficiaryByFamilyId(String familyId)
+ throws NoResultException, QueryTimeoutException {
+ List beneficiaryList = new ArrayList<>();
+ try {
+
+ // find benmap ids
+ List benMapObjArr = null;
+ List benDetailsVanSerialNoList = new ArrayList<>();
+ int vanID = 0;
+
+ List benDetailsList = detailRepo.searchByFamilyId(familyId);
+
+ if (benDetailsList == null || benDetailsList.isEmpty()) {
+ return beneficiaryList;
+ }else {
+ // considering as of now family creation is possible through facility modules
+ // only
+ vanID = benDetailsList.get(0).getVanID();
+
+ for (MBeneficiarydetail benDetails : benDetailsList) {
+ benDetailsVanSerialNoList.add(benDetails.getVanSerialNo());
+ }
+
+ benMapObjArr = mappingRepo.getBenMappingByBenDetailsIds(benDetailsVanSerialNoList, vanID);
+
+ for (Object[] benMapOBJ : benMapObjArr) {
+ beneficiaryList.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
+ }
+
+ }
+
+ } catch (Exception e) {
+ logger.error(
+ "error in beneficiary search for familyId : " + familyId + " error : " + e.getLocalizedMessage());
+ }
+ return beneficiaryList;
+ }
+
+ public List searchBeneficiaryByVillageIdAndLastModifyDate(List villageIDs,
+ Timestamp lastModifiedDate) {
+
+ List beneficiaryList = new ArrayList<>();
+ try {
+ // find benmap ids
+ List benMappingsList = mappingRepo
+ .findByBeneficiaryDetailsByVillageIDAndLastModifyDate(villageIDs, lastModifiedDate);
+ if (benMappingsList != null && !benMappingsList.isEmpty()) {
+ for (MBeneficiarymapping benMapOBJ : benMappingsList) {
+ beneficiaryList.add(this.getBeneficiariesDTO(benMapOBJ));
+ }
+ }
+
+ } catch (Exception e) {
+ logger.error("error in beneficiary search to sync to CHO App with villageIDs: {} ",
+ villageIDs + " error : " + e.getLocalizedMessage());
+ }
+ return beneficiaryList;
+ }
+
+ public Long countBeneficiaryByVillageIdAndLastModifyDate(List villageIDs, Timestamp lastModifiedDate) {
+ Long beneficiaryCount = 0L;
+ try {
+ beneficiaryCount = mappingRepo.getBeneficiaryCountsByVillageIDAndLastModifyDate(villageIDs,
+ lastModifiedDate);
+ } catch (Exception e) {
+ logger.error("error in getting beneficiary count to sync to CHO App with villageIDs: {},error :{} ",
+ villageIDs, e.getLocalizedMessage());
+ }
+ return beneficiaryCount;
+ }
+
+ public List searhBeneficiaryByGovIdentity(String identity)
+ throws NoResultException, QueryTimeoutException {
+ List beneficiaryList = new ArrayList<>();
+ try {
+
+ List benMapObjArr = new ArrayList<>();
+
+ // find identity no
+ List benIdentityList = identityRepo.searchByIdentityNo(identity);
+
+ // find benmap ids
+ if (benIdentityList == null || benIdentityList.isEmpty()) {
+ return beneficiaryList;
+ }else {
+ for (MBeneficiaryidentity identityObj : benIdentityList) {
+ benMapObjArr.addAll(
+ mappingRepo.getBenMappingByVanSerialNo(identityObj.getBenMapId(), identityObj.getVanID()));
+ }
+
+ for (Object[] benMapOBJ : benMapObjArr) {
+ beneficiaryList.add(this.getBeneficiariesDTO(this.getBeneficiariesDTONew(benMapOBJ)));
+ }
+
+ }
+
+ } catch (Exception e) {
+ logger.error("error in beneficiary search for gov identity : " + identity + " error : "
+ + e.getLocalizedMessage());
+ }
+ return beneficiaryList;
+ }
+
+ private MBeneficiarymapping getBeneficiariesDTONew(Object[] benMapArr) {
+ MBeneficiarymapping mapping = new MBeneficiarymapping();
+ if (benMapArr != null && benMapArr.length == 12 && benMapArr[8] != null && benMapArr[9] != null) {
+ mapping.setBenMapId(getBigIntegerValueFromObject(benMapArr[0]));
+ mapping.setCreatedBy(String.valueOf(benMapArr[10]));
+ mapping.setCreatedDate((Timestamp) benMapArr[11]);
+ mapping = mappingRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[9]), (Integer) benMapArr[8]);
+ MBeneficiaryaddress address = addressRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[1]), (Integer) benMapArr[8]);
+ MBeneficiaryconsent consent = consentRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[2]), (Integer) benMapArr[8]);
+ MBeneficiarycontact contact = contactRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[3]), (Integer) benMapArr[8]);
+ MBeneficiarydetail details = detailRepo.getWith_vanSerialNo_vanID(getBigIntegerValueFromObject(benMapArr[4]), (Integer) benMapArr[8]);
+ MBeneficiaryregidmapping regidmapping = regIdRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[5]), (Integer) benMapArr[8]);
+ MBeneficiaryAccount account = accountRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[7]), (Integer) benMapArr[8]);
+ MBeneficiaryImage image = imageRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[6]), (Integer) benMapArr[8]);
+ List servicemap = serviceMapRepo.getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
+ List identity = identityRepo.findByBenMapIdAndVanID(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
+ List familymapping = familyMapRepo.findByBenMapIdAndVanIDOrderByBenFamilyMapIdAsc(getBigIntegerValueFromObject(benMapArr[0]), (Integer) benMapArr[8]);
+
+ mapping.setMBeneficiaryaddress(address);
+ mapping.setMBeneficiaryconsent(consent);
+ mapping.setMBeneficiarycontact(contact);
+ mapping.setMBeneficiarydetail(details);
+ mapping.setMBeneficiaryfamilymappings(familymapping);
+ mapping.setMBeneficiaryidentities(identity);
+ mapping.setMBeneficiaryImage(image);
+ mapping.setMBeneficiaryregidmapping(regidmapping);
+ mapping.setMBeneficiaryservicemappings(servicemap);
+ mapping.setMBeneficiaryAccount(account);
+ //benMapOBJ = mappingRepo.getMapping(getBigIntegerValueFromObject(benMapArr[9]), (Integer) benMapArr[8]);
+
+ BigInteger benRegId = new BigInteger(benMapArr[5].toString());
+ RMNCHBeneficiaryDetailsRmnch obj = rMNCHBeneficiaryDetailsRmnchRepo
+ .getByRegID(benRegId);
+
+ if (obj != null) {
+ if (obj.getHouseoldId() != null) {
+ mapping.setHouseHoldID(obj.getHouseoldId());
+ }
+ if (obj.getGuidelineId() != null) {
+ mapping.setGuideLineID(obj.getGuidelineId());
+ }
+ if (obj.getRchid() != null) {
+ mapping.setRchID(obj.getRchid());
+ }
+ }
+
+ }
+ return mapping;
+ }
+
+ private MBeneficiarymapping getBeneficiariesDTONewPartial(Object[] benMapArr) {
+ MBeneficiarymapping benMapOBJ = new MBeneficiarymapping();
+
+ benMapOBJ.setBenMapId(getBigIntegerValueFromObject(benMapArr[0]));
+ benMapOBJ.setCreatedBy(String.valueOf(benMapArr[10]));
+ benMapOBJ.setCreatedDate((Timestamp) benMapArr[11]);
+
+ if (benMapArr.length == 12 && benMapArr[8] != null && benMapArr[9] != null) {
+
+ benMapOBJ.setMBeneficiarydetail(detailRepo
+ .getWith_vanSerialNo_vanID(getBigIntegerValueFromObject(benMapArr[4]), (Integer) benMapArr[8]));
+ benMapOBJ.setMBeneficiaryregidmapping(regIdRepo
+ .getWithVanSerialNoVanID(getBigIntegerValueFromObject(benMapArr[5]), (Integer) benMapArr[8]));
+ }
+ return benMapOBJ;
+ }
+
+ // 03-10-2018
+ // get ben mapping object from v_benadvancesearch
+ private MBeneficiarymapping getBeneficiariesDTONew1(VBenAdvanceSearch benAdvanceSearchOBJ) {
+ MBeneficiarymapping benMapOBJ = new MBeneficiarymapping();
+
+ // for createdBy & createdDate
+ if (benAdvanceSearchOBJ != null) {
+ MBeneficiarydetail benDetailsOBJ = detailRepo
+ .getWith_vanSerialNo_vanID(benAdvanceSearchOBJ.getBenDetailsID(), benAdvanceSearchOBJ.getVanID());
+
+ if (benAdvanceSearchOBJ.getHouseHoldID() != null) {
+ benMapOBJ.setHouseHoldID(benAdvanceSearchOBJ.getHouseHoldID());
+ }
+ if (benAdvanceSearchOBJ.getGuideLineID() != null) {
+ benMapOBJ.setGuideLineID(benAdvanceSearchOBJ.getGuideLineID());
+ }
+ if (benAdvanceSearchOBJ.getRchID() != null) {
+ benMapOBJ.setRchID(benAdvanceSearchOBJ.getRchID());
+ }
+
+ benMapOBJ.setBenMapId(benAdvanceSearchOBJ.getBenMapID());
+ benMapOBJ.setCreatedBy(benDetailsOBJ.getCreatedBy());
+ benMapOBJ.setCreatedDate(benDetailsOBJ.getCreatedDate());
+
+ benMapOBJ.setMBeneficiaryaddress(addressRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenAddressID(),
+ benAdvanceSearchOBJ.getVanID()));
+ benMapOBJ.setMBeneficiaryconsent(consentRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenConsentID(),
+ benAdvanceSearchOBJ.getVanID()));
+ benMapOBJ.setMBeneficiarycontact(contactRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenContactID(),
+ benAdvanceSearchOBJ.getVanID()));
+ benMapOBJ.setMBeneficiarydetail(benDetailsOBJ);
+ benMapOBJ.setMBeneficiaryregidmapping(regIdRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenRegID(),
+ benAdvanceSearchOBJ.getVanID()));
+ benMapOBJ.setMBeneficiaryImage(imageRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenImageID(),
+ benAdvanceSearchOBJ.getVanID()));
+ benMapOBJ.setMBeneficiaryAccount(accountRepo.getWithVanSerialNoVanID(benAdvanceSearchOBJ.getBenAccountID(),
+ benAdvanceSearchOBJ.getVanID()));
+
+ benMapOBJ.setMBeneficiaryfamilymappings(
+ familyMapRepo.findByBenMapIdOrderByBenFamilyMapIdAsc(benAdvanceSearchOBJ.getVanSerialNo()));
+ benMapOBJ.setMBeneficiaryidentities(identityRepo.findByBenMapId(benAdvanceSearchOBJ.getVanSerialNo()));
+ }
+
+ return benMapOBJ;
+ }
+
+ private BigInteger getBigIntegerValueFromObject(Object value) {
+ BigInteger ret = null;
+ if (value != null) {
+ if (value instanceof BigInteger) {
+ ret = (BigInteger) value;
+ } else if (value instanceof String) {
+ ret = new BigInteger((String) value);
+ } else if (value instanceof BigDecimal) {
+ ret = ((BigDecimal) value).toBigInteger();
+ } else if (value instanceof Number) {
+ ret = BigInteger.valueOf(((Number) value).longValue());
+ } else {
+ throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
+ + " into a BigInteger.");
+ }
+ } else {
+ throw new ClassCastException("given value is null");
+ }
+ return ret;
+ }
+
+ /**
+ * The following parameters can be changed/edited once created: - First Name
+ * - Middle Name - Last Name - DOB/Age - Address (Current, Permanent,
+ * Emergency) - Contact Numbers/Email Ids - Spouse Name - Preferred Num -
+ * Preferred SMS Num - Email Id - Identity
+ *
+ * Following changes need Additional Authorization - First Name - Middle
+ * Name - Last Name - Father Name - Spouse Name - Identity
+ *
+ * @param identity
+ * @return
+ * @throws MissingMandatoryFieldsException
+ */
+ public void editIdentity(IdentityEditDTO identity) throws MissingMandatoryFieldsException {
+ logger.info("IdentityService.editIdentity - start");
+ if (identity.getBeneficiaryRegId() == null && null == identity.getBeneficaryId()) {
+ throw new MissingMandatoryFieldsException("Either of BeneficiaryID or Beneficiary Reg Id is mandatory.");
+ }
+
+ MBeneficiarymapping benMapping = mappingRepo.findByBenRegIdOrderByBenMapIdAsc(identity.getBeneficiaryRegId());
+
+ // Track if ANY change happened (determines if ES sync is needed)
+ boolean isDataUpdate = false;
+
+ // change in self details is implement here and other details here
+ logger.debug("identity.getChangeInSelfDetails = " + identity.getChangeInSelfDetails());
+ logger.debug("identity.getChangeInOtherDetails = " + identity.getChangeInOtherDetails());
+ logger.debug("identity.getChangeInAssociations = " + identity.getChangeInAssociations());
+ if (Boolean.TRUE.equals(identity.getChangeInSelfDetails())
+ || Boolean.TRUE.equals(identity.getChangeInOtherDetails())
+ || Boolean.TRUE.equals(identity.getChangeInAssociations())) {
+
+ // MBeneficiarydetail mbDetl =
+ // editMapper.identityEditDTOToMBeneficiarydetail(identity);
+ // MBeneficiarydetail mbDetl =
+ // convertIdentityEditDTOToMBeneficiarydetail(identity);
+ /**
+ * new logic for data sync, 26-09-2018
+ */
+ // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
+ MBeneficiarydetail benDetails = detailRepo.findBenDetailsByVanSerialNoAndVanID(
+ benMapping.getMBeneficiarydetail().getBeneficiaryDetailsId(), benMapping.getVanID());
+ // next statement is new one, setting correct beneficiaryDetailsId
+ if (benDetails != null) {
+ // Create a new instance of MBeneficiarydetail or use the existing one
+ MBeneficiarydetail mbDetl = convertIdentityEditDTOToMBeneficiarydetail(identity);
+
+ // Set fields from the existing benDetails to mbDetl
+ mbDetl.setBeneficiaryDetailsId(benDetails.getBeneficiaryDetailsId());
+ if (benDetails.getFamilyId() != null) {
+ mbDetl.setFamilyId(benDetails.getFamilyId());
+ }
+ if (benDetails.getHeadOfFamily_RelationID() != null) {
+ mbDetl.setHeadOfFamily_RelationID(benDetails.getHeadOfFamily_RelationID());
+ }
+ if (benDetails.getHeadOfFamily_Relation() != null) {
+ mbDetl.setHeadOfFamily_Relation(benDetails.getHeadOfFamily_Relation());
+ }
+ if (benDetails.getOther() != null) {
+ mbDetl.setOther(benDetails.getOther());
+ }
+
+ // Extract and set extra fields
// String identityJson = new Gson().toJson(json);
// JsonObject identityJsonObject = new Gson().fromJson(identityJson, JsonObject.class);
// JsonObject otherFieldsJson = new JsonObject();
@@ -778,1052 +1061,1106 @@ public void editIdentity(IdentityEditDTO identity) throws MissingMandatoryFields
// }
// }
// String otherFieldsJsonString = otherFieldsJson.toString();
- // mbDetl.setOtherFields(benDetails.getOtherFields());
- logger.debug("Beneficiary details to update = " + new OutputMapper().gson().toJson(mbDetl));
- if (benDetails.getEmergencyRegistration() != null && benDetails.getEmergencyRegistration()) {
- mbDetl.setEmergencyRegistration(true);
- } else {
- mbDetl.setEmergencyRegistration(false);
- }
- detailRepo.save(mbDetl);
- }
- }
- // edition in current emergency and permanent is implement below
- logger.debug("identity.getChangeInAddress = " + identity.getChangeInAddress());
- if (Boolean.TRUE.equals(identity.getChangeInAddress())) {
-
- MBeneficiaryaddress mbAddr = editMapper.identityEditDTOToMBeneficiaryaddress(identity);
-
- /**
- * new logic for data sync, 26-09-2018
- */
-
- // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
- BigInteger benAddressID = addressRepo.findIdByVanSerialNoAndVanID(
- benMapping.getMBeneficiaryaddress().getBenAddressID(), benMapping.getVanID());
- // next statement is new one, setting correct beneficiaryDetailsId
- if (benAddressID != null)
- mbAddr.setBenAddressID(benAddressID);
- else
- throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
-
- /**
- * END
- */
-
- logger.debug("Beneficiary address to update = " + OutputMapper.gson().toJson(mbAddr));
- addressRepo.save(mbAddr);
- }
-
- // edition in beneficiary contacts is updated here
- logger.debug("identity.getChangeInContacts = " + identity.getChangeInContacts());
- if (Boolean.TRUE.equals(identity.getChangeInContacts())) {
-
- MBeneficiarycontact benCon = editMapper.identityEdiDTOToMBeneficiarycontact(identity);
-
- /**
- * new logic for data sync, 26-09-2018
- */
-
- // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
- BigInteger benContactsID = contactRepo.findIdByVanSerialNoAndVanID(
- benMapping.getMBeneficiarycontact().getBenContactsID(), benMapping.getVanID());
- // next statement is new one, setting correct beneficiaryDetailsId
- if (benContactsID != null)
- benCon.setBenContactsID(benContactsID);
- else
- throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
-
- /**
- * END
- */
-
- logger.debug("Beneficiary contact to update = " + OutputMapper.gson().toJson(benCon));
- contactRepo.save(benCon);
- }
-
- // change in identities are added here
- logger.debug("identity.getChangeInIdentities = " + identity.getChangeInIdentities());
- if (Boolean.TRUE.equals(identity.getChangeInIdentities())) {
-
- MBeneficiaryidentity beneficiaryidentity;
- List identities = editMapper
- .identityEditDTOListToMBeneficiaryidentityList(identity.getIdentities());
- logger.debug("identities to upsert = " + OutputMapper.gson().toJson(identities));
-
- // new logic for getting beneficiary identities, 26-09-2018
- List idList = identityRepo.findByBenMapId(benMapping.getVanSerialNo());
-
- logger.debug("existing identies = " + OutputMapper.gson().toJson(idList));
- ListIterator iterator = identities.listIterator();
- int index = 0;
- while (iterator.hasNext()) {
- beneficiaryidentity = iterator.next();
-
- // new logic, 26-09-2018
- beneficiaryidentity.setBenMapId(benMapping.getVanSerialNo());
- logger.debug("Beneficiary identity to update = " + OutputMapper.gson().toJson(beneficiaryidentity));
- if (index < idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
- beneficiaryidentity.setBenIdentityId(idList.get(index).getBenIdentityId());
- }
-
- // new code to set vanID & parkingPlaceID for new record, 26-09-2018
- if (index >= idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
- beneficiaryidentity.setVanID(benMapping.getVanID());
- beneficiaryidentity.setParkingPlaceID(benMapping.getParkingPlaceID());
- }
-
- // new logic, 26-09-2018
- MBeneficiaryidentity m = identityRepo.save(beneficiaryidentity);
-
- // new code, update van serial no for new entry, 26-09-2018
- if (index >= idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
- identityRepo.updateVanSerialNo(m.getBenIdentityId());
- }
-
- index++;
- }
- }
-
- // family detail changes are performing here
- logger.debug("identity.getChangeInFamilyDetails = " + identity.getChangeInFamilyDetails());
- if (Boolean.TRUE.equals(identity.getChangeInFamilyDetails())) {
- List fbMaps = editMapper
- .identityEditDTOListToMBeneficiaryfamilymappingList(identity.getBenFamilyDTOs());
-
- logger.debug("family map to upsert = " + OutputMapper.gson().toJson(fbMaps));
-
- // new logic, 26-09-2018
- List fmList = familyMapRepo
- .findByBenMapIdOrderByBenFamilyMapIdAsc(benMapping.getVanSerialNo());
-
- logger.debug("family map stored = " + OutputMapper.gson().toJson(fmList));
- ListIterator iterator = fbMaps.listIterator();
- MBeneficiaryfamilymapping familymapping;
- int index = 0;
- while (iterator.hasNext()) {
-
- familymapping = iterator.next();
- // new logic, 26-09-2018
- familymapping.setBenMapId(benMapping.getVanSerialNo());
-
- logger.debug("family mapping to update = " + OutputMapper.gson().toJson(familymapping));
- if (index < fmList.size()) {
- familymapping.setBenFamilyMapId(fmList.get(index).getBenFamilyMapId());
- }
-
- if (index >= fmList.size() && familymapping.getBenFamilyMapId() == null) {
- familymapping.setVanID(benMapping.getVanID());
- familymapping.setParkingPlaceID(benMapping.getParkingPlaceID());
- }
-
- // new logic, 26-09-2018
- MBeneficiaryfamilymapping m = familyMapRepo.save(familymapping);
-
- // new code, update van serial no for new entry, 26-09-2018
- if (familymapping.getBenFamilyMapId() == null) {
- familyMapRepo.updateVanSerialNo(m.getBenFamilyMapId());
- }
-
- index++;
- }
- }
-
- // start
- // Feature used in outreach
- if (Boolean.TRUE.equals(identity.getChangeInBankDetails())) {
- MBeneficiaryAccount beneficiaryAccount = editMapper.identityEditDTOToMBeneficiaryAccount(identity);
-
- /**
- * new logic for data sync, 26-09-2018
- */
- // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
- BigInteger benAccountID = accountRepo.findIdByVanSerialNoAndVanID(
- benMapping.getMBeneficiaryAccount().getBenAccountID(), benMapping.getVanID());
- // next statement is new one, setting correct beneficiaryDetailsId
- if (benAccountID != null)
- beneficiaryAccount.setBenAccountID(benAccountID);
- else
- throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
-
- /**
- * END
- */
-
- logger.debug("Account to upsert = " + OutputMapper.gson().toJson(beneficiaryAccount));
- accountRepo.save(beneficiaryAccount);
- }
-
- if (Boolean.TRUE.equals(identity.getChangeInBenImage())) {
- MBeneficiaryImage beneficiaryImage = editMapper.identityEditDTOToMBeneficiaryImage(identity);
-
- /**
- * new logic for data sync, 26-09-2018
- */
- // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
- BigInteger benImageId = imageRepo.findIdByVanSerialNoAndVanID(
- benMapping.getMBeneficiaryImage().getBenImageId(), benMapping.getVanID());
- // next statement is new one, setting correct beneficiaryDetailsId
- if (benImageId != null)
- beneficiaryImage.setBenImageId(benImageId);
- else
- throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
-
- /**
- * END
- */
-
- logger.debug("Image to upsert = " + OutputMapper.gson().toJson(beneficiaryImage));
- beneficiaryImage.setProcessed("N");
- imageRepo.save(beneficiaryImage);
- }
-
- logger.info("IdentityService.editIdentity - end. id = " + benMapping.getBenMapId());
- }
-
- private MBeneficiarydetail convertIdentityEditDTOToMBeneficiarydetail(IdentityEditDTO dto) {
- MBeneficiarydetail beneficiarydetail = new MBeneficiarydetail();
-
- // Directly set values without using @Mapping
- beneficiarydetail.setAreaId(dto.getAreaId());
- beneficiarydetail.setBeneficiaryRegID(dto.getBeneficiaryRegId());
- beneficiarydetail.setCommunity(dto.getCommunity());
- beneficiarydetail.setLiteracyStatus(dto.getLiteracyStatus());
- beneficiarydetail.setCommunityId(dto.getCommunityId());
- beneficiarydetail.setDob(dto.getDob());
- beneficiarydetail.setEducation(dto.getEducation());
- beneficiarydetail.setEducationId(dto.getEducationId());
- beneficiarydetail.setHealthCareWorkerId(dto.getHealthCareWorkerId());
- beneficiarydetail.setHealthCareWorker(dto.getHealthCareWorker());
- beneficiarydetail.setFatherName(dto.getFatherName());
- beneficiarydetail.setMotherName(dto.getMotherName());
- beneficiarydetail.setFirstName(dto.getFirstName());
- beneficiarydetail.setGender(dto.getGender());
- beneficiarydetail.setGenderId(dto.getGenderId());
- beneficiarydetail.setIncomeStatusId(dto.getIncomeStatusId());
- beneficiarydetail.setIncomeStatus(dto.getIncomeStatus());
- beneficiarydetail.setMonthlyFamilyIncome(dto.getMonthlyFamilyIncome());
- if (dto.getLastName() != null)
- beneficiarydetail.setLastName(dto.getLastName());
- beneficiarydetail.setMaritalStatusId(dto.getMaritalStatusId());
- beneficiarydetail.setMaritalStatus(dto.getMaritalStatus());
- beneficiarydetail.setMiddleName(dto.getMiddleName());
- beneficiarydetail.setOccupation(dto.getOccupationName());
- beneficiarydetail.setOccupationId(dto.getOccupationId());
- beneficiarydetail.setPhcId(dto.getPhcId());
- beneficiarydetail.setPlaceOfWork(dto.getPlaceOfWork());
- beneficiarydetail.setPreferredLanguage(dto.getPreferredLanguage());
- beneficiarydetail.setReligion(dto.getReligion());
- if (dto.getReligionId() != null)
- beneficiarydetail.setReligionId(BigInteger.valueOf(dto.getReligionId()));
- beneficiarydetail.setRemarks(dto.getRemarks());
- beneficiarydetail.setServicePointId(dto.getServicePointId());
- beneficiarydetail.setSourceOfInfo(dto.getSourceOfInfo());
- beneficiarydetail.setSpouseName(dto.getSpouseName());
- beneficiarydetail.setStatus(dto.getStatus());
- beneficiarydetail.setTitle(dto.getTitle());
- beneficiarydetail.setTitleId(dto.getTitleId());
- beneficiarydetail.setZoneId(dto.getZoneId());
- beneficiarydetail.setCreatedBy(dto.getAgentName());
- beneficiarydetail.setCreatedDate(dto.getEventTypeDate());
- beneficiarydetail.setIsHIVPositive(MBeneficiarydetail.setIsHIVPositive(dto.getIsHIVPositive()));
- beneficiarydetail.setAgeAtMarriage(
- MBeneficiarydetail.getAgeAtMarriageCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
- beneficiarydetail.setMarriageDate(
- MBeneficiarydetail.getMarriageDateCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
- if(dto.getOtherFields() != null)
- beneficiarydetail.setOtherFields(dto.getOtherFields());
-
- return beneficiarydetail;
- }
-
- /**
- * @param identity
- * @return
- */
-
- ArrayDeque queue = new ArrayDeque<>();
-
- public BeneficiaryCreateResp createIdentity(IdentityDTO identity) {
- logger.info("IdentityService.createIdentity - start");
-
- List list = null;
- MBeneficiaryregidmapping regMap = null;
- synchronized (queue) {
- if (queue.isEmpty()) {
- logger.info("fetching 10000 rows");
- list = regIdRepo.findTop10000ByProvisionedAndReserved(false, false);
- logger.info("Adding SynchronousQueue start-- ");
- for (MBeneficiaryregidmapping map : list) {
- queue.add(map);
- }
- logger.info("Adding SynchronousQueue end-- ");
- }
- regMap = queue.removeFirst();
- }
- regMap.setReserved(true);
- if (regMap.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- regMap.setCreatedDate(ts);
- }
-
- regIdRepo.save(regMap);
-
- regMap.setProvisioned(true);
-
- logger.info("IdentityService.createIdentity - saving Address");
- ObjectMapper objectMapper = new ObjectMapper();
- MBeneficiaryaddress mAddr = identityDTOToMBeneficiaryaddress(identity);
- // MBeneficiaryaddress mAddr1 =
- // mapper.identityDTOToMBeneficiaryaddress(identity);
- logger.info("identity.getIsPermAddrSameAsCurrAddr = " + identity.getIsPermAddrSameAsCurrAddr());
- if (Boolean.TRUE.equals(identity.getIsPermAddrSameAsCurrAddr())) {
- logger.debug("identity.getCurrentAddress = " + identity.getCurrentAddress());
- mAddr.setPermanentAddress(identity.getCurrentAddress());
- }
-
- logger.info("identity.getIsPermAddrSameAsEmerAddr = " + identity.getIsPermAddrSameAsEmerAddr());
- if (Boolean.TRUE.equals(identity.getIsPermAddrSameAsEmerAddr())) {
- logger.debug("identity.getEmergencyAddress = " + identity.getEmergencyAddress());
- mAddr.setPermanentAddress(identity.getEmergencyAddress());
- }
-
- logger.info("identity.getIsEmerAddrSameAsCurrAddr = " + identity.getIsEmerAddrSameAsCurrAddr());
- if (Boolean.TRUE.equals(identity.getIsEmerAddrSameAsCurrAddr())) {
- logger.debug("identity.getCurrentAddress = " + identity.getCurrentAddress());
- mAddr.setEmergencyAddress(identity.getCurrentAddress());
- }
-
- logger.info("identity.getIsEmerAddrSameAsPermAddr = " + identity.getIsEmerAddrSameAsPermAddr());
- if (Boolean.TRUE.equals(identity.getIsEmerAddrSameAsPermAddr())) {
- logger.debug("identity.getPermanentAddress = " + identity.getPermanentAddress());
- mAddr.setEmergencyAddress(identity.getPermanentAddress());
- }
- if (mAddr.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- mAddr.setCreatedDate(ts);
- }
-
- mAddr = addressRepo.save(mAddr);
- logger.info("IdentityService.createIdentity - Address saved - id = " + mAddr.getBenAddressID());
-
- // Update van serial no for data sync
- addressRepo.updateVanSerialNo(mAddr.getBenAddressID());
-
- MBeneficiaryconsent mConsnt = mapper.identityDTOToDefaultMBeneficiaryconsent(identity, true, false);
- logger.info("IdentityService.createIdentity - saving Consent");
- if (mConsnt.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- mConsnt.setCreatedDate(ts);
- }
- mConsnt = consentRepo.save(mConsnt);
- logger.info("IdentityService.createIdentity - Consent saved - id = " + mConsnt.getBenConsentID());
-
- // Update van serial no for data sync
- consentRepo.updateVanSerialNo(mConsnt.getBenConsentID());
-
- logger.info("IdentityService.createIdentity - saving Contacts");
- MBeneficiarycontact mContc = identityDTOToMBeneficiarycontact(identity);
-
- if (mContc.getEmergencyContactNum() != null) {
- mContc.setEmergencyContactNum(cleanPhoneNumber(mContc.getEmergencyContactNum()));
- }
+ // mbDetl.setOtherFields(benDetails.getOtherFields());
+ logger.debug("Beneficiary details to update = " + new OutputMapper().gson().toJson(mbDetl));
+ if (benDetails.getEmergencyRegistration() != null && benDetails.getEmergencyRegistration()) {
+ mbDetl.setEmergencyRegistration(true);
+ } else {
+ mbDetl.setEmergencyRegistration(false);
+ }
+ detailRepo.save(mbDetl);
+ isDataUpdate = true;
+ }
+ }
+ // edition in current emergency and permanent is implement below
+ logger.debug("identity.getChangeInAddress = " + identity.getChangeInAddress());
+ if (Boolean.TRUE.equals(identity.getChangeInAddress())) {
+
+ MBeneficiaryaddress mbAddr = editMapper.identityEditDTOToMBeneficiaryaddress(identity);
+
+ /**
+ * new logic for data sync, 26-09-2018
+ */
+ // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
+ BigInteger benAddressID = addressRepo.findIdByVanSerialNoAndVanID(
+ benMapping.getMBeneficiaryaddress().getBenAddressID(), benMapping.getVanID());
+ // next statement is new one, setting correct beneficiaryDetailsId
+ if (benAddressID != null) {
+ mbAddr.setBenAddressID(benAddressID);
+ }else {
+ throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
+ }
+
+ /**
+ * END
+ */
+ logger.debug("Beneficiary address to update = " + OutputMapper.gson().toJson(mbAddr));
+ addressRepo.save(mbAddr);
+ isDataUpdate = true;
+ }
+
+ // edition in beneficiary contacts is updated here
+ logger.debug("identity.getChangeInContacts = " + identity.getChangeInContacts());
+ if (Boolean.TRUE.equals(identity.getChangeInContacts())) {
+
+ MBeneficiarycontact benCon = editMapper.identityEdiDTOToMBeneficiarycontact(identity);
+
+ /**
+ * new logic for data sync, 26-09-2018
+ */
+ // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
+ BigInteger benContactsID = contactRepo.findIdByVanSerialNoAndVanID(
+ benMapping.getMBeneficiarycontact().getBenContactsID(), benMapping.getVanID());
+ // next statement is new one, setting correct beneficiaryDetailsId
+ if (benContactsID != null) {
+ benCon.setBenContactsID(benContactsID);
+ }else {
+ throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
+ }
+
+ /**
+ * END
+ */
+ logger.debug("Beneficiary contact to update = " + OutputMapper.gson().toJson(benCon));
+ contactRepo.save(benCon);
+ isDataUpdate = true;
+
+ }
+
+ // change in identities are added here
+ logger.debug("identity.getChangeInIdentities = " + identity.getChangeInIdentities());
+ if (Boolean.TRUE.equals(identity.getChangeInIdentities())) {
+
+ MBeneficiaryidentity beneficiaryidentity;
+ List identities = editMapper
+ .identityEditDTOListToMBeneficiaryidentityList(identity.getIdentities());
+ logger.debug("identities to upsert = " + OutputMapper.gson().toJson(identities));
+
+ // new logic for getting beneficiary identities, 26-09-2018
+ List idList = identityRepo.findByBenMapId(benMapping.getVanSerialNo());
+
+ logger.debug("existing identies = " + OutputMapper.gson().toJson(idList));
+ ListIterator iterator = identities.listIterator();
+ int index = 0;
+ while (iterator.hasNext()) {
+ beneficiaryidentity = iterator.next();
+
+ // new logic, 26-09-2018
+ beneficiaryidentity.setBenMapId(benMapping.getVanSerialNo());
+ logger.debug("Beneficiary identity to update = " + OutputMapper.gson().toJson(beneficiaryidentity));
+ if (index < idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
+ beneficiaryidentity.setBenIdentityId(idList.get(index).getBenIdentityId());
+ }
+
+ // new code to set vanID & parkingPlaceID for new record, 26-09-2018
+ if (index >= idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
+ beneficiaryidentity.setVanID(benMapping.getVanID());
+ beneficiaryidentity.setParkingPlaceID(benMapping.getParkingPlaceID());
+ }
+
+ // new logic, 26-09-2018
+ MBeneficiaryidentity m = identityRepo.save(beneficiaryidentity);
+
+ // new code, update van serial no for new entry, 26-09-2018
+ if (index >= idList.size() && beneficiaryidentity.getBenIdentityId() == null) {
+ identityRepo.updateVanSerialNo(m.getBenIdentityId());
+ }
+
+ index++;
+ isDataUpdate = true;
+
+ }
+ }
+
+ // family detail changes are performing here
+ logger.debug("identity.getChangeInFamilyDetails = " + identity.getChangeInFamilyDetails());
+ if (Boolean.TRUE.equals(identity.getChangeInFamilyDetails())) {
+ List fbMaps = editMapper
+ .identityEditDTOListToMBeneficiaryfamilymappingList(identity.getBenFamilyDTOs());
+
+ logger.debug("family map to upsert = " + OutputMapper.gson().toJson(fbMaps));
+
+ // new logic, 26-09-2018
+ List fmList = familyMapRepo
+ .findByBenMapIdOrderByBenFamilyMapIdAsc(benMapping.getVanSerialNo());
+
+ logger.debug("family map stored = " + OutputMapper.gson().toJson(fmList));
+ ListIterator iterator = fbMaps.listIterator();
+ MBeneficiaryfamilymapping familymapping;
+ int index = 0;
+ while (iterator.hasNext()) {
+
+ familymapping = iterator.next();
+ // new logic, 26-09-2018
+ familymapping.setBenMapId(benMapping.getVanSerialNo());
+
+ logger.debug("family mapping to update = " + OutputMapper.gson().toJson(familymapping));
+ if (index < fmList.size()) {
+ familymapping.setBenFamilyMapId(fmList.get(index).getBenFamilyMapId());
+ }
+
+ if (index >= fmList.size() && familymapping.getBenFamilyMapId() == null) {
+ familymapping.setVanID(benMapping.getVanID());
+ familymapping.setParkingPlaceID(benMapping.getParkingPlaceID());
+ }
+
+ // new logic, 26-09-2018
+ MBeneficiaryfamilymapping m = familyMapRepo.save(familymapping);
+
+ // new code, update van serial no for new entry, 26-09-2018
+ if (familymapping.getBenFamilyMapId() == null) {
+ familyMapRepo.updateVanSerialNo(m.getBenFamilyMapId());
+ }
+
+ index++;
+ isDataUpdate = true;
+
+ }
+ }
+
+ // start
+ // Feature used in outreach
+ if (Boolean.TRUE.equals(identity.getChangeInBankDetails())) {
+ MBeneficiaryAccount beneficiaryAccount = editMapper.identityEditDTOToMBeneficiaryAccount(identity);
+
+ /**
+ * new logic for data sync, 26-09-2018
+ */
+ // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
+ BigInteger benAccountID = accountRepo.findIdByVanSerialNoAndVanID(
+ benMapping.getMBeneficiaryAccount().getBenAccountID(), benMapping.getVanID());
+ // next statement is new one, setting correct beneficiaryDetailsId
+ if (benAccountID != null) {
+ beneficiaryAccount.setBenAccountID(benAccountID);
+ }else {
+ throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
+ }
+
+ /**
+ * END
+ */
+ logger.debug("Account to upsert = " + OutputMapper.gson().toJson(beneficiaryAccount));
+ accountRepo.save(beneficiaryAccount);
+ isDataUpdate = true;
+
+ }
+
+ if (Boolean.TRUE.equals(identity.getChangeInBenImage())) {
+ MBeneficiaryImage beneficiaryImage = editMapper.identityEditDTOToMBeneficiaryImage(identity);
+
+ /**
+ * new logic for data sync, 26-09-2018
+ */
+ // getting correct beneficiaryDetailsId by passing vanSerialNo & vanID
+ BigInteger benImageId = imageRepo.findIdByVanSerialNoAndVanID(
+ benMapping.getMBeneficiaryImage().getBenImageId(), benMapping.getVanID());
+ // next statement is new one, setting correct beneficiaryDetailsId
+ if (benImageId != null) {
+ beneficiaryImage.setBenImageId(benImageId);
+ }else {
+ throw new MissingMandatoryFieldsException("Either of vanSerialNO or vanID is missing.");
+ }
+
+ /**
+ * END
+ */
+ logger.debug("Image to upsert = " + OutputMapper.gson().toJson(beneficiaryImage));
+ beneficiaryImage.setProcessed("N");
+ imageRepo.save(beneficiaryImage);
+ isDataUpdate = true;
+
+ }
+
+ // Trigger async sync to Elasticsearch
+ if (isDataUpdate && identity.getBeneficiaryRegId() != null) {
+ logger.info("Triggering Elasticsearch sync for benRegId: {}", identity.getBeneficiaryRegId());
+ syncService.syncBeneficiaryAsync(identity.getBeneficiaryRegId());
+ }
- if (mContc.getPhoneNum1() != null) {
- mContc.setPhoneNum1(cleanPhoneNumber(mContc.getPhoneNum1()));
+ logger.info("IdentityService.editIdentity - end. id = " + benMapping.getBenMapId());
+}
+
+
+
+ private MBeneficiarydetail convertIdentityEditDTOToMBeneficiarydetail(IdentityEditDTO dto) {
+ MBeneficiarydetail beneficiarydetail = new MBeneficiarydetail();
+
+ // Directly set values without using @Mapping
+ beneficiarydetail.setAreaId(dto.getAreaId());
+ beneficiarydetail.setBeneficiaryRegID(dto.getBeneficiaryRegId());
+ beneficiarydetail.setCommunity(dto.getCommunity());
+ beneficiarydetail.setLiteracyStatus(dto.getLiteracyStatus());
+ beneficiarydetail.setCommunityId(dto.getCommunityId());
+ beneficiarydetail.setDob(dto.getDob());
+ beneficiarydetail.setEducation(dto.getEducation());
+ beneficiarydetail.setEducationId(dto.getEducationId());
+ beneficiarydetail.setHealthCareWorkerId(dto.getHealthCareWorkerId());
+ beneficiarydetail.setHealthCareWorker(dto.getHealthCareWorker());
+ beneficiarydetail.setFatherName(dto.getFatherName());
+ beneficiarydetail.setMotherName(dto.getMotherName());
+ beneficiarydetail.setFirstName(dto.getFirstName());
+ beneficiarydetail.setGender(dto.getGender());
+ beneficiarydetail.setGenderId(dto.getGenderId());
+ beneficiarydetail.setIncomeStatusId(dto.getIncomeStatusId());
+ beneficiarydetail.setIncomeStatus(dto.getIncomeStatus());
+ beneficiarydetail.setMonthlyFamilyIncome(dto.getMonthlyFamilyIncome());
+ if (dto.getLastName() != null) {
+ beneficiarydetail.setLastName(dto.getLastName());
+ }
+ beneficiarydetail.setMaritalStatusId(dto.getMaritalStatusId());
+ beneficiarydetail.setMaritalStatus(dto.getMaritalStatus());
+ beneficiarydetail.setMiddleName(dto.getMiddleName());
+ beneficiarydetail.setOccupation(dto.getOccupationName());
+ beneficiarydetail.setOccupationId(dto.getOccupationId());
+ beneficiarydetail.setPhcId(dto.getPhcId());
+ beneficiarydetail.setPlaceOfWork(dto.getPlaceOfWork());
+ beneficiarydetail.setPreferredLanguage(dto.getPreferredLanguage());
+ beneficiarydetail.setReligion(dto.getReligion());
+ if (dto.getReligionId() != null) {
+ beneficiarydetail.setReligionId(BigInteger.valueOf(dto.getReligionId()));
+ }
+ beneficiarydetail.setRemarks(dto.getRemarks());
+ beneficiarydetail.setServicePointId(dto.getServicePointId());
+ beneficiarydetail.setSourceOfInfo(dto.getSourceOfInfo());
+ beneficiarydetail.setSpouseName(dto.getSpouseName());
+ beneficiarydetail.setStatus(dto.getStatus());
+ beneficiarydetail.setTitle(dto.getTitle());
+ beneficiarydetail.setTitleId(dto.getTitleId());
+ beneficiarydetail.setZoneId(dto.getZoneId());
+ beneficiarydetail.setCreatedBy(dto.getAgentName());
+ beneficiarydetail.setCreatedDate(dto.getEventTypeDate());
+ beneficiarydetail.setIsHIVPositive(MBeneficiarydetail.setIsHIVPositive(dto.getIsHIVPositive()));
+ beneficiarydetail.setAgeAtMarriage(
+ MBeneficiarydetail.getAgeAtMarriageCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
+ beneficiarydetail.setMarriageDate(
+ MBeneficiarydetail.getMarriageDateCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
+ if (dto.getOtherFields() != null) {
+ beneficiarydetail.setOtherFields(dto.getOtherFields());
+ }
+
+ return beneficiarydetail;
}
-
- if (mContc.getPhoneNum2() != null) {
- mContc.setPhoneNum2(cleanPhoneNumber(mContc.getPhoneNum2()));
+
+ /**
+ * @param identity
+ * @return
+ */
+ ArrayDeque queue = new ArrayDeque<>();
+
+ public BeneficiaryCreateResp createIdentity(IdentityDTO identity) {
+ logger.info("IdentityService.createIdentity - start");
+
+ List list = null;
+ MBeneficiaryregidmapping regMap = null;
+ synchronized (queue) {
+ if (queue.isEmpty()) {
+ logger.info("fetching 10000 rows");
+ list = regIdRepo.findTop10000ByProvisionedAndReserved(false, false);
+ logger.info("Adding SynchronousQueue start-- ");
+ for (MBeneficiaryregidmapping map : list) {
+ queue.add(map);
+ }
+ logger.info("Adding SynchronousQueue end-- ");
+ }
+ regMap = queue.removeFirst();
+ }
+ regMap.setReserved(true);
+ if (regMap.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ regMap.setCreatedDate(ts);
+ }
+
+ regIdRepo.save(regMap);
+
+ regMap.setProvisioned(true);
+
+ logger.info("IdentityService.createIdentity - saving Address");
+ ObjectMapper objectMapper = new ObjectMapper();
+ MBeneficiaryaddress mAddr = identityDTOToMBeneficiaryaddress(identity);
+ // MBeneficiaryaddress mAddr1 =
+ // mapper.identityDTOToMBeneficiaryaddress(identity);
+ logger.info("identity.getIsPermAddrSameAsCurrAddr = " + identity.getIsPermAddrSameAsCurrAddr());
+ if (Boolean.TRUE.equals(identity.getIsPermAddrSameAsCurrAddr())) {
+ logger.debug("identity.getCurrentAddress = " + identity.getCurrentAddress());
+ mAddr.setPermanentAddress(identity.getCurrentAddress());
+ }
+
+ logger.info("identity.getIsPermAddrSameAsEmerAddr = " + identity.getIsPermAddrSameAsEmerAddr());
+ if (Boolean.TRUE.equals(identity.getIsPermAddrSameAsEmerAddr())) {
+ logger.debug("identity.getEmergencyAddress = " + identity.getEmergencyAddress());
+ mAddr.setPermanentAddress(identity.getEmergencyAddress());
+ }
+
+ logger.info("identity.getIsEmerAddrSameAsCurrAddr = " + identity.getIsEmerAddrSameAsCurrAddr());
+ if (Boolean.TRUE.equals(identity.getIsEmerAddrSameAsCurrAddr())) {
+ logger.debug("identity.getCurrentAddress = " + identity.getCurrentAddress());
+ mAddr.setEmergencyAddress(identity.getCurrentAddress());
+ }
+
+ logger.info("identity.getIsEmerAddrSameAsPermAddr = " + identity.getIsEmerAddrSameAsPermAddr());
+ if (Boolean.TRUE.equals(identity.getIsEmerAddrSameAsPermAddr())) {
+ logger.debug("identity.getPermanentAddress = " + identity.getPermanentAddress());
+ mAddr.setEmergencyAddress(identity.getPermanentAddress());
+ }
+ if (mAddr.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ mAddr.setCreatedDate(ts);
+ }
+
+ mAddr = addressRepo.save(mAddr);
+ logger.info("IdentityService.createIdentity - Address saved - id = " + mAddr.getBenAddressID());
+
+ // Update van serial no for data sync
+ addressRepo.updateVanSerialNo(mAddr.getBenAddressID());
+
+ MBeneficiaryconsent mConsnt = mapper.identityDTOToDefaultMBeneficiaryconsent(identity, true, false);
+ logger.info("IdentityService.createIdentity - saving Consent");
+ if (mConsnt.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ mConsnt.setCreatedDate(ts);
+ }
+ mConsnt = consentRepo.save(mConsnt);
+ logger.info("IdentityService.createIdentity - Consent saved - id = " + mConsnt.getBenConsentID());
+
+ // Update van serial no for data sync
+ consentRepo.updateVanSerialNo(mConsnt.getBenConsentID());
+
+ logger.info("IdentityService.createIdentity - saving Contacts");
+ MBeneficiarycontact mContc = identityDTOToMBeneficiarycontact(identity);
+
+ if (mContc.getEmergencyContactNum() != null) {
+ mContc.setEmergencyContactNum(cleanPhoneNumber(mContc.getEmergencyContactNum()));
+ }
+
+ if (mContc.getPhoneNum1() != null) {
+ mContc.setPhoneNum1(cleanPhoneNumber(mContc.getPhoneNum1()));
+ }
+
+ if (mContc.getPhoneNum2() != null) {
+ mContc.setPhoneNum2(cleanPhoneNumber(mContc.getPhoneNum2()));
+ }
+ if (mContc.getPhoneNum3() != null) {
+ mContc.setPhoneNum3(cleanPhoneNumber(mContc.getPhoneNum3()));
+ }
+
+ if (mContc.getPhoneNum4() != null) {
+ mContc.setPhoneNum4(cleanPhoneNumber(mContc.getPhoneNum4()));
+ }
+ if (mContc.getPhoneNum5() != null) {
+ mContc.setPhoneNum5(cleanPhoneNumber(mContc.getPhoneNum5()));
+ }
+ if (mContc.getPreferredSMSPhoneNum() != null) {
+ mContc.setPreferredSMSPhoneNum(cleanPhoneNumber(mContc.getPreferredSMSPhoneNum()));
+ }
+ if (mContc.getPreferredPhoneNum() != null) {
+ mContc.setPreferredPhoneNum(cleanPhoneNumber(mContc.getPreferredPhoneNum()));
+ }
+
+ // MBeneficiarycontact mContc =
+ // mapper.identityDTOToMBeneficiarycontact(identity);
+ if (mContc.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ mContc.setCreatedDate(ts);
+ }
+ mContc = contactRepo.save(mContc);
+ logger.info("IdentityService.createIdentity - Contacts saved - id = " + mContc.getBenContactsID());
+
+ // Update van serial no for data sync
+ contactRepo.updateVanSerialNo(mContc.getBenContactsID());
+
+ logger.info("IdentityService.createIdentity - saving Details");
+ // MBeneficiarydetail mDetl = mapper.identityDTOToMBeneficiarydetail(identity);
+ MBeneficiarydetail mDetl = convertIdentityDTOToMBeneficiarydetail(identity);
+
+ if (mDetl.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ mDetl.setCreatedDate(ts);
+ }
+ mDetl = detailRepo.save(mDetl);
+ logger.info("IdentityService.createIdentity - Details saved - id = " + mDetl.getBeneficiaryDetailsId());
+
+ // Update van serial no for data sync
+ detailRepo.updateVanSerialNo(mDetl.getBeneficiaryDetailsId());
+
+ MBeneficiaryAccount bankOBJ = mapper.identityDTOToMBeneficiaryAccount(identity);
+ if (bankOBJ.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ bankOBJ.setCreatedDate(ts);
+ }
+ bankOBJ = accountRepo.save(bankOBJ);
+ // Update van serial no for data sync
+ accountRepo.updateVanSerialNo(bankOBJ.getBenAccountID());
+
+ // MBeneficiaryImage benImageOBJ = mapper.identityDTOToMBeneficiaryImage(identity);
+ MBeneficiaryImage benImageOBJ = identityDTOToMBeneficiaryImage(identity);
+
+ if (benImageOBJ.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ benImageOBJ.setCreatedDate(ts);
+ }
+ benImageOBJ = imageRepo.save(benImageOBJ);
+
+ // Update van serial no for data sync
+ imageRepo.updateVanSerialNo(benImageOBJ.getBenImageId());
+
+ logger.info("IdentityService.createIdentity - saving Mapping");
+ MBeneficiarymapping benMapping = mapper.identityDTOToMBeneficiarymapping(identity);
+
+ benMapping.setMBeneficiarycontact(mContc);
+ benMapping.setMBeneficiaryaddress(mAddr);
+ benMapping.setMBeneficiaryconsent(mConsnt);
+ benMapping.setMBeneficiarydetail(mDetl);
+ benMapping.setMBeneficiaryregidmapping(regMap);
+ benMapping.setMBeneficiaryImage(benImageOBJ);
+ benMapping.setMBeneficiaryAccount(bankOBJ);
+
+ regMap.setProviderServiceMapID(identity.getProviderServiceMapId());
+ // added columns for data sync
+ // 17-09-2018
+ if (identity.getVanID() != null) {
+ regMap.setVanID(identity.getVanID());
+ }
+ if (identity.getParkingPlaceId() != null) {
+ regMap.setParkingPlaceID(identity.getParkingPlaceId());
+ }
+ regMap.setVanSerialNo(regMap.getBenRegId());
+ // END
+
+ regIdRepo.save(regMap);
+ if (benMapping.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ benMapping.setCreatedDate(ts);
+ }
+
+ if (identity.getBenFamilyDTOs().get(0).getVanID() != null) {
+ benMapping.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
+ }
+
+ benMapping = mappingRepo.save(benMapping);
+ // Update van serial no for data sync
+ mappingRepo.updateVanSerialNo(benMapping.getBenMapId());
+
+ final MBeneficiarymapping benMapping2 = benMapping;
+ logger.info("IdentityService.createIdentity - saving FamilyMaps");
+ List fIdenList = null;
+ List fList = null;
+
+ // new logic (18-09-2018, Neeraj kumar)
+ if (null != identity.getBenFamilyDTOs()) {
+ fIdenList = mapper.identityDTOListToMBeneficiaryfamilymappingList(identity.getBenFamilyDTOs());
+ if (fIdenList != null) {
+ for (MBeneficiaryfamilymapping bfMapping : fIdenList) {
+ bfMapping.setBenMapId(benMapping2.getBenMapId());
+
+ if (bfMapping.getVanID() == null && identity.getVanID() != null) {
+ bfMapping.setVanID(identity.getVanID());
+ }
+ if (bfMapping.getVanID() == null && identity.getBenFamilyDTOs().get(0).getVanID() != null) {
+ bfMapping.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
+ }
+
+ if (bfMapping.getParkingPlaceID() == null && identity.getParkingPlaceId() != null) {
+ bfMapping.setParkingPlaceID(identity.getParkingPlaceId());
+ }
+
+ if (bfMapping.getAssociatedBenRegId() == null) {
+ bfMapping.setAssociatedBenRegId(benMapping2.getBenRegId());
+ }
+ }
+ fList = (List) familyMapRepo.saveAll(fIdenList);
+ // Update van serial no for data sync
+ if (fList != null && !fList.isEmpty()) {
+ for (MBeneficiaryfamilymapping obj : fList) {
+ familyMapRepo.updateVanSerialNo(obj.getBenFamilyMapId());
+ }
+ }
+ }
+ }
+
+ logger.info("IdentityService.createIdentity - FamilyMap saved ");
+ logger.info("IdentityService.createIdentity - saving Service Map");
+ MBeneficiaryservicemapping sMap = mapper.identityDTOToMBeneficiaryservicemapping(identity);
+ sMap.setBenMapId(benMapping.getBenMapId());
+ if (sMap.getCreatedDate() == null) {
+ SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
+ String dateToStoreInDataBase = sdf.format(new Date());
+ Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
+ sMap.setCreatedDate(ts);
+ }
+ sMap = serviceMapRepo.save(sMap);
+ logger.info("IdentityService.createIdentity - ServiceMap saved - id = " + sMap.getBenServiceMapID());
+
+ // Update van serial no for data sync
+ serviceMapRepo.updateVanSerialNo(sMap.getBenServiceMapID());
+
+ List sList = new ArrayList<>();
+ sList.add(sMap);
+ logger.info("IdentityService.createIdentity - saving Identity");
+ List mIdenList2 = new ArrayList<>();
+ if (null != identity.getIdentities()) {
+ List mIdenList = mapper
+ .identityDTOListToMBeneficiaryidentityList(identity.getIdentities());
+ mIdenList.forEach(mIden -> {
+ mIden.setBenMapId(benMapping2.getBenMapId());
+ mIden.setCreatedBy(identity.getAgentName());
+ mIden.setCreatedDate(identity.getEventTypeDate());
+
+ // set new column(vanID, parkingPlaceID) value for data sync
+ if (identity.getVanID() != null) {
+ mIden.setVanID(identity.getVanID());
+ }
+ if (identity.getParkingPlaceId() != null) {
+ mIden.setParkingPlaceID(identity.getParkingPlaceId());
+ }
+
+ MBeneficiaryidentity m = identityRepo.save(mIden);
+
+ // Update van serial no for data sync
+ identityRepo.updateVanSerialNo(m.getBenIdentityId());
+
+ mIdenList2.add(m);
+ logger.info("IdentityService.createIdentity - Identity saved - id = " + m.getBenIdentityId());
+ });
+ }
+
+ // return partialMapper.mBeneficiarymappingToBeneficiaryCreateResp(benMapping);
+ logger.info("IdentityService.createIdentity - end. id = " + benMapping.getBenMapId());
+
+ BeneficiaryCreateResp response = partialMapper.mBeneficiarymappingToBeneficiaryCreateResp(benMapping);
+
+ // Trigger async sync to Elasticsearch
+ if (regMap != null && regMap.getBenRegId() != null) {
+ logger.info("Triggering Elasticsearch sync for benRegId: {}", regMap.getBenRegId());
+ syncService.syncBeneficiaryAsync(regMap.getBenRegId());
+ }
+
+ return response;
}
- if (mContc.getPhoneNum3() != null) {
- mContc.setPhoneNum3(cleanPhoneNumber(mContc.getPhoneNum3()));
+
+ private String cleanPhoneNumber(String phoneNumber) {
+ if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
+ return phoneNumber;
+ }
+
+ // Remove +91 prefix
+ String cleaned = phoneNumber.trim();
+ if (cleaned.startsWith("+91")) {
+ cleaned = cleaned.substring(3);
+ } else if (cleaned.startsWith("91") && cleaned.length() == 12) {
+ // Handle case where + is already removed but 91 remains
+ cleaned = cleaned.substring(2);
+ }
+
+ return cleaned.trim();
}
-
- if (mContc.getPhoneNum4() != null) {
- mContc.setPhoneNum4(cleanPhoneNumber(mContc.getPhoneNum4()));
+
+ private MBeneficiarydetail convertIdentityDTOToMBeneficiarydetail(IdentityDTO dto) {
+ MBeneficiarydetail beneficiarydetail = new MBeneficiarydetail();
+ beneficiarydetail.setAreaId(dto.getAreaId());
+ if (null != dto.getBeneficiaryRegId()) {
+ beneficiarydetail.setBeneficiaryRegID(BigInteger.valueOf(dto.getBeneficiaryRegId()));
+ }
+ beneficiarydetail.setCommunity(dto.getCommunity());
+ beneficiarydetail.setCommunityId(dto.getCommunityId());
+ beneficiarydetail.setDob(dto.getDob());
+ beneficiarydetail.setEducation(dto.getEducation());
+ beneficiarydetail.setEducationId(dto.getEducationId());
+ beneficiarydetail.setEmergencyRegistration(dto.getEmergencyRegistration());
+ beneficiarydetail.setHealthCareWorkerId(dto.getHealthCareWorkerId());
+ beneficiarydetail.setHealthCareWorker(dto.getHealthCareWorker());
+ beneficiarydetail.setFatherName(dto.getFatherName());
+ beneficiarydetail.setMotherName(dto.getMotherName());
+ beneficiarydetail.setFirstName(dto.getFirstName());
+ beneficiarydetail.setGender(dto.getGender());
+ beneficiarydetail.setGenderId(dto.getGenderId());
+ beneficiarydetail.setIncomeStatus(dto.getIncomeStatus());
+ beneficiarydetail.setMonthlyFamilyIncome(dto.getMonthlyFamilyIncome());
+ beneficiarydetail.setIncomeStatusId(dto.getIncomeStatusId());
+ beneficiarydetail.setLastName(dto.getLastName());
+ beneficiarydetail.setMaritalStatusId(dto.getMaritalStatusId());
+ beneficiarydetail.setMaritalStatus(dto.getMaritalStatus());
+ beneficiarydetail.setMiddleName(dto.getMiddleName());
+ beneficiarydetail.setOccupation(dto.getOccupationName());
+ beneficiarydetail.setOccupationId(dto.getOccupationId());
+ beneficiarydetail.setPhcId(dto.getPhcId());
+ beneficiarydetail.setPlaceOfWork(dto.getPlaceOfWork());
+ beneficiarydetail.setPreferredLanguageId(dto.getPreferredLanguageId());
+ beneficiarydetail.setPreferredLanguage(dto.getPreferredLanguage());
+ beneficiarydetail.setReligion(dto.getReligion());
+ if (dto.getFaceEmbedding() != null) {
+ beneficiarydetail.setFaceEmbedding(dto.getFaceEmbedding().toString());
+ }
+ if (dto.getReligionId() != null) {
+ beneficiarydetail.setReligionId(BigInteger.valueOf(dto.getReligionId()));
+ }
+ beneficiarydetail.setRemarks(dto.getRemarks());
+ if (dto.getServicePointId() != null) {
+ beneficiarydetail.setServicePointId(BigInteger.valueOf(dto.getServicePointId()));
+ }
+ beneficiarydetail.setSourceOfInfo(dto.getSourceOfInfo());
+ beneficiarydetail.setSpouseName(dto.getSpouseName());
+ beneficiarydetail.setStatus(dto.getStatus());
+ beneficiarydetail.setTitle(dto.getTitle());
+ beneficiarydetail.setTitleId(dto.getTitleId());
+ beneficiarydetail.setZoneId(dto.getZoneId());
+ beneficiarydetail.setCreatedBy(dto.getAgentName());
+ beneficiarydetail.setCreatedDate(dto.getCreatedDate());
+ beneficiarydetail.setIsHIVPositive(MBeneficiarydetail.setIsHIVPositive(dto.getIsHIVPositive()));
+ beneficiarydetail.setAgeAtMarriage(
+ MBeneficiarydetail.getAgeAtMarriageCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
+ beneficiarydetail.setMarriageDate(
+ MBeneficiarydetail.getMarriageDateCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
+ beneficiarydetail.setVanID(dto.getVanID());
+ beneficiarydetail.setParkingPlaceID(dto.getParkingPlaceId());
+ if (dto.getOtherFields() != null) {
+ beneficiarydetail.setOtherFields(dto.getOtherFields());
+ }
+ if (dto.getLiteracyStatus() != null) {
+ beneficiarydetail.setLiteracyStatus(dto.getLiteracyStatus());
+ }
+ return beneficiarydetail;
}
- if (mContc.getPhoneNum5() != null) {
- mContc.setPhoneNum5(cleanPhoneNumber(mContc.getPhoneNum5()));
+
+ private MBeneficiaryImage identityDTOToMBeneficiaryImage(IdentityDTO identity) {
+ MBeneficiaryImage beneficiaryImage = new MBeneficiaryImage();
+
+ beneficiaryImage.setBenImage(identity.getBenImage());
+ beneficiaryImage.setCreatedBy(identity.getAgentName());
+ beneficiaryImage.setCreatedDate(identity.getCreatedDate());
+ if (identity.getVanID() != null) {
+ beneficiaryImage.setVanID(identity.getVanID());
+ }
+ if (identity.getBenFamilyDTOs() != null) {
+ beneficiaryImage.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
+ }
+
+ beneficiaryImage.setParkingPlaceID(identity.getParkingPlaceId());
+
+ return beneficiaryImage;
}
- if (mContc.getPreferredSMSPhoneNum() != null) {
- mContc.setPreferredSMSPhoneNum(cleanPhoneNumber(mContc.getPreferredSMSPhoneNum()));
- } if (mContc.getPreferredPhoneNum() != null) {
- mContc.setPreferredPhoneNum(cleanPhoneNumber(mContc.getPreferredPhoneNum()));
+
+ private MBeneficiarycontact identityDTOToMBeneficiarycontact(IdentityDTO dto) {
+ MBeneficiarycontact beneficiaryContact = new MBeneficiarycontact();
+ if (dto.getContact() != null) {
+ beneficiaryContact.setPreferredPhoneNum(dto.getContact().getPreferredPhoneNum());
+ beneficiaryContact.setPreferredPhoneTyp(dto.getContact().getPreferredPhoneTyp());
+ beneficiaryContact.setPreferredSMSPhoneNum(dto.getContact().getPreferredSMSPhoneNum());
+ beneficiaryContact.setPreferredSMSPhoneTyp(dto.getContact().getPreferredSMSPhoneTyp());
+ beneficiaryContact.setEmergencyContactNum(dto.getContact().getEmergencyContactNum());
+ beneficiaryContact.setPhoneNum1(dto.getContact().getPhoneNum1());
+ beneficiaryContact.setPhoneTyp1(dto.getContact().getPhoneTyp1());
+ beneficiaryContact.setPhoneNum2(dto.getContact().getPhoneNum2());
+ beneficiaryContact.setPhoneTyp2(dto.getContact().getPhoneTyp2());
+ beneficiaryContact.setPhoneNum3(dto.getContact().getPhoneNum3());
+ beneficiaryContact.setPhoneTyp3(dto.getContact().getPhoneTyp3());
+ beneficiaryContact.setPhoneNum4(dto.getContact().getPhoneNum4());
+ beneficiaryContact.setPhoneTyp4(dto.getContact().getPhoneTyp4());
+ beneficiaryContact.setPhoneNum5(dto.getContact().getPhoneNum5());
+ beneficiaryContact.setPhoneTyp5(dto.getContact().getPhoneTyp5());
+ }
+ beneficiaryContact.setEmailId(dto.getPreferredEmailId());
+ beneficiaryContact.setCreatedBy(dto.getAgentName());
+ beneficiaryContact.setCreatedDate(dto.getCreatedDate());
+ beneficiaryContact.setVanID(dto.getVanID());
+ beneficiaryContact.setParkingPlaceID(dto.getParkingPlaceId());
+ return beneficiaryContact;
}
-
-
-
-
- // MBeneficiarycontact mContc =
- // mapper.identityDTOToMBeneficiarycontact(identity);
- if (mContc.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- mContc.setCreatedDate(ts);
- }
- mContc = contactRepo.save(mContc);
- logger.info("IdentityService.createIdentity - Contacts saved - id = " + mContc.getBenContactsID());
-
- // Update van serial no for data sync
- contactRepo.updateVanSerialNo(mContc.getBenContactsID());
-
- logger.info("IdentityService.createIdentity - saving Details");
- // MBeneficiarydetail mDetl = mapper.identityDTOToMBeneficiarydetail(identity);
- MBeneficiarydetail mDetl = convertIdentityDTOToMBeneficiarydetail(identity);
-
- if (mDetl.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- mDetl.setCreatedDate(ts);
- }
- mDetl = detailRepo.save(mDetl);
- logger.info("IdentityService.createIdentity - Details saved - id = " + mDetl.getBeneficiaryDetailsId());
-
- // Update van serial no for data sync
- detailRepo.updateVanSerialNo(mDetl.getBeneficiaryDetailsId());
-
- MBeneficiaryAccount bankOBJ = mapper.identityDTOToMBeneficiaryAccount(identity);
- if (bankOBJ.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- bankOBJ.setCreatedDate(ts);
- }
- bankOBJ = accountRepo.save(bankOBJ);
- // Update van serial no for data sync
- accountRepo.updateVanSerialNo(bankOBJ.getBenAccountID());
-
- // MBeneficiaryImage benImageOBJ = mapper.identityDTOToMBeneficiaryImage(identity);
- MBeneficiaryImage benImageOBJ = identityDTOToMBeneficiaryImage(identity);
-
- if (benImageOBJ.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- benImageOBJ.setCreatedDate(ts);
- }
- benImageOBJ = imageRepo.save(benImageOBJ);
-
- // Update van serial no for data sync
- imageRepo.updateVanSerialNo(benImageOBJ.getBenImageId());
-
- logger.info("IdentityService.createIdentity - saving Mapping");
- MBeneficiarymapping benMapping = mapper.identityDTOToMBeneficiarymapping(identity);
-
- benMapping.setMBeneficiarycontact(mContc);
- benMapping.setMBeneficiaryaddress(mAddr);
- benMapping.setMBeneficiaryconsent(mConsnt);
- benMapping.setMBeneficiarydetail(mDetl);
- benMapping.setMBeneficiaryregidmapping(regMap);
- benMapping.setMBeneficiaryImage(benImageOBJ);
- benMapping.setMBeneficiaryAccount(bankOBJ);
-
- regMap.setProviderServiceMapID(identity.getProviderServiceMapId());
- // added columns for data sync
- // 17-09-2018
- if (identity.getVanID() != null)
- regMap.setVanID(identity.getVanID());
- if (identity.getParkingPlaceId() != null)
- regMap.setParkingPlaceID(identity.getParkingPlaceId());
- regMap.setVanSerialNo(regMap.getBenRegId());
- // END
-
- regIdRepo.save(regMap);
- if (benMapping.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- benMapping.setCreatedDate(ts);
- }
-
- if (identity.getBenFamilyDTOs().get(0).getVanID() != null)
- benMapping.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
-
- benMapping = mappingRepo.save(benMapping);
- // Update van serial no for data sync
- mappingRepo.updateVanSerialNo(benMapping.getBenMapId());
-
- final MBeneficiarymapping benMapping2 = benMapping;
- logger.info("IdentityService.createIdentity - saving FamilyMaps");
- List fIdenList = null;
- List fList = null;
-
- // new logic (18-09-2018, Neeraj kumar)
- if (null != identity.getBenFamilyDTOs()) {
- fIdenList = mapper.identityDTOListToMBeneficiaryfamilymappingList(identity.getBenFamilyDTOs());
- if (fIdenList != null) {
- for (MBeneficiaryfamilymapping bfMapping : fIdenList) {
- bfMapping.setBenMapId(benMapping2.getBenMapId());
-
- if (bfMapping.getVanID() == null && identity.getVanID() != null)
- bfMapping.setVanID(identity.getVanID());
- if (bfMapping.getVanID() == null && identity.getBenFamilyDTOs().get(0).getVanID() != null)
- bfMapping.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
-
- if (bfMapping.getParkingPlaceID() == null && identity.getParkingPlaceId() != null)
- bfMapping.setParkingPlaceID(identity.getParkingPlaceId());
-
- if (bfMapping.getAssociatedBenRegId() == null) {
- bfMapping.setAssociatedBenRegId(benMapping2.getBenRegId());
- }
- }
- fList = (List) familyMapRepo.saveAll(fIdenList);
- // Update van serial no for data sync
- if (fList != null && !fList.isEmpty()) {
- for (MBeneficiaryfamilymapping obj : fList) {
- familyMapRepo.updateVanSerialNo(obj.getBenFamilyMapId());
- }
- }
- }
- }
-
- logger.info("IdentityService.createIdentity - FamilyMap saved ");
- logger.info("IdentityService.createIdentity - saving Service Map");
- MBeneficiaryservicemapping sMap = mapper.identityDTOToMBeneficiaryservicemapping(identity);
- sMap.setBenMapId(benMapping.getBenMapId());
- if (sMap.getCreatedDate() == null) {
- SimpleDateFormat sdf = new SimpleDateFormat(CREATED_DATE_FORMAT);
- String dateToStoreInDataBase = sdf.format(new Date());
- Timestamp ts = Timestamp.valueOf(dateToStoreInDataBase);
- sMap.setCreatedDate(ts);
- }
- sMap = serviceMapRepo.save(sMap);
- logger.info("IdentityService.createIdentity - ServiceMap saved - id = " + sMap.getBenServiceMapID());
-
- // Update van serial no for data sync
- serviceMapRepo.updateVanSerialNo(sMap.getBenServiceMapID());
-
- List sList = new ArrayList<>();
- sList.add(sMap);
- logger.info("IdentityService.createIdentity - saving Identity");
- List mIdenList2 = new ArrayList<>();
- if (null != identity.getIdentities()) {
- List mIdenList = mapper
- .identityDTOListToMBeneficiaryidentityList(identity.getIdentities());
- mIdenList.forEach(mIden -> {
- mIden.setBenMapId(benMapping2.getBenMapId());
- mIden.setCreatedBy(identity.getAgentName());
- mIden.setCreatedDate(identity.getEventTypeDate());
-
- // set new column(vanID, parkingPlaceID) value for data sync
- if (identity.getVanID() != null)
- mIden.setVanID(identity.getVanID());
- if (identity.getParkingPlaceId() != null)
- mIden.setParkingPlaceID(identity.getParkingPlaceId());
-
- MBeneficiaryidentity m = identityRepo.save(mIden);
-
- // Update van serial no for data sync
- identityRepo.updateVanSerialNo(m.getBenIdentityId());
-
- mIdenList2.add(m);
- logger.info("IdentityService.createIdentity - Identity saved - id = " + m.getBenIdentityId());
- });
- }
-
- logger.info("IdentityService.createIdentity - end. id = " + benMapping.getBenMapId());
- return partialMapper.mBeneficiarymappingToBeneficiaryCreateResp(benMapping);
- }
-private String cleanPhoneNumber(String phoneNumber) {
- if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
- return phoneNumber;
+
+ private MBeneficiaryaddress identityDTOToMBeneficiaryaddress(IdentityDTO dto) {
+ MBeneficiaryaddress beneficiaryAddress = new MBeneficiaryaddress();
+ if (dto.getCurrentAddress() != null) {
+ beneficiaryAddress.setCurrAddrLine1(dto.getCurrentAddress().getAddrLine1());
+ beneficiaryAddress.setCurrAddrLine2(dto.getCurrentAddress().getAddrLine2());
+ beneficiaryAddress.setCurrAddrLine3(dto.getCurrentAddress().getAddrLine3());
+ beneficiaryAddress.setCurrCountryId(dto.getCurrentAddress().getCountryId());
+ beneficiaryAddress.setCurrCountry(dto.getCurrentAddress().getCountry());
+ beneficiaryAddress.setCurrStateId(dto.getCurrentAddress().getStateId());
+ beneficiaryAddress.setCurrState(dto.getCurrentAddress().getState());
+ beneficiaryAddress.setCurrDistrictId(dto.getCurrentAddress().getDistrictId());
+ beneficiaryAddress.setCurrDistrict(dto.getCurrentAddress().getDistrict());
+ beneficiaryAddress.setCurrSubDistrictId(dto.getCurrentAddress().getSubDistrictId());
+ beneficiaryAddress.setCurrSubDistrict(dto.getCurrentAddress().getSubDistrict());
+ beneficiaryAddress.setCurrVillageId(dto.getCurrentAddress().getVillageId());
+ beneficiaryAddress.setCurrVillage(dto.getCurrentAddress().getVillage());
+ beneficiaryAddress.setCurrAddressValue(dto.getCurrentAddress().getAddressValue());
+ beneficiaryAddress.setCurrPinCode(dto.getCurrentAddress().getPinCode());
+ beneficiaryAddress.setCurrZoneID(dto.getCurrentAddress().getZoneID());
+ beneficiaryAddress.setCurrZone(dto.getCurrentAddress().getZoneName());
+ beneficiaryAddress.setCurrAreaId(dto.getCurrentAddress().getParkingPlaceID());
+ beneficiaryAddress.setCurrArea(dto.getCurrentAddress().getParkingPlaceName());
+ beneficiaryAddress.setCurrServicePointId(dto.getCurrentAddress().getServicePointID());
+ beneficiaryAddress.setCurrServicePoint(dto.getCurrentAddress().getServicePointName());
+ beneficiaryAddress.setCurrHabitation(dto.getCurrentAddress().getHabitation());
+ }
+ if (dto.getEmergencyAddress() != null) {
+ beneficiaryAddress.setEmerAddrLine1(dto.getEmergencyAddress().getAddrLine1());
+ beneficiaryAddress.setEmerAddrLine2(dto.getEmergencyAddress().getAddrLine2());
+ beneficiaryAddress.setEmerAddrLine3(dto.getEmergencyAddress().getAddrLine3());
+ beneficiaryAddress.setEmerCountryId(dto.getEmergencyAddress().getCountryId());
+ beneficiaryAddress.setEmerCountry(dto.getEmergencyAddress().getCountry());
+ beneficiaryAddress.setEmerStateId(dto.getEmergencyAddress().getStateId());
+ beneficiaryAddress.setEmerState(dto.getEmergencyAddress().getState());
+ beneficiaryAddress.setEmerDistrictId(dto.getEmergencyAddress().getDistrictId());
+ beneficiaryAddress.setEmerDistrict(dto.getEmergencyAddress().getDistrict());
+ beneficiaryAddress.setEmerSubDistrictId(dto.getEmergencyAddress().getSubDistrictId());
+ beneficiaryAddress.setEmerSubDistrict(dto.getEmergencyAddress().getSubDistrict());
+ beneficiaryAddress.setEmerVillageId(dto.getEmergencyAddress().getVillageId());
+ beneficiaryAddress.setEmerVillage(dto.getEmergencyAddress().getVillage());
+ beneficiaryAddress.setEmerAddressValue(dto.getEmergencyAddress().getAddressValue());
+ beneficiaryAddress.setEmerPinCode(dto.getEmergencyAddress().getPinCode());
+ beneficiaryAddress.setEmerZoneID(dto.getEmergencyAddress().getZoneID());
+ beneficiaryAddress.setEmerZone(dto.getEmergencyAddress().getZoneName());
+ beneficiaryAddress.setEmerAreaId(dto.getEmergencyAddress().getParkingPlaceID());
+ beneficiaryAddress.setEmerArea(dto.getEmergencyAddress().getParkingPlaceName());
+ beneficiaryAddress.setEmerServicePointId(dto.getEmergencyAddress().getServicePointID());
+ beneficiaryAddress.setEmerServicePoint(dto.getEmergencyAddress().getServicePointName());
+ beneficiaryAddress.setEmerHabitation(dto.getEmergencyAddress().getHabitation());
+ }
+
+ if (dto.getPermanentAddress() != null) {
+ beneficiaryAddress.setPermAddrLine1(dto.getPermanentAddress().getAddrLine1());
+ beneficiaryAddress.setPermAddrLine2(dto.getPermanentAddress().getAddrLine2());
+ beneficiaryAddress.setPermAddrLine3(dto.getPermanentAddress().getAddrLine3());
+ beneficiaryAddress.setPermCountryId(dto.getPermanentAddress().getCountryId());
+ beneficiaryAddress.setPermCountry(dto.getPermanentAddress().getCountry());
+ beneficiaryAddress.setPermStateId(dto.getPermanentAddress().getStateId());
+ beneficiaryAddress.setPermState(dto.getPermanentAddress().getState());
+ beneficiaryAddress.setPermDistrictId(dto.getPermanentAddress().getDistrictId());
+ beneficiaryAddress.setPermDistrict(dto.getPermanentAddress().getDistrict());
+ beneficiaryAddress.setPermSubDistrictId(dto.getPermanentAddress().getSubDistrictId());
+ beneficiaryAddress.setPermSubDistrict(dto.getPermanentAddress().getSubDistrict());
+ beneficiaryAddress.setPermVillageId(dto.getPermanentAddress().getVillageId());
+ beneficiaryAddress.setPermVillage(dto.getPermanentAddress().getVillage());
+ beneficiaryAddress.setPermAddressValue(dto.getPermanentAddress().getAddressValue());
+ beneficiaryAddress.setPermPinCode(dto.getPermanentAddress().getPinCode());
+
+ beneficiaryAddress.setPermZoneID(dto.getPermanentAddress().getZoneID());
+ beneficiaryAddress.setPermZone(dto.getPermanentAddress().getZoneName());
+ beneficiaryAddress.setPermAreaId(dto.getPermanentAddress().getParkingPlaceID());
+ beneficiaryAddress.setPermArea(dto.getPermanentAddress().getParkingPlaceName());
+ beneficiaryAddress.setPermServicePointId(dto.getPermanentAddress().getServicePointID());
+ beneficiaryAddress.setPermServicePoint(dto.getPermanentAddress().getServicePointName());
+ beneficiaryAddress.setPermHabitation(dto.getPermanentAddress().getHabitation());
+ }
+ if (dto.getAgentName() != null) {
+ beneficiaryAddress.setCreatedBy(dto.getAgentName());
+ }
+ if (dto.getCreatedDate() != null) {
+ beneficiaryAddress.setCreatedDate(dto.getCreatedDate());
+ }
+ if (dto.getVanID() != null) {
+ beneficiaryAddress.setVanID(dto.getVanID());
+ }
+ if (dto.getParkingPlaceId() != null) {
+ beneficiaryAddress.setParkingPlaceID(dto.getParkingPlaceId());
+ }
+
+ return beneficiaryAddress;
}
-
- // Remove +91 prefix
- String cleaned = phoneNumber.trim();
- if (cleaned.startsWith("+91")) {
- cleaned = cleaned.substring(3);
- } else if (cleaned.startsWith("91") && cleaned.length() == 12) {
- // Handle case where + is already removed but 91 remains
- cleaned = cleaned.substring(2);
+
+ public String getReservedIdList() {
+
+ return "success";
}
-
- return cleaned.trim();
-}
- private MBeneficiarydetail convertIdentityDTOToMBeneficiarydetail(IdentityDTO dto) {
- MBeneficiarydetail beneficiarydetail = new MBeneficiarydetail();
- beneficiarydetail.setAreaId(dto.getAreaId());
- if (null != dto.getBeneficiaryRegId())
- beneficiarydetail.setBeneficiaryRegID(BigInteger.valueOf(dto.getBeneficiaryRegId()));
- beneficiarydetail.setCommunity(dto.getCommunity());
- beneficiarydetail.setCommunityId(dto.getCommunityId());
- beneficiarydetail.setDob(dto.getDob());
- beneficiarydetail.setEducation(dto.getEducation());
- beneficiarydetail.setEducationId(dto.getEducationId());
- beneficiarydetail.setEmergencyRegistration(dto.getEmergencyRegistration());
- beneficiarydetail.setHealthCareWorkerId(dto.getHealthCareWorkerId());
- beneficiarydetail.setHealthCareWorker(dto.getHealthCareWorker());
- beneficiarydetail.setFatherName(dto.getFatherName());
- beneficiarydetail.setMotherName(dto.getMotherName());
- beneficiarydetail.setFirstName(dto.getFirstName());
- beneficiarydetail.setGender(dto.getGender());
- beneficiarydetail.setGenderId(dto.getGenderId());
- beneficiarydetail.setIncomeStatus(dto.getIncomeStatus());
- beneficiarydetail.setMonthlyFamilyIncome(dto.getMonthlyFamilyIncome());
- beneficiarydetail.setIncomeStatusId(dto.getIncomeStatusId());
- beneficiarydetail.setLastName(dto.getLastName());
- beneficiarydetail.setMaritalStatusId(dto.getMaritalStatusId());
- beneficiarydetail.setMaritalStatus(dto.getMaritalStatus());
- beneficiarydetail.setMiddleName(dto.getMiddleName());
- beneficiarydetail.setOccupation(dto.getOccupationName());
- beneficiarydetail.setOccupationId(dto.getOccupationId());
- beneficiarydetail.setPhcId(dto.getPhcId());
- beneficiarydetail.setPlaceOfWork(dto.getPlaceOfWork());
- beneficiarydetail.setPreferredLanguageId(dto.getPreferredLanguageId());
- beneficiarydetail.setPreferredLanguage(dto.getPreferredLanguage());
- beneficiarydetail.setReligion(dto.getReligion());
- if (dto.getFaceEmbedding() != null)
- beneficiarydetail.setFaceEmbedding(dto.getFaceEmbedding().toString());
- if (dto.getReligionId() != null)
- beneficiarydetail.setReligionId(BigInteger.valueOf(dto.getReligionId()));
- beneficiarydetail.setRemarks(dto.getRemarks());
- if (dto.getServicePointId() != null)
- beneficiarydetail.setServicePointId(BigInteger.valueOf(dto.getServicePointId()));
- beneficiarydetail.setSourceOfInfo(dto.getSourceOfInfo());
- beneficiarydetail.setSpouseName(dto.getSpouseName());
- beneficiarydetail.setStatus(dto.getStatus());
- beneficiarydetail.setTitle(dto.getTitle());
- beneficiarydetail.setTitleId(dto.getTitleId());
- beneficiarydetail.setZoneId(dto.getZoneId());
- beneficiarydetail.setCreatedBy(dto.getAgentName());
- beneficiarydetail.setCreatedDate(dto.getCreatedDate());
- beneficiarydetail.setIsHIVPositive(MBeneficiarydetail.setIsHIVPositive(dto.getIsHIVPositive()));
- beneficiarydetail.setAgeAtMarriage(
- MBeneficiarydetail.getAgeAtMarriageCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
- beneficiarydetail.setMarriageDate(
- MBeneficiarydetail.getMarriageDateCalc(dto.getDob(), dto.getMarriageDate(), dto.getAgeAtMarriage()));
- beneficiarydetail.setVanID(dto.getVanID());
- beneficiarydetail.setParkingPlaceID(dto.getParkingPlaceId());
- if(dto.getOtherFields() != null)
- beneficiarydetail.setOtherFields(dto.getOtherFields());
- if(dto.getLiteracyStatus() != null)
- beneficiarydetail.setLiteracyStatus(dto.getLiteracyStatus());
- return beneficiarydetail;
- }
-
- private MBeneficiaryImage identityDTOToMBeneficiaryImage(IdentityDTO identity) {
- MBeneficiaryImage beneficiaryImage = new MBeneficiaryImage();
-
- beneficiaryImage.setBenImage(identity.getBenImage());
- beneficiaryImage.setCreatedBy(identity.getAgentName());
- beneficiaryImage.setCreatedDate(identity.getCreatedDate());
- if (identity.getVanID() != null)
- beneficiaryImage.setVanID(identity.getVanID());
- if (identity.getBenFamilyDTOs() != null)
- beneficiaryImage.setVanID(identity.getBenFamilyDTOs().get(0).getVanID());
-
- beneficiaryImage.setParkingPlaceID(identity.getParkingPlaceId());
-
- return beneficiaryImage;
- }
-
- private MBeneficiarycontact identityDTOToMBeneficiarycontact(IdentityDTO dto) {
- MBeneficiarycontact beneficiaryContact = new MBeneficiarycontact();
- if (dto.getContact() != null) {
- beneficiaryContact.setPreferredPhoneNum(dto.getContact().getPreferredPhoneNum());
- beneficiaryContact.setPreferredPhoneTyp(dto.getContact().getPreferredPhoneTyp());
- beneficiaryContact.setPreferredSMSPhoneNum(dto.getContact().getPreferredSMSPhoneNum());
- beneficiaryContact.setPreferredSMSPhoneTyp(dto.getContact().getPreferredSMSPhoneTyp());
- beneficiaryContact.setEmergencyContactNum(dto.getContact().getEmergencyContactNum());
- beneficiaryContact.setPhoneNum1(dto.getContact().getPhoneNum1());
- beneficiaryContact.setPhoneTyp1(dto.getContact().getPhoneTyp1());
- beneficiaryContact.setPhoneNum2(dto.getContact().getPhoneNum2());
- beneficiaryContact.setPhoneTyp2(dto.getContact().getPhoneTyp2());
- beneficiaryContact.setPhoneNum3(dto.getContact().getPhoneNum3());
- beneficiaryContact.setPhoneTyp3(dto.getContact().getPhoneTyp3());
- beneficiaryContact.setPhoneNum4(dto.getContact().getPhoneNum4());
- beneficiaryContact.setPhoneTyp4(dto.getContact().getPhoneTyp4());
- beneficiaryContact.setPhoneNum5(dto.getContact().getPhoneNum5());
- beneficiaryContact.setPhoneTyp5(dto.getContact().getPhoneTyp5());
- }
- beneficiaryContact.setEmailId(dto.getPreferredEmailId());
- beneficiaryContact.setCreatedBy(dto.getAgentName());
- beneficiaryContact.setCreatedDate(dto.getCreatedDate());
- beneficiaryContact.setVanID(dto.getVanID());
- beneficiaryContact.setParkingPlaceID(dto.getParkingPlaceId());
- return beneficiaryContact;
- }
-
- private MBeneficiaryaddress identityDTOToMBeneficiaryaddress(IdentityDTO dto) {
- MBeneficiaryaddress beneficiaryAddress = new MBeneficiaryaddress();
- if (dto.getCurrentAddress() != null) {
- beneficiaryAddress.setCurrAddrLine1(dto.getCurrentAddress().getAddrLine1());
- beneficiaryAddress.setCurrAddrLine2(dto.getCurrentAddress().getAddrLine2());
- beneficiaryAddress.setCurrAddrLine3(dto.getCurrentAddress().getAddrLine3());
- beneficiaryAddress.setCurrCountryId(dto.getCurrentAddress().getCountryId());
- beneficiaryAddress.setCurrCountry(dto.getCurrentAddress().getCountry());
- beneficiaryAddress.setCurrStateId(dto.getCurrentAddress().getStateId());
- beneficiaryAddress.setCurrState(dto.getCurrentAddress().getState());
- beneficiaryAddress.setCurrDistrictId(dto.getCurrentAddress().getDistrictId());
- beneficiaryAddress.setCurrDistrict(dto.getCurrentAddress().getDistrict());
- beneficiaryAddress.setCurrSubDistrictId(dto.getCurrentAddress().getSubDistrictId());
- beneficiaryAddress.setCurrSubDistrict(dto.getCurrentAddress().getSubDistrict());
- beneficiaryAddress.setCurrVillageId(dto.getCurrentAddress().getVillageId());
- beneficiaryAddress.setCurrVillage(dto.getCurrentAddress().getVillage());
- beneficiaryAddress.setCurrAddressValue(dto.getCurrentAddress().getAddressValue());
- beneficiaryAddress.setCurrPinCode(dto.getCurrentAddress().getPinCode());
- beneficiaryAddress.setCurrZoneID(dto.getCurrentAddress().getZoneID());
- beneficiaryAddress.setCurrZone(dto.getCurrentAddress().getZoneName());
- beneficiaryAddress.setCurrAreaId(dto.getCurrentAddress().getParkingPlaceID());
- beneficiaryAddress.setCurrArea(dto.getCurrentAddress().getParkingPlaceName());
- beneficiaryAddress.setCurrServicePointId(dto.getCurrentAddress().getServicePointID());
- beneficiaryAddress.setCurrServicePoint(dto.getCurrentAddress().getServicePointName());
- beneficiaryAddress.setCurrHabitation(dto.getCurrentAddress().getHabitation());
- }
- if (dto.getEmergencyAddress() != null) {
- beneficiaryAddress.setEmerAddrLine1(dto.getEmergencyAddress().getAddrLine1());
- beneficiaryAddress.setEmerAddrLine2(dto.getEmergencyAddress().getAddrLine2());
- beneficiaryAddress.setEmerAddrLine3(dto.getEmergencyAddress().getAddrLine3());
- beneficiaryAddress.setEmerCountryId(dto.getEmergencyAddress().getCountryId());
- beneficiaryAddress.setEmerCountry(dto.getEmergencyAddress().getCountry());
- beneficiaryAddress.setEmerStateId(dto.getEmergencyAddress().getStateId());
- beneficiaryAddress.setEmerState(dto.getEmergencyAddress().getState());
- beneficiaryAddress.setEmerDistrictId(dto.getEmergencyAddress().getDistrictId());
- beneficiaryAddress.setEmerDistrict(dto.getEmergencyAddress().getDistrict());
- beneficiaryAddress.setEmerSubDistrictId(dto.getEmergencyAddress().getSubDistrictId());
- beneficiaryAddress.setEmerSubDistrict(dto.getEmergencyAddress().getSubDistrict());
- beneficiaryAddress.setEmerVillageId(dto.getEmergencyAddress().getVillageId());
- beneficiaryAddress.setEmerVillage(dto.getEmergencyAddress().getVillage());
- beneficiaryAddress.setEmerAddressValue(dto.getEmergencyAddress().getAddressValue());
- beneficiaryAddress.setEmerPinCode(dto.getEmergencyAddress().getPinCode());
- beneficiaryAddress.setEmerZoneID(dto.getEmergencyAddress().getZoneID());
- beneficiaryAddress.setEmerZone(dto.getEmergencyAddress().getZoneName());
- beneficiaryAddress.setEmerAreaId(dto.getEmergencyAddress().getParkingPlaceID());
- beneficiaryAddress.setEmerArea(dto.getEmergencyAddress().getParkingPlaceName());
- beneficiaryAddress.setEmerServicePointId(dto.getEmergencyAddress().getServicePointID());
- beneficiaryAddress.setEmerServicePoint(dto.getEmergencyAddress().getServicePointName());
- beneficiaryAddress.setEmerHabitation(dto.getEmergencyAddress().getHabitation());
- }
-
- if (dto.getPermanentAddress() != null) {
- beneficiaryAddress.setPermAddrLine1(dto.getPermanentAddress().getAddrLine1());
- beneficiaryAddress.setPermAddrLine2(dto.getPermanentAddress().getAddrLine2());
- beneficiaryAddress.setPermAddrLine3(dto.getPermanentAddress().getAddrLine3());
- beneficiaryAddress.setPermCountryId(dto.getPermanentAddress().getCountryId());
- beneficiaryAddress.setPermCountry(dto.getPermanentAddress().getCountry());
- beneficiaryAddress.setPermStateId(dto.getPermanentAddress().getStateId());
- beneficiaryAddress.setPermState(dto.getPermanentAddress().getState());
- beneficiaryAddress.setPermDistrictId(dto.getPermanentAddress().getDistrictId());
- beneficiaryAddress.setPermDistrict(dto.getPermanentAddress().getDistrict());
- beneficiaryAddress.setPermSubDistrictId(dto.getPermanentAddress().getSubDistrictId());
- beneficiaryAddress.setPermSubDistrict(dto.getPermanentAddress().getSubDistrict());
- beneficiaryAddress.setPermVillageId(dto.getPermanentAddress().getVillageId());
- beneficiaryAddress.setPermVillage(dto.getPermanentAddress().getVillage());
- beneficiaryAddress.setPermAddressValue(dto.getPermanentAddress().getAddressValue());
- beneficiaryAddress.setPermPinCode(dto.getPermanentAddress().getPinCode());
-
- beneficiaryAddress.setPermZoneID(dto.getPermanentAddress().getZoneID());
- beneficiaryAddress.setPermZone(dto.getPermanentAddress().getZoneName());
- beneficiaryAddress.setPermAreaId(dto.getPermanentAddress().getParkingPlaceID());
- beneficiaryAddress.setPermArea(dto.getPermanentAddress().getParkingPlaceName());
- beneficiaryAddress.setPermServicePointId(dto.getPermanentAddress().getServicePointID());
- beneficiaryAddress.setPermServicePoint(dto.getPermanentAddress().getServicePointName());
- beneficiaryAddress.setPermHabitation(dto.getPermanentAddress().getHabitation());
- }
- if (dto.getAgentName() != null) {
- beneficiaryAddress.setCreatedBy(dto.getAgentName());
- }
- if (dto.getCreatedDate() != null) {
- beneficiaryAddress.setCreatedDate(dto.getCreatedDate());
- }
- if (dto.getVanID() != null) {
- beneficiaryAddress.setVanID(dto.getVanID());
- }
- if (dto.getParkingPlaceId() != null) {
- beneficiaryAddress.setParkingPlaceID(dto.getParkingPlaceId());
- }
-
- return beneficiaryAddress;
- }
-
- public String getReservedIdList() {
-
- return "success";
- }
-
- /**
- *
- * @param reserveIdentityDTO
- * @return
- */
- public String reserveIdentity(ReserveIdentityDTO reserveIdentityDTO) {
-
- Long availableCount = regIdRepo.countByProviderServiceMapIDAndVehicalNoOrderByBenRegIdAsc(
- reserveIdentityDTO.getProviderServiceMapID(), reserveIdentityDTO.getVehicalNo());
-
- if (reserveIdentityDTO.getReserveCount() < availableCount) {
-
- MBeneficiaryregidmapping beneficiaryregidmapping;
- Long countToBeAllocate = reserveIdentityDTO.getReserveCount() - availableCount;
- countToBeAllocate++;
- for (int index = 0; index < countToBeAllocate; index++) {
-
- beneficiaryregidmapping = regIdRepo.findFirstByProviderServiceMapIDAndVehicalNoOrderByBenRegIdAsc(null,
- null);
- beneficiaryregidmapping.setProviderServiceMapID(reserveIdentityDTO.getProviderServiceMapID());
- beneficiaryregidmapping.setVehicalNo(reserveIdentityDTO.getVehicalNo());
- regIdRepo.save(beneficiaryregidmapping);
- }
- }
-
- return "Successfully Completed";
- }
-
- public String unReserveIdentity(ReserveIdentityDTO unReserve) {
-
- regIdRepo.unreserveBeneficiaryIds(unReserve.getProviderServiceMapID(), unReserve.getVehicalNo());
- return "Successfully Completed";
- }
-
- /**
- * Get partial details of beneficiaries (first name middle name and last name)
- * list on benId's list
- *
- * @param BenRegIds
- * @return {@link List} Beneficiaries
- */
-
- public List getBeneficiariesPartialDeatilsByBenRegIdList(List benRegIds) {
-
- logger.info("IdentityService.getBeneficiariesPartialDeatilsByBenRegId - end");
- List list = new ArrayList<>();
-
- // new logic, 19-12-2018
- List benMapObjArr = null;
- if (benRegIds != null && !benRegIds.isEmpty()) {
- benMapObjArr = mappingRepo.getBenMappingByRegIDList(benRegIds);
- if (benMapObjArr != null && !benMapObjArr.isEmpty()) {
- for (Object[] objArr : benMapObjArr) {
- MBeneficiarymapping benMap = this.getBeneficiariesDTONewPartial(objArr);
-
- list.add(partialMapper.mBeneficiarymappingToBeneficiariesPartialDTO(benMap));
- }
- }
- logger.info("benMap size" + (list.isEmpty() ? "No Beneficiary Found" : list.size()));
-
- }
- // end
- logger.info("IdetityService.getBeneficiariesPartialDeatilsByBenRegId - end");
-
- return list;
- }
-
- /**
- * Get partial details of beneficiaries (first name middle name and last name)
- * list on benId's list
- *
- * @param benRegIds
- * @return {@link List} Beneficiaries
- */
- public List getBeneficiariesDeatilsByBenRegIdList(List benRegIds) {
-
- logger.info("IdentityService.getBeneficiariesDeatilsByBenRegIdList - end");
- List list = new ArrayList<>();
-
- // new logic, 19-12-2018
- List benMapObjArr = null;
- if (benRegIds != null && !benRegIds.isEmpty()) {
- benMapObjArr = mappingRepo.getBenMappingByRegIDList(benRegIds);
- if (benMapObjArr != null && !benMapObjArr.isEmpty()) {
- for (Object[] objArr : benMapObjArr) {
- MBeneficiarymapping benMap = this.getBeneficiariesDTONew(objArr);
- list.add(this.getBeneficiariesDTO(benMap));
- }
- }
- logger.info("benMap size" + (list.isEmpty() ? "No Beneficiary Found" : list.size()));
- }
- // end
- logger.info("IdetityService.getBeneficiariesPartialDeatilsByBenRegId - end");
-
- return list;
- }
-
- /**
- *
- * @param benMap
- * @return
- */
- private BeneficiariesDTO getBeneficiariesDTO(MBeneficiarymapping benMap) {
- BeneficiariesDTO bdto = mapper.mBeneficiarymappingToBeneficiariesDTO(benMap);
- if (null != benMap && null != benMap.getMBeneficiarydetail()
- && !StringUtils.isEmpty(benMap.getMBeneficiarydetail().getFaceEmbedding())) {
- String faceEmbedding = benMap.getMBeneficiarydetail().getFaceEmbedding();
- String trimmedInput = faceEmbedding.replaceAll("[\\[\\]]", "");
- List floatList = new ArrayList<>();
- if(!StringUtils.isEmpty(trimmedInput)) {
- String[] stringNumbers = trimmedInput.split(",\\s*");
- for (String str : stringNumbers) {
- floatList.add(Float.parseFloat(str));
- }
- }
- bdto.setFaceEmbedding(floatList);
- }
- // bdto.setOtherFields(benMap.getMBeneficiarydetail().getOtherFields());
- bdto.setBeneficiaryFamilyTags(
- mapper.mapToMBeneficiaryfamilymappingWithBenFamilyDTOList(benMap.getMBeneficiaryfamilymappings()));
- bdto.setBeneficiaryIdentites(
- mapper.mBeneficiaryidentityListToBenIdentityDTOList(benMap.getMBeneficiaryidentities()));
-
- List abhaList = v_BenAdvanceSearchRepo.getBenAbhaDetailsByBenRegID(bdto.getBenRegId());
- if (abhaList != null && !abhaList.isEmpty()) {
- List abhaDTOList = new ArrayList<>();
- AbhaAddressDTO abhaDTO;
- for (Object[] objArr : abhaList) {
- abhaDTO = new AbhaAddressDTO();
- abhaDTO.setBeneficiaryRegID(bdto.getBenRegId());
- if (objArr[1] != null)
- abhaDTO.setHealthID(objArr[1].toString());
- if (objArr[2] != null)
- abhaDTO.setHealthIDNumber(objArr[2].toString());
- if (objArr[3] != null)
- abhaDTO.setAuthenticationMode(objArr[3].toString());
- if (objArr[4] != null)
- abhaDTO.setCreatedDate((Timestamp) objArr[4]);
-
- abhaDTOList.add(abhaDTO);
-
- }
- bdto.setAbhaDetails(abhaDTOList);
- }
- return bdto;
- }
-
- private BeneficiariesDTO mBeneficiarymappingToBeneficiariesDTO(MBeneficiarymapping benMap) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /**
- * finite search
- *
- * @param identityDTO
- * @return
- */
- public List getBeneficiaries(IdentityDTO identityDTO) {
- List list = new ArrayList<>();
-
- List benMapList = mappingRepo.finiteSearch(identityDTO);
- for (MBeneficiarymapping benMap : benMapList) {
- list.add(this.getBeneficiariesDTO(benMap));
- logger.info("benMapId: " + benMap.getBenMapId() + " :: BenId: "
- + benMap.getMBeneficiaryregidmapping().getBeneficiaryID());
- }
-
- return list;
- }
-
- /***
- *
- * @return beneficiary image for beneficiary Reg ID.
- */
- public String getBeneficiaryImage(String requestOBJ) {
- OutputResponse response = new OutputResponse();
- try {
- Map