From 7370a65de99d1c0619ef6dcc814b40a100148ae3 Mon Sep 17 00:00:00 2001 From: njorocs Date: Sun, 26 Jan 2025 15:31:05 +0300 Subject: [PATCH] Added benefits package and interventions location attributes.Implemented Fetching benefit packages and interventions from HIE, persisiting the response in the respective location attributes. Created local endpoints for returning the payload from local instatnce. Modified value_reference column in location_attribute to accomodate large strings --- .../BenefitsPackageDataExchange.java | 202 +++++++++++++++++ .../InterventionsDataExchange.java | 204 ++++++++++++++++++ .../kenyaemr/metadata/FacilityMetadata.java | 14 ++ .../KenyaemrCoreRestController.java | 153 +++++++++++++ omod/src/main/resources/liquibase.xml | 8 + 5 files changed, 581 insertions(+) create mode 100644 api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/BenefitsPackageDataExchange.java create mode 100644 api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/InterventionsDataExchange.java diff --git a/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/BenefitsPackageDataExchange.java b/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/BenefitsPackageDataExchange.java new file mode 100644 index 000000000..217b68347 --- /dev/null +++ b/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/BenefitsPackageDataExchange.java @@ -0,0 +1,202 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under + * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. + * + * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS + * graphic logo is a trademark of OpenMRS Inc. + */ +package org.openmrs.module.kenyaemr.dataExchange; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.openmrs.Location; +import org.openmrs.LocationAttribute; +import org.openmrs.LocationAttributeType; +import org.openmrs.User; +import org.openmrs.api.LocationService; +import org.openmrs.api.context.Context; +import org.openmrs.module.kenyaemr.metadata.CommonMetadata; +import org.openmrs.module.kenyaemr.metadata.FacilityMetadata; +import org.openmrs.module.metadatadeploy.MetadataUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.openmrs.module.kenyaemr.util.EmrUtils.getDefaultLocation; +import static org.openmrs.module.kenyaemr.util.EmrUtils.getGlobalPropertyValue; + +/** + * A scheduled task that automatically updates the facility status. + */ +public class BenefitsPackageDataExchange { + private static final Logger log = LoggerFactory.getLogger(BenefitsPackageDataExchange.class); + + private static final LocationService locationService = Context.getLocationService(); + + private static final String BASE_JWT_URL_KEY = CommonMetadata.GP_SHA_FACILITY_VERIFICATION_JWT_GET_END_POINT; + private static final String BASE_URL_KEY = CommonMetadata.GP_HIE_BASE_END_POINT_URL; + private static final String API_USER_KEY = CommonMetadata.GP_HIE_API_USER; + private static final String API_SECRET_KEY = CommonMetadata.GP_SHA_FACILITY_VERIFICATION_GET_API_SECRET; + + public static ResponseEntity getBenefitsPackage() { + + String bearerToken = getBearerToken(); + if (bearerToken.isEmpty()) { + System.err.println("Bearer token is missing"); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + + try { + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSslConnectionFactory()).build(); + HttpGet getRequest = new HttpGet(getGlobalPropertyValue(BASE_URL_KEY)+"benefit-package"); + getRequest.setHeader("Authorization", "Bearer " + bearerToken); + + HttpResponse response = httpClient.execute(getRequest); + + int responseCode = response.getStatusLine().getStatusCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(createSuccessResponse(response)); + } else { + System.err.println("Error: failed to connect: "+ responseCode); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + } catch (Exception ex) { + System.err.println("Error fetching benefits package: "+ ex.getMessage()); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + } + + private static SSLConnectionSocketFactory createSslConnectionFactory() throws Exception { + return new SSLConnectionSocketFactory( + SSLContexts.createDefault(), + new String[]{"TLSv1.2"}, + null, + SSLConnectionSocketFactory.getDefaultHostnameVerifier() + ); + } + + private static String getBearerToken() { + String username = getGlobalPropertyValue(API_USER_KEY).trim(); + String secret = getGlobalPropertyValue(API_SECRET_KEY).trim(); + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpGet getRequest = new HttpGet(getGlobalPropertyValue(BASE_JWT_URL_KEY) + "hie-auth?key=O7B-DHABP00278"); + getRequest.setHeader("Content-Type", "application/x-www-form-urlencoded"); + getRequest.setHeader("Authorization", createBasicAuthHeader(username, secret)); + + try (CloseableHttpResponse response = httpClient.execute(getRequest)) { + + if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { + String responseString = EntityUtils.toString(response.getEntity()).trim(); + log.info("Bearer token retrieved successfully."); + return responseString; + } else { + System.err.println("Failed to fetch Bearer Token. HTTP Status:"+ response.getStatusLine().getStatusCode()); + } + } + } catch (Exception e) { + System.err.println("Error retrieving Bearer Token: "+ e.getMessage()); + } + return ""; + } + + private static String createBasicAuthHeader(String username, String password) { + String credentials = username + ":" + password; + return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + } + + private static Map extractBenefitsPackage(String benefitsPackage) { + Map statusMap = new HashMap<>(); + statusMap.put("shaBenefitsPackage", "--"); + + if(benefitsPackage != null) { + statusMap.put("shaBenefitsPackage", benefitsPackage); + } + + return statusMap; + } + + private static String createSuccessResponse(HttpResponse response) { + try { + return EntityUtils.toString(response.getEntity()); + } catch (IOException e) { + throw new RuntimeException("Error parsing response", e); + } + } + private static LocationAttribute getOrUpdateAttribute(Location location, LocationAttributeType type, String value, User creator) { + // Check if the attribute already exists + LocationAttribute existingAttribute = location.getActiveAttributes(type) + .stream() + .filter(attr -> attr.getAttributeType().equals(type)) + .findFirst() + .orElse(null); + + if (existingAttribute == null) { + // Create a new attribute if none exists + LocationAttribute newAttribute = new LocationAttribute(); + newAttribute.setAttributeType(type); + newAttribute.setValue(value); + newAttribute.setCreator(creator); + newAttribute.setDateCreated(new Date()); + location.addAttribute(newAttribute); + return newAttribute; + } else if (!existingAttribute.getValue().equals(value)) { + // Update the value if it differs + existingAttribute.setValue(value); + return existingAttribute; + } + + // No changes needed + return null; + } + + public static boolean saveBenefitsPackage() { + try { + ResponseEntity responseEntity = getBenefitsPackage(); + String responseBody = responseEntity.getBody(); + + if (responseEntity.getStatusCode().is2xxSuccessful() && responseBody != null) { + Map benefitsPackage = extractBenefitsPackage(responseBody); + + if (benefitsPackage.get("shaBenefitsPackage").equals("--")) { + System.err.println("No valid benefits package found in the response."); + return false; + } + + Location location = getDefaultLocation(); + User authenticatedUser = Context.getAuthenticatedUser(); + + if (authenticatedUser == null) { + throw new IllegalStateException("No authenticated user in context"); + } + // Update or create attributes + getOrUpdateAttribute(location, MetadataUtils.existing(LocationAttributeType.class, FacilityMetadata._LocationAttributeType.SHA_BENEFITS_PACKAGE), benefitsPackage.get("shaBenefitsPackage"), authenticatedUser); + + locationService.saveLocation(location); // Persist changes + return true; + } else { + System.err.println("Failed to save benefits package: " + responseEntity.getBody()); + return false; + } + } catch (Exception e) { + System.err.println("Error in saving benefits package: " + e); + return false; + } + } +} \ No newline at end of file diff --git a/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/InterventionsDataExchange.java b/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/InterventionsDataExchange.java new file mode 100644 index 000000000..fca86aa6b --- /dev/null +++ b/api/src/main/java/org/openmrs/module/kenyaemr/dataExchange/InterventionsDataExchange.java @@ -0,0 +1,204 @@ +/** + * This Source Code Form is subject to the terms of the Mozilla Public License, + * v. 2.0. If a copy of the MPL was not distributed with this file, You can + * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under + * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. + * + * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS + * graphic logo is a trademark of OpenMRS Inc. + */ +package org.openmrs.module.kenyaemr.dataExchange; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.util.EntityUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.openmrs.Location; +import org.openmrs.LocationAttribute; +import org.openmrs.LocationAttributeType; +import org.openmrs.User; +import org.openmrs.api.LocationService; +import org.openmrs.api.context.Context; +import org.openmrs.module.kenyaemr.metadata.CommonMetadata; +import org.openmrs.module.kenyaemr.metadata.FacilityMetadata; +import org.openmrs.module.metadatadeploy.MetadataUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import static org.openmrs.module.kenyaemr.util.EmrUtils.*; + +/** + * A scheduled task that automatically updates the facility status. + */ +public class InterventionsDataExchange { + private static final Logger log = LoggerFactory.getLogger(InterventionsDataExchange.class); + + private static final LocationService locationService = Context.getLocationService(); + + private static final String BASE_JWT_URL_KEY = CommonMetadata.GP_SHA_FACILITY_VERIFICATION_JWT_GET_END_POINT; + private static final String BASE_URL_KEY = CommonMetadata.GP_HIE_BASE_END_POINT_URL; + private static final String API_USER_KEY = CommonMetadata.GP_HIE_API_USER; + private static final String API_SECRET_KEY = CommonMetadata.GP_SHA_FACILITY_VERIFICATION_GET_API_SECRET; + + public static ResponseEntity getInterventions() { + + String bearerToken = getBearerToken(); + if (bearerToken.isEmpty()) { + System.err.println("Bearer token is missing"); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + + try { + CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSslConnectionFactory()).build(); + HttpGet getRequest = new HttpGet(getGlobalPropertyValue(BASE_URL_KEY) + "interventions"); + getRequest.setHeader("Authorization", "Bearer " + bearerToken); + + HttpResponse response = httpClient.execute(getRequest); + + int responseCode = response.getStatusLine().getStatusCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(createSuccessResponse(response)); + } else { + System.err.println("Error: failed to connect: "+ responseCode); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + } catch (Exception ex) { + System.err.println("Error fetching interventions: "+ ex.getMessage()); + return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body("{\"status\": \"Error\"}"); + } + } + + private static SSLConnectionSocketFactory createSslConnectionFactory() throws Exception { + return new SSLConnectionSocketFactory( + SSLContexts.createDefault(), + new String[]{"TLSv1.2"}, + null, + SSLConnectionSocketFactory.getDefaultHostnameVerifier() + ); + } + + private static String getBearerToken() { + String username = getGlobalPropertyValue(API_USER_KEY).trim(); + String secret = getGlobalPropertyValue(API_SECRET_KEY).trim(); + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpGet getRequest = new HttpGet(getGlobalPropertyValue(BASE_JWT_URL_KEY) + "hie-auth?key=O7B-DHABP00278"); + getRequest.setHeader("Content-Type", "application/x-www-form-urlencoded"); + getRequest.setHeader("Authorization", createBasicAuthHeader(username, secret)); + + try (CloseableHttpResponse response = httpClient.execute(getRequest)) { + + if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { + String responseString = EntityUtils.toString(response.getEntity()).trim(); + log.info("Bearer token retrieved successfully..."); + return responseString; + } else { + System.err.println("Failed to fetch Bearer Token. HTTP Status:"+ response.getStatusLine().getStatusCode()); + } + } + } catch (Exception e) { + System.err.println("Error retrieving Bearer Token: "+ e.getMessage()); + } + return ""; + } + + private static String createBasicAuthHeader(String username, String password) { + String credentials = username + ":" + password; + return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + } + + private static Map extractInterventions(String interventions) { + Map statusMap = new HashMap<>(); + statusMap.put("shaInterventions", "--"); + + if(interventions != null) { + statusMap.put("shaInterventions", interventions); + } + + return statusMap; + } + + private static String createSuccessResponse(HttpResponse response) { + try { + return EntityUtils.toString(response.getEntity()); + } catch (IOException e) { + throw new RuntimeException("Error parsing response", e); + } + } + private static LocationAttribute getOrUpdateAttribute(Location location, LocationAttributeType type, String value, User creator) { + // Check if the attribute already exists + LocationAttribute existingAttribute = location.getActiveAttributes(type) + .stream() + .filter(attr -> attr.getAttributeType().equals(type)) + .findFirst() + .orElse(null); + + if (existingAttribute == null) { + // Create a new attribute if none exists + LocationAttribute newAttribute = new LocationAttribute(); + newAttribute.setAttributeType(type); + newAttribute.setValue(value); + newAttribute.setCreator(creator); + newAttribute.setDateCreated(new Date()); + location.addAttribute(newAttribute); + return newAttribute; + } else if (!existingAttribute.getValue().equals(value)) { + // Update the value if it differs + existingAttribute.setValue(value); + return existingAttribute; + } + + // No changes needed + return null; + } + + public static boolean saveInterventions() { + try { + ResponseEntity responseEntity = getInterventions(); + String responseBody = responseEntity.getBody(); + + if (responseEntity.getStatusCode().is2xxSuccessful() && responseBody != null) { + Map interventions = extractInterventions(responseBody); + + if (interventions.get("shaInterventions").equals("--")) { + System.err.println("No valid interventions found in the response."); + return false; + } + + Location location = getDefaultLocation(); + User authenticatedUser = Context.getAuthenticatedUser(); + + if (authenticatedUser == null) { + throw new IllegalStateException("No authenticated user in context"); + } + // Update or create attributes + getOrUpdateAttribute(location, MetadataUtils.existing(LocationAttributeType.class, FacilityMetadata._LocationAttributeType.SHA_INTERVENTIONS), interventions.get("shaInterventions"), authenticatedUser); + + locationService.saveLocation(location); // Persist changes + return true; + } else { + System.err.println("Failed to save interventions: " + responseEntity.getBody()); + return false; + } + } catch (Exception e) { + System.err.println("Error in saving interventions: " + e); + return false; + } + } +} \ No newline at end of file diff --git a/api/src/main/java/org/openmrs/module/kenyaemr/metadata/FacilityMetadata.java b/api/src/main/java/org/openmrs/module/kenyaemr/metadata/FacilityMetadata.java index 562ef2ab7..4724eff68 100755 --- a/api/src/main/java/org/openmrs/module/kenyaemr/metadata/FacilityMetadata.java +++ b/api/src/main/java/org/openmrs/module/kenyaemr/metadata/FacilityMetadata.java @@ -52,6 +52,8 @@ public static final class _LocationAttributeType { public static final String FACILITY_HIE_FHIR_REFERENCE = "682f0a48-a642-491b-aa6d-41084bee0ee0"; public static final String FACILITY_REGISTRY_CODE = "1d1e2531-6a4a-4ed9-ab0a-02663e82379c"; public static final String FACILITY_LICENSE_NUMBER = "5f719dc5-3a70-48e5-8404-90bbcc35b36e"; + public static final String SHA_BENEFITS_PACKAGE = "db1cf31e-8b06-4c36-94bf-3a932fadd2d7"; + public static final String SHA_INTERVENTIONS = "cbe19f79-dcda-4532-a9c9-6f62c7a25b39"; } /** @@ -108,6 +110,18 @@ public void install() throws Exception { FreeTextDatatype.class, "", 0, 1, _LocationAttributeType.FACILITY_REGISTRY_CODE )); + + install(locationAttributeType( + "SHA Benefits Package", "SHA benefits package", + FreeTextDatatype.class, "", 0, 1, + _LocationAttributeType.SHA_BENEFITS_PACKAGE + )); + + install(locationAttributeType( + "SHA Interventions", "SHA interventions", + FreeTextDatatype.class, "", 0, 1, + _LocationAttributeType.SHA_INTERVENTIONS + )); } /** diff --git a/omod/src/main/java/org/openmrs/module/kenyaemr/web/controller/KenyaemrCoreRestController.java b/omod/src/main/java/org/openmrs/module/kenyaemr/web/controller/KenyaemrCoreRestController.java index d976b49ff..57cb0f2f9 100644 --- a/omod/src/main/java/org/openmrs/module/kenyaemr/web/controller/KenyaemrCoreRestController.java +++ b/omod/src/main/java/org/openmrs/module/kenyaemr/web/controller/KenyaemrCoreRestController.java @@ -98,7 +98,9 @@ import org.openmrs.module.kenyaemr.calculation.library.tb.TbDiseaseClassificationCalculation; import org.openmrs.module.kenyaemr.calculation.library.tb.TbPatientClassificationCalculation; import org.openmrs.module.kenyaemr.calculation.library.tb.TbTreatmentNumberCalculation; +import org.openmrs.module.kenyaemr.dataExchange.BenefitsPackageDataExchange; import org.openmrs.module.kenyaemr.dataExchange.FacilityDetailsDataExchange; +import org.openmrs.module.kenyaemr.dataExchange.InterventionsDataExchange; import org.openmrs.module.kenyaemr.metadata.CommonMetadata; import org.openmrs.module.kenyaemr.metadata.FacilityMetadata; import org.openmrs.module.kenyaemr.metadata.HivMetadata; @@ -599,6 +601,157 @@ private boolean isValuesEmptyOrDefault(ObjectNode node, String... keys) { } return allEmptyOrDefault; } + /** + * Fetches SHA benefits package + * + * @return custom location object + */ + @RequestMapping(method = RequestMethod.GET, value = "/sha-benefits-package") + @ResponseBody + public Object getShaBenefitsPackage(@RequestParam(value = "synchronize", defaultValue = "false") boolean isSynchronize) { + ObjectNode locationNode = null; + + Context.addProxyPrivilege(PrivilegeConstants.GET_LOCATIONS); + Context.addProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES); + Context.addProxyPrivilege(PrivilegeConstants.MANAGE_LOCATIONS); + Context.addProxyPrivilege(PrivilegeConstants.GET_LOCATION_ATTRIBUTE_TYPES); + + try { + if (isSynchronize && getRemoteBenefitsPackage()) { + locationNode = getSavedBenefitsPackage(); + if (locationNode != null) { + locationNode.put("source", "HIE"); + } + } else { + locationNode = getSavedBenefitsPackage(); + if (locationNode != null && isValuesEmptyOrDefault(locationNode, "shaBenefitsPackage")) { + + if (getRemoteBenefitsPackage()) { + locationNode = getSavedBenefitsPackage(); + if (locationNode != null) { + locationNode.put("source", "HIE"); + } + } else { + locationNode.put("source", "Error synchronizing with HIE and no local data found"); + } + } else if (locationNode != null) { + locationNode.put("source", "Local"); + } + } + } catch (Exception e) { + System.err.println("Error in fetching SHA benefits package: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving SHA benefits details."); + } finally { + Context.removeProxyPrivilege(PrivilegeConstants.GET_LOCATIONS); + Context.removeProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES); + Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_LOCATIONS); + Context.removeProxyPrivilege(PrivilegeConstants.GET_LOCATION_ATTRIBUTE_TYPES); + } + + if (locationNode == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Benefits package details not found."); + } + return ResponseEntity.ok(locationNode.toString()); + } + + private boolean getRemoteBenefitsPackage() { + boolean syncSuccess = false; + try { + syncSuccess = BenefitsPackageDataExchange.saveBenefitsPackage(); + } catch (Exception e) { + System.err.println("Error during synchronization: " + e); + } + return syncSuccess; + } + + private ObjectNode getSavedBenefitsPackage() { + Location location = EmrUtils.getDefaultLocation(); + + if (location == null) { + System.out.println("Default location not configured."); + return null; + } + ObjectNode locationNode = JsonNodeFactory.instance.objectNode(); + // Retrieve attributes + locationNode.put("shaBenefitsPackage", getLocationAttributeValue(location, FacilityMetadata._LocationAttributeType.SHA_BENEFITS_PACKAGE)); + return locationNode; + } + + /** + * Fetches SHA interventions + * + * @return custom location object + */ + @RequestMapping(method = RequestMethod.GET, value = "/sha-interventions") + @ResponseBody + public Object getShaInterventions(@RequestParam(value = "synchronize", defaultValue = "false") boolean isSynchronize) { + ObjectNode locationNode = null; + + Context.addProxyPrivilege(PrivilegeConstants.GET_LOCATIONS); + Context.addProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES); + Context.addProxyPrivilege(PrivilegeConstants.MANAGE_LOCATIONS); + Context.addProxyPrivilege(PrivilegeConstants.GET_LOCATION_ATTRIBUTE_TYPES); + + try { + if (isSynchronize && getRemoteInterventions()) { + locationNode = getSavedInterventions(); + if (locationNode != null) { + locationNode.put("source", "HIE"); + } + } else { + locationNode = getSavedInterventions(); + if (locationNode != null && isValuesEmptyOrDefault(locationNode, "shaInterventions")) { + + if (getRemoteInterventions()) { + locationNode = getSavedInterventions(); + if (locationNode != null) { + locationNode.put("source", "HIE"); + } + } else { + locationNode.put("source", "Error synchronizing with HIE and no local data found"); + } + } else if (locationNode != null) { + locationNode.put("source", "Local"); + } + } + } catch (Exception e) { + System.err.println("Error in fetching SHA interventions: " + e.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving SHA interventions."); + } finally { + Context.removeProxyPrivilege(PrivilegeConstants.GET_LOCATIONS); + Context.removeProxyPrivilege(PrivilegeConstants.GET_GLOBAL_PROPERTIES); + Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_LOCATIONS); + Context.removeProxyPrivilege(PrivilegeConstants.GET_LOCATION_ATTRIBUTE_TYPES); + } + + if (locationNode == null) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("SHA interventions details not found."); + } + return ResponseEntity.ok(locationNode.toString()); + } + + private boolean getRemoteInterventions() { + boolean syncSuccess = false; + try { + syncSuccess = InterventionsDataExchange.saveInterventions(); + } catch (Exception e) { + System.err.println("Error during synchronization: " + e); + } + return syncSuccess; + } + + private ObjectNode getSavedInterventions() { + Location location = EmrUtils.getDefaultLocation(); + + if (location == null) { + System.out.println("Default location not configured."); + return null; + } + ObjectNode locationNode = JsonNodeFactory.instance.objectNode(); + // Retrieve attributes + locationNode.put("shaInterventions", getLocationAttributeValue(location, FacilityMetadata._LocationAttributeType.SHA_INTERVENTIONS)); + return locationNode; + } // Helper method for attribute retrieval private String getLocationAttributeValue(Location location, String attributeTypeUuid) { diff --git a/omod/src/main/resources/liquibase.xml b/omod/src/main/resources/liquibase.xml index fc2300d93..ccbc0a340 100755 --- a/omod/src/main/resources/liquibase.xml +++ b/omod/src/main/resources/liquibase.xml @@ -487,6 +487,14 @@ schedulable_class='org.openmrs.module.kenyaemrIL.MLabViralLoadResultsPullTask' + + + Modify value_reference column data type to MEDIUMTEXT in location_attribute table + + ALTER TABLE location_attribute MODIFY COLUMN value_reference MEDIUMTEXT; + + +