diff --git a/.gitignore b/.gitignore index c16ed227ef..f29deebda6 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ project.properties .settings build/ jacoco.exec -opensrp-chw/ba/ \ No newline at end of file +opensrp-chw/ba/ +opensrp-chw/nacp/ \ No newline at end of file diff --git a/build.gradle b/build.gradle index 9d88944b7e..ce9656fbd7 100644 --- a/build.gradle +++ b/build.gradle @@ -64,9 +64,9 @@ subprojects { ext.androidToolsBuildGradle = '4.0.1' ext.androidBuildToolsVersion = '29.0.3' - ext.androidMinSdkVersion = 19 - ext.androidCompileSdkVersion = 29 - ext.androidTargetSdkVersion = 29 + ext.androidMinSdkVersion = 21 + ext.androidCompileSdkVersion = 30 + ext.androidTargetSdkVersion = 31 ext.androidAnnotationsVersion = '3.0.1' ext.androidAnnotationsAPIVersion = '3.0.1' diff --git a/opensrp-chw/build.gradle b/opensrp-chw/build.gradle index 09a8c650d4..50dc92556d 100644 --- a/opensrp-chw/build.gradle +++ b/opensrp-chw/build.gradle @@ -10,12 +10,37 @@ buildscript { classpath 'com.android.tools.build:gradle:4.0.1' } } - +def githubProperties = new Properties() +if (rootProject.file("github.properties").exists()) { + githubProperties.load(new FileInputStream(rootProject.file("github.properties"))) +} allprojects { repositories { maven { url 'https://maven.google.com' } maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } maven { url 'https://maven.fabric.io/public' } + maven { + + name = "GitHubPackages" + + url = uri("https://maven.pkg.github.com/SoftmedTanzania/opensrp-client-chw-core") + credentials { + username = githubProperties['gpr.usr'] ?: System.getenv("GPR_USER") + password = githubProperties['gpr.key'] ?: System.getenv("GPR_API_KEY") + } + + } + + maven { + + name = "GitHubPackages" + + url = uri("https://maven.pkg.github.com/SoftmedTanzania/opensrp-client-chw-ld") + credentials { + username = githubProperties['gpr.usr'] ?: System.getenv("GPR_USER") + password = githubProperties['gpr.key'] ?: System.getenv("GPR_API_KEY") + } + } mavenLocal() } } @@ -109,7 +134,7 @@ android { buildConfigField "int", "SCHEDULE_SERVICE_MINUTES", '720' buildConfigField "int", "STOCK_USAGE_REPORT_MINUTES", '1440' buildConfigField "boolean", "USE_UNIFIED_REFERRAL_APPROACH", "true" - buildConfigField "boolean", "BUILD_FOR_BORESHA_AFYA_SOUTH", "false" + buildConfigField "boolean", "BUILD_FOR_BORESHA_AFYA_SOUTH", "true" } debug { @@ -127,7 +152,7 @@ android { buildConfigField "int", "SCHEDULE_SERVICE_MINUTES", '360' buildConfigField "int", "STOCK_USAGE_REPORT_MINUTES", '1440' buildConfigField "boolean", "USE_UNIFIED_REFERRAL_APPROACH", "true" - buildConfigField "boolean", "BUILD_FOR_BORESHA_AFYA_SOUTH", "false" + buildConfigField "boolean", "BUILD_FOR_BORESHA_AFYA_SOUTH", "true" testCoverageEnabled true } } @@ -171,6 +196,24 @@ android { flavorDimensions 'baseDimension' productFlavors { + nacp { + dimension = 'baseDimension' + applicationIdSuffix ".moh" + versionCode 14 + versionName "1.1.6" + buildConfigField "String", 'opensrp_url', '"https://ucs.nacp.go.tz/opensrp/"' + buildConfigField "String", 'guidebooks_url', '"https://opensrp.s3.amazonaws.com/media/ba/"' +// buildConfigField "String", 'opensrp_url_debug', '"http://50.116.15.4:8082/opensrp/"' + buildConfigField "String", 'opensrp_url_debug', '"http://170.187.199.69:8082/opensrp/"' + buildConfigField "String[]", "LOCATION_HIERACHY", '{"Country","Region","District","Ward" , "MOH Jhpiego Facility Name", "Health Facility", "Village", "Village Sublocations"}' + buildConfigField "String[]", "ALLOWED_LOCATION_LEVELS", '{"Ward" , "Facility", "Health Facility", "Village", "Village Sublocations"}' + buildConfigField "String[]", "ALLOWED_LOCATION_LEVELS_DEBUG", '{"Ward", "Facility", "Health Facility", "Village", "Village Sublocations"}' + buildConfigField "String", 'DEFAULT_LOCATION', '"Village Sublocations"' + buildConfigField "String", 'DEFAULT_LOCATION_DEBUG', '"Village"' + buildConfigField "long", "MAPBOX_DOWNLOAD_TILE_LIMIT", "6001" + + buildConfigField "int", "DATABASE_VERSION", '25' + } ba { dimension = 'baseDimension' applicationIdSuffix ".ba" @@ -291,10 +334,20 @@ android { dataBinding { enabled = true } + + bundle { + language { + // Specifies that the app bundle should not support + // configuration APKs for language resources. These + // resources are instead packaged with each base and + // dynamic feature APK. + enableSplit = false + } + } } dependencies { - implementation('org.smartregister:opensrp-client-chw-core:1.5.29-SNAPSHOT@aar') { + implementation('org.smartregister:opensrp-client-chw-core:1.5.36.14-NACP-SNAPSHOT@aar') { transitive = true exclude group: 'com.android.support', module: 'appcompat-v7' exclude group: 'androidx.legacy', module: 'legacy-support-v4' @@ -302,17 +355,6 @@ dependencies { exclude group: 'androidx.constraintlayout', module: 'constraintlayout' exclude group: 'com.google.guava', module: 'guava' exclude group: 'com.rengwuxian.materialedittext', module: 'library' - exclude group: 'org.smartregister', module: 'opensrp-client-native-form' - } - implementation('org.smartregister:opensrp-client-native-form:2.1.13-SNAPSHOT@aar') { - transitive = true - exclude group: 'com.android.support', module: 'appcompat-v7' - exclude group: 'com.android.support', module: 'cardview-v7' - exclude group: 'com.android.support', module: 'support-media-compat' - exclude group: 'com.android.support', module: 'support-v4' - exclude group: 'com.android.support', module: 'design' - exclude group: 'io.ona.rdt-capture', module: 'lib' - exclude group: 'com.google.guava', module: 'guava' } implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:5.1.0' implementation('io.ona.kujaku:library:0.9.0') { @@ -330,6 +372,8 @@ dependencies { implementation 'com.android.support:multidex:1.0.3' //Do not upgrade to 24.jre-1 due to compatibility issues implementation 'com.google.guava:guava:20.0' + implementation 'androidx.webkit:webkit:1.4.0' + implementation 'com.whiteelephant:monthandyearpicker:1.3.0' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' androidTestImplementation 'org.mockito:mockito-android:3.0.0' diff --git a/opensrp-chw/src/chad/java/org/smartregister/chw/activity/HivProfileActivityFlv.java b/opensrp-chw/src/chad/java/org/smartregister/chw/activity/HivProfileActivityFlv.java new file mode 100644 index 0000000000..dd5af7c454 --- /dev/null +++ b/opensrp-chw/src/chad/java/org/smartregister/chw/activity/HivProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class HivProfileActivityFlv extends DefaultHivProfileActivityFlv { +} diff --git a/opensrp-chw/src/chad/java/org/smartregister/chw/activity/TbProfileActivityFlv.java b/opensrp-chw/src/chad/java/org/smartregister/chw/activity/TbProfileActivityFlv.java new file mode 100644 index 0000000000..524838ce9e --- /dev/null +++ b/opensrp-chw/src/chad/java/org/smartregister/chw/activity/TbProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class TbProfileActivityFlv extends DefaultTbProfileActivityFlv { +} diff --git a/opensrp-chw/src/drc/java/org/smartregister/chw/activity/HivProfileActivityFlv.java b/opensrp-chw/src/drc/java/org/smartregister/chw/activity/HivProfileActivityFlv.java new file mode 100644 index 0000000000..2b4ea8beb6 --- /dev/null +++ b/opensrp-chw/src/drc/java/org/smartregister/chw/activity/HivProfileActivityFlv.java @@ -0,0 +1,5 @@ +package org.smartregister.chw.activity; + +public class HivProfileActivityFlv extends DefaultHivProfileActivityFlv { + +} diff --git a/opensrp-chw/src/drc/java/org/smartregister/chw/activity/TbProfileActivityFlv.java b/opensrp-chw/src/drc/java/org/smartregister/chw/activity/TbProfileActivityFlv.java new file mode 100644 index 0000000000..794a0a6bec --- /dev/null +++ b/opensrp-chw/src/drc/java/org/smartregister/chw/activity/TbProfileActivityFlv.java @@ -0,0 +1,5 @@ +package org.smartregister.chw.activity; + +public class TbProfileActivityFlv extends DefaultTbProfileActivityFlv { + +} diff --git a/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/HivProfileActivityFlv.java b/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/HivProfileActivityFlv.java new file mode 100644 index 0000000000..dd5af7c454 --- /dev/null +++ b/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/HivProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class HivProfileActivityFlv extends DefaultHivProfileActivityFlv { +} diff --git a/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/TbProfileActivityFlv.java b/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/TbProfileActivityFlv.java new file mode 100644 index 0000000000..524838ce9e --- /dev/null +++ b/opensrp-chw/src/guinea/java/org/smartregister/chw/activity/TbProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class TbProfileActivityFlv extends DefaultTbProfileActivityFlv { +} diff --git a/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/HivProfileActivityFlv.java b/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/HivProfileActivityFlv.java new file mode 100644 index 0000000000..dd5af7c454 --- /dev/null +++ b/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/HivProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class HivProfileActivityFlv extends DefaultHivProfileActivityFlv { +} diff --git a/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/TbProfileActivityFlv.java b/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/TbProfileActivityFlv.java new file mode 100644 index 0000000000..524838ce9e --- /dev/null +++ b/opensrp-chw/src/liberia/java/org/smartregister/chw/activity/TbProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class TbProfileActivityFlv extends DefaultTbProfileActivityFlv { +} diff --git a/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/HivProfileActivityFlv.java b/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/HivProfileActivityFlv.java new file mode 100644 index 0000000000..dd5af7c454 --- /dev/null +++ b/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/HivProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class HivProfileActivityFlv extends DefaultHivProfileActivityFlv { +} diff --git a/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/TbProfileActivityFlv.java b/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/TbProfileActivityFlv.java new file mode 100644 index 0000000000..524838ce9e --- /dev/null +++ b/opensrp-chw/src/lmh/java/org/smartregister/chw/activity/TbProfileActivityFlv.java @@ -0,0 +1,4 @@ +package org.smartregister.chw.activity; + +public class TbProfileActivityFlv extends DefaultTbProfileActivityFlv { +} diff --git a/opensrp-chw/src/main/AndroidManifest.xml b/opensrp-chw/src/main/AndroidManifest.xml index 36a582f220..9d21615bc7 100644 --- a/opensrp-chw/src/main/AndroidManifest.xml +++ b/opensrp-chw/src/main/AndroidManifest.xml @@ -3,33 +3,115 @@ xmlns:tools="http://schemas.android.com/tools" package="org.smartregister.chw"> - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -49,6 +134,9 @@ + @@ -146,20 +234,6 @@ - - - - - - - - - @@ -221,35 +292,108 @@ - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -279,12 +423,62 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/assets/config/mother_champion-reporting-indicator-definitions.yml b/opensrp-chw/src/main/assets/config/mother_champion-reporting-indicator-definitions.yml new file mode 100644 index 0000000000..8cc489e938 --- /dev/null +++ b/opensrp-chw/src/main/assets/config/mother_champion-reporting-indicator-definitions.yml @@ -0,0 +1,53 @@ +indicators: + - key: "b-1" + description: "Idadi ya wateja wa PMTCT waliounganishwa kwenye kikundi/vikundi vya IGA and Ushauri Nasaha" + indicatorQuery: " SELECT count(DISTINCT emcf.entity_id) as count + from ec_mother_champion_followup emcf + WHERE linked_to_psychosocial_group = 'yes' + AND date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1, 4) || + '-' || + substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6, 2) || + '-' || '01')" + - key: "b-2" + description: "Idadi ya wateja wapya wa PMTCT waliofuatiliwa na mama vinara na kuanza kutumia dawa" + indicatorQuery: " SELECT count(DISTINCT emcf.entity_id) as count + from ec_mother_champion_followup emcf + WHERE visit_number = 0 + AND date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1, 4) || + '-' || + substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6, 2) || + '-' || '01')" + - key: "b-3" + description: "Idadi ya wateja wa PMTCT waliopotea kwenye matumizi ya dawa (LTF) na kurudishwa/kufuatiliwa na mama vinara" + indicatorQuery: " SELECT count(DISTINCT epcf.entity_id) as count + from ec_pmtct_community_feedback epcf + WHERE date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1, 4) || + '-' || + substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6, 2) || + '-' || '01')" + - key: "b-4" + description: "Idadi ya vipindi alivyofundisha mama kinara/vinara kwa wateja wa PMTCT" + indicatorQuery: " SELECT count(DISTINCT id) as count + from ec_sbcc es + WHERE date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(es.sbcc_date, 7, 4) || '-' || substr(es.sbcc_date, 4, 2) || '-' || '01')" + - key: "b-5" + description: "Idadi ya wateja wa PMTCT walioelimishwa na mama kinara/vinara" + indicatorQuery: " SELECT SUM(participants_number) as count + from ec_sbcc es + WHERE date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(es.sbcc_date, 7, 4) || '-' || substr(es.sbcc_date, 4, 2) || '-' || '01')" + - key: "b-7" + description: "Idadi ya wenza waliofuatiliwa/kuletwa kituoni kupima" + indicatorQuery: " SELECT COUNT(DISTINCT eapcf.entity_id) as count + from ec_anc_partner_community_feedback eapcf + WHERE + partner_agree_attending_hf = 'yes' + AND date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) = + date(substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1, 4) || + '-' || + substr(strftime('%Y-%m-%d', datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6, 2) || + '-' || '01')" \ No newline at end of file diff --git a/opensrp-chw/src/main/assets/json.form/anc_pregnancy_outcome.json b/opensrp-chw/src/main/assets/json.form/anc_pregnancy_outcome.json index ace7fe2a56..2170d22084 100644 --- a/opensrp-chw/src/main/assets/json.form/anc_pregnancy_outcome.json +++ b/opensrp-chw/src/main/assets/json.form/anc_pregnancy_outcome.json @@ -123,6 +123,7 @@ "hint": "Delivery date", "expanded": false, "max_date": "today", + "min_date": "today-6w", "v_required": { "value": "true", "err": "Please enter date the woman delivered" diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/HealthFacilityVisitAction.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/HealthFacilityVisitAction.java index 4393475af3..decda4b68a 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/HealthFacilityVisitAction.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/HealthFacilityVisitAction.java @@ -67,9 +67,6 @@ public String getPreProcessed() { LocalDate visitDate = dateList.get(0); scheduleStatus = (visitDate.isBefore(LocalDate.now())) ? BaseAncHomeVisitAction.ScheduleStatus.OVERDUE : BaseAncHomeVisitAction.ScheduleStatus.DUE; - String due = (visitDate.isBefore(LocalDate.now())) ? context.getString(R.string.overdue) : context.getString(R.string.due); - - subTitle = MessageFormat.format("{0}{1}", due, DateTimeFormat.forPattern("dd MMM yyyy").print(visitDate)); String title = jsonObject.getJSONObject(JsonFormConstants.STEP1).getString(JsonFormConstants.STEP_TITLE); jsonObject.getJSONObject(JsonFormConstants.STEP1).put("title", MessageFormat.format(title, memberObject.getConfirmedContacts() + 1)); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPPreventiveServicesActionHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPPreventiveServicesActionHelper.java new file mode 100644 index 0000000000..9de0aa8e78 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPPreventiveServicesActionHelper.java @@ -0,0 +1,99 @@ +package org.smartregister.chw.actionhelper; + +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.util.JsonFormUtils.STEP1; + +import android.content.Context; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.kvp.dao.KvpDao; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; + +import java.util.List; +import java.util.Map; + +public class KvpPrEPPreventiveServicesActionHelper implements BaseKvpVisitAction.KvpVisitActionHelper { + + private String condoms_given; + private String jsonPayload; + private String baseEntityId; + + public KvpPrEPPreventiveServicesActionHelper(String baseEntityId) { + this.baseEntityId = baseEntityId; + } + + @Override + public void onJsonFormLoaded(String jsonPayload, Context context, Map> map) { + this.jsonPayload = jsonPayload; + } + + @Override + public String getPreProcessed() { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + if (!KvpDao.getDominantKVPGroup(baseEntityId).equalsIgnoreCase("pwud") && + !KvpDao.getDominantKVPGroup(baseEntityId).equalsIgnoreCase("pwid")) { + getFieldJSONObject(fields(jsonObject, STEP1), "number_of_needles_and_syringes_distributed").put("type", "hidden"); + getFieldJSONObject(fields(jsonObject, STEP1), "number_of_sterile_water_for_injection_distributed").put("type", "hidden"); + getFieldJSONObject(fields(jsonObject, STEP1), "number_of_alcohol_swabs_distributed").put("type", "hidden"); + getFieldJSONObject(fields(jsonObject, STEP1), "number_of_disposable_safety_boxes_distributed").put("type", "hidden"); + getFieldJSONObject(fields(jsonObject, STEP1), "number_of_plasters_distributed").put("type", "hidden"); + getFieldJSONObject(fields(jsonObject, STEP1), "protective_items_for_PWID_label").put("type", "hidden"); + } + return jsonObject.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + } + + @Override + public void onPayloadReceived(String jsonPayload) { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + condoms_given = CoreJsonFormUtils.getValue(jsonObject, "condoms_given"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public BaseKvpVisitAction.ScheduleStatus getPreProcessedStatus() { + return null; + } + + @Override + public String getPreProcessedSubTitle() { + return null; + } + + @Override + public String postProcess(String jsonPayload) { + return null; + } + + @Override + public String evaluateSubTitle() { + return null; + } + + @Override + public BaseKvpVisitAction.Status evaluateStatusOnPayload() { + if (StringUtils.isBlank(condoms_given)) + return BaseKvpVisitAction.Status.PENDING; + else { + return BaseKvpVisitAction.Status.COMPLETED; + } + } + + @Override + public void onPayloadReceived(BaseKvpVisitAction baseKvpVisitAction) { + //overridden + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPReferralServicesActionHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPReferralServicesActionHelper.java new file mode 100644 index 0000000000..4029436314 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPReferralServicesActionHelper.java @@ -0,0 +1,80 @@ +package org.smartregister.chw.actionhelper; + +import android.content.Context; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; + +import java.util.List; +import java.util.Map; + +public class KvpPrEPReferralServicesActionHelper implements BaseKvpVisitAction.KvpVisitActionHelper { + + private String referral_to_structural_services; + private String jsonPayload; + + @Override + public void onJsonFormLoaded(String jsonPayload, Context context, Map> map) { + this.jsonPayload = jsonPayload; + } + + @Override + public String getPreProcessed() { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + return jsonObject.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + } + + @Override + public void onPayloadReceived(String jsonPayload) { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + referral_to_structural_services = CoreJsonFormUtils.getValue(jsonObject, "referral_to_structural_services"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public BaseKvpVisitAction.ScheduleStatus getPreProcessedStatus() { + return null; + } + + @Override + public String getPreProcessedSubTitle() { + return null; + } + + @Override + public String postProcess(String s) { + return null; + } + + @Override + public String evaluateSubTitle() { + return null; + } + + @Override + public BaseKvpVisitAction.Status evaluateStatusOnPayload() { + if (StringUtils.isBlank(referral_to_structural_services)) + return BaseKvpVisitAction.Status.PENDING; + else { + return BaseKvpVisitAction.Status.COMPLETED; + } + } + + @Override + public void onPayloadReceived(BaseKvpVisitAction baseKvpVisitAction) { + //overridden + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPSbccServicesActionHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPSbccServicesActionHelper.java new file mode 100644 index 0000000000..0de617d314 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPSbccServicesActionHelper.java @@ -0,0 +1,82 @@ +package org.smartregister.chw.actionhelper; + +import android.content.Context; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; + +import java.util.List; +import java.util.Map; + +public class KvpPrEPSbccServicesActionHelper implements BaseKvpVisitAction.KvpVisitActionHelper { + + private String jsonPayload; + private String subTitle; + private String services_offered; + private BaseKvpVisitAction.ScheduleStatus scheduleStatus; + + @Override + public void onJsonFormLoaded(String jsonPayload, Context context, Map> map) { + this.jsonPayload = jsonPayload; + } + + @Override + public String getPreProcessed() { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + return jsonObject.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + } + + @Override + public void onPayloadReceived(String jsonPayload) { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + services_offered = CoreJsonFormUtils.getValue(jsonObject, "sbcc_services_offered"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public BaseKvpVisitAction.ScheduleStatus getPreProcessedStatus() { + return scheduleStatus; + } + + @Override + public String getPreProcessedSubTitle() { + return subTitle; + } + + @Override + public String postProcess(String s) { + return null; + } + + @Override + public String evaluateSubTitle() { + return null; + } + + @Override + public BaseKvpVisitAction.Status evaluateStatusOnPayload() { + if (StringUtils.isBlank(services_offered)) + return BaseKvpVisitAction.Status.PENDING; + else { + return BaseKvpVisitAction.Status.COMPLETED; + } + } + + @Override + public void onPayloadReceived(BaseKvpVisitAction baseKvpVisitAction) { + //Overridden + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPStructuralServicesActionHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPStructuralServicesActionHelper.java new file mode 100644 index 0000000000..c4250ead88 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPStructuralServicesActionHelper.java @@ -0,0 +1,80 @@ +package org.smartregister.chw.actionhelper; + +import android.content.Context; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; + +import java.util.List; +import java.util.Map; + +public class KvpPrEPStructuralServicesActionHelper implements BaseKvpVisitAction.KvpVisitActionHelper { + + private String structural_services_provided; + private String jsonPayload; + + @Override + public void onJsonFormLoaded(String jsonPayload, Context context, Map> map) { + this.jsonPayload = jsonPayload; + } + + @Override + public String getPreProcessed() { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + return jsonObject.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + } + + @Override + public void onPayloadReceived(String jsonPayload) { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + structural_services_provided = CoreJsonFormUtils.getValue(jsonObject, "structural_services_provided"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public BaseKvpVisitAction.ScheduleStatus getPreProcessedStatus() { + return null; + } + + @Override + public String getPreProcessedSubTitle() { + return null; + } + + @Override + public String postProcess(String s) { + return null; + } + + @Override + public String evaluateSubTitle() { + return null; + } + + @Override + public BaseKvpVisitAction.Status evaluateStatusOnPayload() { + if (StringUtils.isBlank(structural_services_provided)) + return BaseKvpVisitAction.Status.PENDING; + else { + return BaseKvpVisitAction.Status.COMPLETED; + } + } + + @Override + public void onPayloadReceived(BaseKvpVisitAction baseKvpVisitAction) { + //overridden + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPVisitTypeActionHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPVisitTypeActionHelper.java new file mode 100644 index 0000000000..e10f0f1d49 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/actionhelper/KvpPrEPVisitTypeActionHelper.java @@ -0,0 +1,80 @@ +package org.smartregister.chw.actionhelper; + +import android.content.Context; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; + +import java.util.List; +import java.util.Map; + +public class KvpPrEPVisitTypeActionHelper implements BaseKvpVisitAction.KvpVisitActionHelper { + + private String jsonPayload; + private String visitType; + + @Override + public void onJsonFormLoaded(String jsonPayload, Context context, Map> map) { + this.jsonPayload = jsonPayload; + } + + @Override + public String getPreProcessed() { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + return jsonObject.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + } + + @Override + public void onPayloadReceived(String jsonPayload) { + try { + JSONObject jsonObject = new JSONObject(jsonPayload); + visitType = CoreJsonFormUtils.getValue(jsonObject, "visit_type"); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public BaseKvpVisitAction.ScheduleStatus getPreProcessedStatus() { + return null; + } + + @Override + public String getPreProcessedSubTitle() { + return null; + } + + @Override + public String postProcess(String jsonPayload) { + return null; + } + + @Override + public String evaluateSubTitle() { + return null; + } + + @Override + public BaseKvpVisitAction.Status evaluateStatusOnPayload() { + if (StringUtils.isBlank(visitType)) + return BaseKvpVisitAction.Status.PENDING; + else { + return BaseKvpVisitAction.Status.COMPLETED; + } + } + + @Override + public void onPayloadReceived(BaseKvpVisitAction baseKvpVisitAction) { + //overridden + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsActivity.java new file mode 100644 index 0000000000..1560d122dd --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsActivity.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.activity; +import android.view.View; +import android.widget.TextView; +import org.smartregister.chw.R; + +public class AGYWReportsActivity extends CBHSReportsActivity{ + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.cbhs_monthly_summary) { + AGYWReportsViewActivity.startMe(this, "agyw-report", reportPeriod); + } + } + + @Override + public void setUpToolbar() { + super.setUpToolbar(); + TextView title = findViewById(R.id.toolbar_title); + title.setText(R.string.agyw_reports); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsViewActivity.java new file mode 100644 index 0000000000..68d539dda7 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWReportsViewActivity.java @@ -0,0 +1,19 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.R; +import org.smartregister.chw.util.Constants; + + +public class AGYWReportsViewActivity extends ChwReportsViewActivity{ + public static void startMe(Activity activity, String reportPath, String reportDate) { + Intent intent = new Intent(activity, AGYWReportsViewActivity.class); + intent.putExtra(ARG_REPORT_PATH, reportPath); + intent.putExtra(ARG_REPORT_DATE, reportDate); + intent.putExtra(ARG_REPORT_TITLE, R.string.agyw_reports); + intent.putExtra(ARG_REPORT_TYPE, Constants.ReportConstants.ReportTypes.AGYW_REPORT); + activity.startActivity(intent); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWServicesActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWServicesActivity.java new file mode 100644 index 0000000000..d4e82c2917 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AGYWServicesActivity.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.agyw.activity.BaseAGYWServicesActivity; +import org.smartregister.chw.agyw.handlers.BaseServiceActionHandler; +import org.smartregister.chw.agyw.util.Constants; +import org.smartregister.chw.listener.AgywServiceActionHandler; + +public class AGYWServicesActivity extends BaseAGYWServicesActivity { + public static void startMe(Activity activity, String baseEntityID) { + Intent intent = new Intent(activity, AGYWServicesActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityID); + activity.startActivity(intent); + } + + @Override + public BaseServiceActionHandler getServiceHandler() { + return new AgywServiceActionHandler(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AboveFiveChildProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AboveFiveChildProfileActivity.java index 229eb4e398..52b3614d9d 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AboveFiveChildProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AboveFiveChildProfileActivity.java @@ -1,5 +1,7 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.util.Constants.MALARIA_REFERRAL_FORM; + import android.app.Activity; import android.content.Intent; import android.view.Gravity; @@ -18,14 +20,13 @@ import org.smartregister.chw.model.ReferralTypeModel; import org.smartregister.chw.presenter.AboveFiveChildProfilePresenter; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.util.UtilsFlv; import org.smartregister.family.util.Constants; import java.util.ArrayList; import java.util.Date; import java.util.List; -import static org.smartregister.chw.util.Constants.MALARIA_REFERRAL_FORM; - public class AboveFiveChildProfileActivity extends CoreAboveFiveChildProfileActivity { public FamilyMemberFloatingMenu familyFloatingMenu; private List referralTypeModels = new ArrayList<>(); @@ -39,6 +40,8 @@ public List getReferralTypeModels() { public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.findItem(R.id.action_malaria_followup_visit).setVisible(false); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + UtilsFlv.updateMalariaMenuItems(memberObject.getBaseEntityId(), menu); return true; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivity.java new file mode 100644 index 0000000000..e2bd927054 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivity.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.agyw.domain.MemberObject; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.presenter.BaseAncMedicalHistoryPresenter; +import org.smartregister.chw.core.activity.CoreAncMedicalHistoryActivity; +import org.smartregister.chw.interactor.AgywMedicalHistoryInteractor; + +import java.util.List; + +public class AgywMedicalHistoryActivity extends CoreAncMedicalHistoryActivity { + private static MemberObject agywMemberObject; + private final Flavor flavor = new AgywMedicalHistoryActivityFlv(); + private ProgressBar progressBar; + + public static void startMe(Activity activity, MemberObject memberObject) { + Intent intent = new Intent(activity, AgywMedicalHistoryActivity.class); + agywMemberObject = memberObject; + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncMedicalHistoryPresenter(new AgywMedicalHistoryInteractor(), this, agywMemberObject.getBaseEntityId()); + } + + @Override + public void setUpView() { + linearLayout = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.linearLayoutMedicalHistory); + progressBar = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.progressBarMedicalHistory); + + TextView tvTitle = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.tvTitle); + tvTitle.setText(getString(org.smartregister.chw.opensrp_chw_anc.R.string.back_to, agywMemberObject.getFullName())); + + ((TextView) findViewById(R.id.medical_history)).setText(getString(R.string.visits_history)); + } + + @Override + public View renderView(List visits) { + super.renderView(visits); + View view = flavor.bindViews(this); + displayLoadingState(true); + flavor.processViewData(visits, this); + displayLoadingState(false); + TextView agywVisitTitle = view.findViewById(org.smartregister.chw.core.R.id.customFontTextViewHealthFacilityVisitTitle); + agywVisitTitle.setText(R.string.agyw_visit); + return view; + } + + @Override + public void displayLoadingState(boolean state) { + progressBar.setVisibility(state ? View.VISIBLE : View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivityFlv.java new file mode 100644 index 0000000000..027fc7f578 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywMedicalHistoryActivityFlv.java @@ -0,0 +1,211 @@ +package org.smartregister.chw.activity; + +import android.content.Context; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.BulletSpan; +import android.text.style.StyleSpan; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.core.activity.DefaultAncMedicalHistoryActivityFlv; +import org.smartregister.chw.util.Constants; + +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import timber.log.Timber; + +public class AgywMedicalHistoryActivityFlv extends DefaultAncMedicalHistoryActivityFlv { + private final StyleSpan boldSpan = new StyleSpan(android.graphics.Typeface.BOLD); + private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()); + + @Override + protected void processAncCard(String has_card, Context context) { + // super.processAncCard(has_card, context); + linearLayoutAncCard.setVisibility(View.GONE); + } + + @Override + protected void processHealthFacilityVisit(List> hf_visits, Context context) { + //super.processHealthFacilityVisit(hf_visits, context); + } + + @Override + public void processViewData(List visits, Context context) { + + if (visits.size() > 0) { + int days = 0; + List> hf_visits = new ArrayList<>(); + + int x = 0; + while (x < visits.size()) { + + // the first object in this list is the days difference + if (x == 0) { + days = Days.daysBetween(new DateTime(visits.get(visits.size() - 1).getDate()), new DateTime()).getDays(); + } + + + String[] visitParams = {"condom_provided", "provided_male_condoms", "provided_female_condoms", "hivst_kit_needed", "family_planning_service", "sbcc_intervention_provided", "economic_empowerment_education", "education_materials", "entrepreneurial_tools", "given_capital", "distribute_sanitary_pads", "nurturing_and_upb_edu", "nurturing_and_upb_edu_given"}; + extractVisitDetails(visits, visitParams, hf_visits, x, context); + + x++; + } + + processLastVisit(days, context); + processVisit(hf_visits, context, visits); + } + } + + private void extractVisitDetails(List sourceVisits, String[] hf_params, List> hf_visits, int iteration, Context context) { + // get the hf details + Map map = new HashMap<>(); + for (String param : hf_params) { + try { + List details = sourceVisits.get(iteration).getVisitDetails().get(param); + map.put(param, getTexts(context, details)); + } catch (Exception e) { + e.printStackTrace(); + } + + } + hf_visits.add(map); + } + + + private void processLastVisit(int days, Context context) { + linearLayoutLastVisit.setVisibility(View.VISIBLE); + if (days < 1) { + customFontTextViewLastVisit.setText(org.smartregister.chw.core.R.string.less_than_twenty_four); + } else { + customFontTextViewLastVisit.setText(StringUtils.capitalize(MessageFormat.format(context.getString(org.smartregister.chw.core.R.string.days_ago), String.valueOf(days)))); + } + } + + + protected void processVisit(List> community_visits, Context context, List visits) { + if (community_visits != null && community_visits.size() > 0) { + linearLayoutHealthFacilityVisit.setVisibility(View.VISIBLE); + + int x = 0; + for (Map vals : community_visits) { + View view = inflater.inflate(R.layout.medical_history_visit, null); + TextView tvTitle = view.findViewById(R.id.title); + TextView tvTypeOfService = view.findViewById(R.id.type_of_service); + LinearLayout visitDetailsLayout = view.findViewById(R.id.visit_details_layout); + + evaluateTitle(context, x, vals, tvTitle); + + String visitType; + + switch (visits.get(x).getVisitType()) { + case Constants.Events.AGYW_STRUCTURAL_SERVICES: + visitType = context.getString(R.string.agyw_structural_services); + break; + case Constants.Events.AGYW_BEHAVIORAL_SERVICES: + visitType = context.getString(R.string.agyw_behavioral_services); + break; + case Constants.Events.AGYW_BIO_MEDICAL_SERVICES: + visitType = context.getString(R.string.agyw_bio_medical_services); + break; + default: + visitType = visits.get(x).getVisitType(); + + } + tvTypeOfService.setText(visitType + " - " + simpleDateFormat.format(visits.get(x).getDate())); + + + for (Map.Entry entry : vals.entrySet()) { + TextView visitDetailTv = new TextView(context); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams + ((int) LinearLayout.LayoutParams.MATCH_PARENT, (int) LinearLayout.LayoutParams.WRAP_CONTENT); + + visitDetailTv.setLayoutParams(params); + float scale = context.getResources().getDisplayMetrics().density; + int dpAsPixels = (int) (10 * scale + 0.5f); + visitDetailTv.setPadding(dpAsPixels, 0, 0, 0); + visitDetailsLayout.addView(visitDetailTv); + + + try { + int resource = context.getResources().getIdentifier("agyw_" + entry.getKey(), "string", context.getPackageName()); + evaluateView(context, vals, visitDetailTv, entry.getKey(), resource, ""); + } catch (Exception e) { + Timber.e(e); + } + } + linearLayoutHealthFacilityVisitDetails.addView(view, 0); + + x++; + } + } + } + + + private void evaluateTitle(Context context, int x, Map vals, TextView tvTitle) { + String visitDate = vals.get("followup_visit_date"); + if (StringUtils.isBlank(visitDate)) { + tvTitle.setVisibility(View.GONE); + } else { + try { + tvTitle.setText(MessageFormat.format(context.getString(R.string.mother_champion_visit_title), x + 1, visitDate)); + } catch (Exception e) { + Timber.e(e); + } + } + } + + private void evaluateView(Context context, Map vals, TextView tv, String valueKey, int viewTitleStringResource, String valuePrefixInStringResources) { + if (StringUtils.isNotBlank(getMapValue(vals, valueKey))) { + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); + spannableStringBuilder.append(context.getString(viewTitleStringResource), boldSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).append("\n"); + + String stringValue = getMapValue(vals, valueKey); + String[] stringValueArray; + if (stringValue.contains(",")) { + stringValueArray = stringValue.split(","); + for (String value : stringValueArray) { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, value.trim()) + "\n", new BulletSpan(10), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } else { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, stringValue)).append("\n"); + } + tv.setText(spannableStringBuilder); + } else { + tv.setVisibility(View.GONE); + } + } + + + private String getMapValue(Map map, String key) { + if (map.containsKey(key)) { + return map.get(key); + } + return ""; + } + + private String getStringResource(Context context, String prefix, String resourceName) { + int resourceId = context.getResources(). + getIdentifier(prefix + resourceName.trim(), "string", context.getPackageName()); + try { + return context.getString(resourceId); + } catch (Exception e) { + Timber.e(e); + return prefix + resourceName; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywProfileActivity.java new file mode 100644 index 0000000000..67367b70a7 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywProfileActivity.java @@ -0,0 +1,89 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.view.Menu; +import android.view.View; +import android.widget.TextView; + +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.agyw.activity.BaseAGYWProfileActivity; +import org.smartregister.chw.agyw.util.Constants; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.pmtct.PmtctLibrary; +import org.smartregister.chw.pmtct.domain.Visit; +import org.smartregister.chw.util.Utils; +import org.smartregister.common.Gender; + +import java.util.ArrayList; +import java.util.List; + +public class AgywProfileActivity extends BaseAGYWProfileActivity { + + public static void startProfile(Activity activity, String baseEntityId) { + Intent intent = new Intent(activity, AgywProfileActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + activity.startActivity(intent); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + //TODO: update options menu with required details + return false; + } + + @Override + protected void startAGYWServices() { + AGYWServicesActivity.startMe(this, memberObject.getBaseEntityId()); + } + + @Override + public void startReferralForm() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + List referralTypeModels = new ArrayList<>(); + referralTypeModels.add(new ReferralTypeModel(getString(R.string.sti_referral), + org.smartregister.chw.util.Constants.JSON_FORM.getSTIServicesReferralForm(), CoreConstants.TASKS_FOCUS.STI_REFERRAL)); + referralTypeModels.addAll(Utils.getCommonReferralTypes(this, memberObject.getBaseEntityId())); + referralTypeModels.add(new ReferralTypeModel(getString(R.string.kvp_friendly_services), + CoreConstants.JSON_FORM.getFemaleKvpFriendlyServicesReferralForm(), CoreConstants.TASKS_FOCUS.KVP_FRIENDLY_SERVICES)); + referralTypeModels.add(new ReferralTypeModel(getString(R.string.family_planning_referral), + org.smartregister.chw.util.Constants.JSON_FORM.getFamilyPlanningUnifiedReferralForm(Gender.FEMALE.toString()), CoreConstants.TASKS_FOCUS.FP_SIDE_EFFECTS)); + referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), + CoreConstants.JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); + Utils.launchClientReferralActivity(this, referralTypeModels, memberObject.getBaseEntityId()); + } + } + + @Override + public void refreshMedicalHistory(boolean hasHistory) { + Visit lastAgywStructuralServices = getVisit(org.smartregister.chw.util.Constants.Events.AGYW_STRUCTURAL_SERVICES); + Visit lastAgywBehavioralServices = getVisit(org.smartregister.chw.util.Constants.Events.AGYW_BEHAVIORAL_SERVICES); + Visit lastAgywBioMedicalServices = getVisit(org.smartregister.chw.util.Constants.Events.AGYW_BIO_MEDICAL_SERVICES); + if (lastAgywStructuralServices != null || lastAgywBehavioralServices != null || lastAgywBioMedicalServices != null) { + rlLastVisit.setVisibility(View.VISIBLE); + findViewById(R.id.view_notification_and_referral_row).setVisibility(View.VISIBLE); + ((TextView) findViewById(R.id.vViewHistory)).setText(R.string.visits_history_profile_title); + ((TextView) findViewById(R.id.ivViewHistoryArrow)).setText(getString(R.string.view_visits_history)); + } else { + rlLastVisit.setVisibility(View.GONE); + } + } + + @Override + public void openMedicalHistory() { + AgywMedicalHistoryActivity.startMe(this, memberObject); + } + + private Visit getVisit(String eventType) { + return PmtctLibrary.getInstance().visitRepository().getLatestVisit(memberObject.getBaseEntityId(), eventType); + } + + + @Override + protected void onResume() { + super.onResume(); + refreshMedicalHistory(true); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywRegisterActivity.java new file mode 100644 index 0000000000..4479e5549c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywRegisterActivity.java @@ -0,0 +1,43 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import com.vijay.jsonwizard.domain.Form; + +import org.smartregister.chw.R; +import org.smartregister.chw.agyw.util.Constants; +import org.smartregister.chw.core.activity.CoreAgywRegisterActivity; +import org.smartregister.chw.fragment.AgywRegisterFragment; +import org.smartregister.view.fragment.BaseRegisterFragment; + +public class AgywRegisterActivity extends CoreAgywRegisterActivity { + + public static void startRegistration(Activity activity, String baseEntityId, int age) { + Intent intent = new Intent(activity, AgywRegisterActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.ACTION, Constants.ACTIVITY_PAYLOAD_TYPE.REGISTRATION); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.AGE, age); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.AGYW_FORM_NAME, Constants.FORMS.AGYW_REGISTRATION); + + activity.startActivity(intent); + } + + @Override + public Form getFormConfig() { + Form form = new Form(); + form.setActionBarBackground(org.smartregister.chw.core.R.color.family_actionbar); + form.setWizard(true); + form.setName(getString(R.string.agyw_screening)); + form.setNavigationBackground(org.smartregister.chw.core.R.color.family_navigation); + form.setNextLabel(this.getResources().getString(org.smartregister.chw.core.R.string.next)); + form.setPreviousLabel(this.getResources().getString(org.smartregister.chw.core.R.string.back)); + form.setSaveLabel(this.getResources().getString(org.smartregister.chw.core.R.string.save)); + return form; + } + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new AgywRegisterFragment(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywServicesFormActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywServicesFormActivity.java new file mode 100644 index 0000000000..d7c47cf642 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AgywServicesFormActivity.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.agyw.util.Constants; +import org.smartregister.chw.core.activity.CoreAgywServicesFormsActivity; + +public class AgywServicesFormActivity extends CoreAgywServicesFormsActivity { + public static void startMe(Activity activity, String formName, String baseEntityId, int age) { + Intent intent = new Intent(activity, AgywServicesFormActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.AGYW_FORM_NAME, formName); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.AGE, age); + + activity.startActivity(intent); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsMemberProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsMemberProfileActivity.java index a977cf95ff..a325ee8322 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsMemberProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsMemberProfileActivity.java @@ -1,170 +1,155 @@ package org.smartregister.chw.activity; -import android.app.Activity; +import static org.smartregister.chw.util.Utils.getClientGender; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + import android.content.Context; -import android.content.Intent; import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import androidx.appcompat.app.ActionBar; -import androidx.appcompat.widget.Toolbar; -import androidx.viewpager.widget.ViewPager; -import com.vijay.jsonwizard.constants.JsonFormConstants; -import com.vijay.jsonwizard.domain.Form; +import com.vijay.jsonwizard.utils.FormUtils; -import org.jetbrains.annotations.NotNull; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.smartregister.chw.R; -import org.smartregister.chw.contract.AllClientsMemberContract; -import org.smartregister.chw.core.activity.CoreFamilyOtherMemberProfileActivity; +import org.smartregister.chw.agyw.dao.AGYWDao; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreAllClientsMemberProfileActivity; import org.smartregister.chw.core.activity.CoreFamilyProfileActivity; +import org.smartregister.chw.core.contract.CoreAllClientsMemberContract; import org.smartregister.chw.core.form_data.NativeFormsDataBinder; import org.smartregister.chw.core.fragment.FamilyCallDialogFragment; -import org.smartregister.chw.core.listener.OnClickFloatingMenu; import org.smartregister.chw.core.utils.CoreConstants; -import org.smartregister.chw.core.utils.CoreJsonFormUtils; import org.smartregister.chw.custom_view.FamilyMemberFloatingMenu; import org.smartregister.chw.dataloader.FamilyMemberDataLoader; import org.smartregister.chw.fp.util.FamilyPlanningConstants; import org.smartregister.chw.fragment.FamilyOtherMemberProfileFragment; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.kvp.dao.KvpDao; import org.smartregister.chw.presenter.AllClientsMemberPresenter; import org.smartregister.chw.presenter.FamilyOtherMemberActivityPresenter; import org.smartregister.chw.util.Constants; import org.smartregister.chw.util.Utils; -import org.smartregister.commonregistry.CommonPersonObject; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.family.adapter.ViewPagerAdapter; import org.smartregister.family.fragment.BaseFamilyOtherMemberProfileFragment; import org.smartregister.family.model.BaseFamilyOtherMemberProfileActivityModel; -import org.smartregister.family.util.Constants.JSON_FORM_EXTRA; import org.smartregister.family.util.DBConstants; -import org.smartregister.family.util.JsonFormUtils; -import org.smartregister.helper.ImageRenderHelper; -import org.smartregister.opd.activity.BaseOpdFormActivity; -import org.smartregister.opd.utils.OpdConstants; import org.smartregister.view.contract.BaseProfileContract; -import org.smartregister.view.customcontrols.CustomFontTextView; +import androidx.viewpager.widget.ViewPager; import timber.log.Timber; -import static com.vijay.jsonwizard.constants.JsonFormConstants.COUNT; -import static com.vijay.jsonwizard.constants.JsonFormConstants.STEP1; -import static org.smartregister.chw.core.utils.CoreReferralUtils.getCommonRepository; -import static org.smartregister.family.util.JsonFormUtils.STEP2; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; -public class AllClientsMemberProfileActivity extends CoreFamilyOtherMemberProfileActivity implements OnClickFloatingMenu, AllClientsMemberContract.View { +public class AllClientsMemberProfileActivity extends CoreAllClientsMemberProfileActivity { + private final FamilyOtherMemberProfileActivity.Flavor flavor = new FamilyOtherMemberProfileActivityFlv(); private FamilyMemberFloatingMenu familyFloatingMenu; - private RelativeLayout layoutFamilyHasRow; - private CustomFontTextView familyHeadTextView; - private CustomFontTextView careGiverTextView; - private AllClientsMemberContract.Presenter allClientsMemberPresenter; + private CoreAllClientsMemberContract.Presenter allClientsMemberPresenter; @Override - protected void onCreation() { - setIndependentClient(true); - setContentView(R.layout.activity_all_clients_member_profile); - - Toolbar toolbar = findViewById(org.smartregister.family.R.id.family_toolbar); - setSupportActionBar(toolbar); + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); - ActionBar actionBar = getSupportActionBar(); - if (actionBar != null) { - actionBar.setDisplayHomeAsUpEnabled(true); - actionBar.setTitle(""); + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.GENDER, false); + menu.findItem(R.id.action_location_info).setVisible(true); + menu.findItem(R.id.action_cbhs_registration).setVisible(true); + menu.findItem(R.id.action_tb_registration).setVisible(false); + menu.findItem(R.id.action_fp_initiation).setVisible(false); + + if (flavor.hasANC() && !presenter().isWomanAlreadyRegisteredOnAnc(commonPersonObject) && flavor.isOfReproductiveAge(commonPersonObject, "Female") && gender.equalsIgnoreCase("Female")) { + flavor.updateFpMenuItems(baseEntityId, menu); + menu.findItem(R.id.action_anc_registration).setVisible(true); + } else { + menu.findItem(R.id.action_anc_registration).setVisible(false); } + if (flavor.hasANC() && flavor.isOfReproductiveAge(commonPersonObject, "Female") && gender.equalsIgnoreCase("Female")) { + flavor.updateFpMenuItems(baseEntityId, menu); + menu.findItem(R.id.action_pregnancy_out_come).setVisible(true); + } else { + menu.findItem(R.id.action_pregnancy_out_come).setVisible(false); + } + menu.findItem(R.id.action_sick_child_follow_up).setVisible(false); + menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + flavor.updateMalariaMenuItems(baseEntityId, menu); - appBarLayout = findViewById(org.smartregister.family.R.id.toolbar_appbarlayout); - - imageRenderHelper = new ImageRenderHelper(this); + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(baseEntityId) && age >= 15); + } - initializePresenter(); + if (ChwApplication.getApplicationFlavor().hasAGYW()) { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + if (gender.equalsIgnoreCase("Female") && age >= 10 && age <= 24 && !AGYWDao.isRegisteredForAgyw(baseEntityId)) { + menu.findItem(R.id.action_agyw_screening).setVisible(true); + } + } - setupViews(); + if(ChwApplication.getApplicationFlavor().hasKvp()){ + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(baseEntityId) && age >= 15); + } + return true; } @Override - public void setFamilyServiceStatus(String status) { - layoutFamilyHasRow.setVisibility(View.GONE); - } - - @Override - protected void setupViews() { - super.setupViews(); - TextView toolbarTitle = findViewById(R.id.toolbar_title); - toolbarTitle.setText(getString(R.string.return_to_all_client)); - layoutFamilyHasRow = findViewById(R.id.family_has_row); - familyHeadTextView = findViewById(R.id.family_head); - careGiverTextView = findViewById(R.id.primary_caregiver); + public FamilyOtherMemberActivityPresenter presenter() { + return (FamilyOtherMemberActivityPresenter) presenter; } @Override - protected void onResumption() { - super.onResumption(); - layoutFamilyHasRow.setVisibility(View.GONE); + protected void startAncRegister() { + AncRegisterActivity.startAncRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, PhoneNumber, + Constants.JSON_FORM.getAncRegistration(), null, familyBaseEntityId, familyName); } @Override - public void toggleFamilyHead(boolean show) { - familyHeadTextView.setVisibility(View.GONE); + protected void startPncRegister() { + PncRegisterActivity.startPncRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, PhoneNumber, + CoreConstants.JSON_FORM.getPregnancyOutcome(), null, familyBaseEntityId, familyName, null); } @Override - public void togglePrimaryCaregiver(boolean show) { - careGiverTextView.setVisibility(View.GONE); + protected void startMalariaRegister() { + MalariaRegisterActivity.startMalariaRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, familyBaseEntityId); } @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - menu.findItem(R.id.action_location_info).setVisible(true); - menu.findItem(R.id.action_hiv_registration).setVisible(true); - menu.findItem(R.id.action_tb_registration).setVisible(true); - menu.findItem(R.id.action_anc_registration).setVisible(false); - menu.findItem(R.id.action_sick_child_follow_up).setVisible(false); - menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); - return true; - } + protected void startHivRegister() { + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.GENDER, false); + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); - @Override - public boolean onOptionsItemSelected(MenuItem item) { - super.onOptionsItemSelected(item); - int itemId = item.getItemId(); - if (itemId == R.id.action_location_info) { - JSONObject preFilledForm = CoreJsonFormUtils.getAutoPopulatedJsonEditFormString( - CoreConstants.JSON_FORM.getFamilyDetailsRegister(), this, - getFamilyRegistrationDetails(), Utils.metadata().familyRegister.updateEventType); - if (preFilledForm != null) startFormActivity(preFilledForm); - return true; - } else if (itemId == R.id.action_hiv_registration) { - //TODO Start HIV registration form - return true; - } else if (itemId == R.id.action_tb_registration) { - //TODO Start HIV registration form - return true; - } - return true; - } + try { + String formName = Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(AllClientsMemberProfileActivity.this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); - @Override - public FamilyOtherMemberActivityPresenter presenter() { - return (FamilyOtherMemberActivityPresenter) presenter; - } + updateAgeAndGender(fields, age, gender); - @Override - protected void startAncRegister() { - AncRegisterActivity.startAncRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, PhoneNumber, - Constants.JSON_FORM.getAncRegistration(), null, familyBaseEntityId, familyName); + HivRegisterActivity.startHIVFormActivity(AllClientsMemberProfileActivity.this, baseEntityId, formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } } @Override - protected void startMalariaRegister() { - MalariaRegisterActivity.startMalariaRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, familyBaseEntityId); + protected void startTbRegister() { + try { + TbRegisterActivity.startTbFormActivity(AllClientsMemberProfileActivity.this, baseEntityId, Constants.JSON_FORM.getTbRegistration(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, Constants.JSON_FORM.getTbRegistration()).toString()); + } catch (JSONException e) { + Timber.e(e); + } } @Override @@ -186,6 +171,37 @@ protected void startFpChangeMethod() { FamilyPlanningConstants.ActivityPayload.CHANGE_METHOD_PAYLOAD_TYPE); } + @Override + protected void startHivstRegistration() { + String gender = org.smartregister.family.util.Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.GENDER, false); + HivstRegisterActivity.startHivstRegistrationActivity(AllClientsMemberProfileActivity.this, baseEntityId, gender); + } + + @Override + protected void startAgywScreening() { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + AgywRegisterActivity.startRegistration(AllClientsMemberProfileActivity.this, baseEntityId, age); + } + + @Override + protected void startKvpPrEPRegistration() { + String gender = getClientGender(baseEntityId); + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + KvpPrEPRegisterActivity.startRegistration(AllClientsMemberProfileActivity.this, baseEntityId, gender, age); + } + + @Override + protected void startKvpRegistration() { + //do nothing + } + + @Override + protected void startPrEPRegistration() { + //do nothing + } + @Override protected void removeIndividualProfile() { IndividualProfileRemoveActivity.startIndividualProfileActivity(AllClientsMemberProfileActivity.this, @@ -202,52 +218,15 @@ protected void startEditMemberJsonForm(Integer title_resource, CommonPersonObjec NativeFormsDataBinder binder = new NativeFormsDataBinder(getContext(), commonPersonObject.getCaseId()); binder.setDataLoader(new FamilyMemberDataLoader(familyName, isPrimaryCareGiver, titleString, Utils.metadata().familyMemberRegister.updateEventType, uniqueID)); - JSONObject jsonObject = binder.getPrePopulatedForm(Constants.ALL_CLIENT_REGISTRATION_FORM); + JSONObject jsonObject = binder.getPrePopulatedForm(CoreConstants.JSON_FORM.getAllClientUpdateRegistrationInfoForm()); try { - //Remove the first step and use the updated one - if (jsonObject != null && jsonObject.has(STEP1)) { - - jsonObject.put(JsonFormUtils.ENTITY_ID, baseEntityId); - jsonObject.put(COUNT, "1"); - jsonObject.remove(STEP1); - jsonObject.put(STEP1, jsonObject.getJSONObject(STEP2)); - jsonObject.remove(STEP2); - startFormActivity(jsonObject); - } - + startFormActivity(jsonObject); } catch (Exception e) { Timber.e(e); } } - @NotNull - private CommonPersonObjectClient getFamilyRegistrationDetails() { - //Update common person client object with all details from family register table - final CommonPersonObject personObject = getCommonRepository(Utils.metadata().familyRegister.tableName) - .findByBaseEntityId(familyBaseEntityId); - CommonPersonObjectClient commonPersonObjectClient = new CommonPersonObjectClient(personObject.getCaseId(), - personObject.getDetails(), ""); - commonPersonObjectClient.setColumnmaps(personObject.getColumnmaps()); - commonPersonObjectClient.setDetails(personObject.getDetails()); - return commonPersonObjectClient; - } - - @Override - public void startFormActivity(JSONObject jsonForm) { - Intent intent = new Intent(this, BaseOpdFormActivity.class); - intent.putExtra(OpdConstants.JSON_FORM_EXTRA.JSON, jsonForm.toString()); - Form form = new Form(); - form.setName(getString(R.string.update_client_registration)); - form.setActionBarBackground(R.color.family_actionbar); - form.setNavigationBackground(R.color.family_navigation); - form.setHomeAsUpIndicator(R.mipmap.ic_cross_white); - form.setPreviousLabel(getResources().getString(R.string.back)); - form.setWizard(false); - intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); - startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); - } - @Override protected BaseProfileContract.Presenter getFamilyOtherMemberActivityPresenter( String familyBaseEntityId, String baseEntityId, String familyHead, String primaryCaregiver, String villageTown, String familyName) { @@ -280,21 +259,6 @@ protected void initializePresenter() { allClientsMemberPresenter = new AllClientsMemberPresenter(this, baseEntityId); } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (resultCode != Activity.RESULT_OK) return; - try { - String jsonString = data.getStringExtra(JSON_FORM_EXTRA.JSON); - JSONObject form = new JSONObject(jsonString); - if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyRegister.updateEventType)) { - getAllClientsMemberPresenter().updateLocationInfo(jsonString, familyBaseEntityId); - } - } catch (Exception e) { - Timber.e(e); - } - } - @Override protected ViewPager setupViewPager(ViewPager viewPager) { adapter = new ViewPagerAdapter(getSupportFragmentManager()); @@ -321,6 +285,16 @@ protected void startHfMalariaFollowupForm() { //Implements from super } + @Override + protected void startPmtctRegisration() { + //do nothing - implementation in hf + } + + @Override + protected void startLDRegistration() { + //do nothing - implementation in hf + } + @Override protected void setIndependentClient(boolean isIndependentClient) { super.isIndependent = isIndependentClient; @@ -333,7 +307,7 @@ public void onClickMenu(int viewId) { FamilyCallDialogFragment.launchDialog(this, familyBaseEntityId); break; case R.id.refer_to_facility_layout: - Utils.launchClientReferralActivity(this, Utils.getCommonReferralTypes(this), baseEntityId); + Utils.launchClientReferralActivity(this, Utils.getCommonReferralTypes(this, baseEntityId), baseEntityId); break; default: break; @@ -341,7 +315,7 @@ public void onClickMenu(int viewId) { } @Override - public AllClientsMemberContract.Presenter getAllClientsMemberPresenter() { + public CoreAllClientsMemberContract.Presenter getAllClientsMemberPresenter() { return allClientsMemberPresenter; } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsRegisterActivity.java index c302fc85f7..2c366dfc79 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsRegisterActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllClientsRegisterActivity.java @@ -7,36 +7,23 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import com.google.android.material.bottomnavigation.BottomNavigationView; -import com.vijay.jsonwizard.constants.JsonFormConstants; -import com.vijay.jsonwizard.domain.Form; - -import org.json.JSONException; -import org.json.JSONObject; import org.smartregister.AllConstants; import org.smartregister.chw.R; import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.core.activity.CoreAllClientsRegisterActivity; +import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.fragment.AllClientsRegisterFragment; import org.smartregister.chw.model.ChwAllClientsRegisterModel; import org.smartregister.chw.presenter.ChwAllClientRegisterPresenter; -import org.smartregister.chw.util.Constants; -import org.smartregister.chw.util.JsonFormUtils; import org.smartregister.chw.util.Utils; import org.smartregister.helper.BottomNavigationHelper; -import org.smartregister.opd.activity.BaseOpdFormActivity; import org.smartregister.opd.contract.OpdRegisterActivityContract; -import org.smartregister.opd.pojo.RegisterParams; import org.smartregister.opd.presenter.BaseOpdRegisterActivityPresenter; -import org.smartregister.opd.utils.OpdConstants; -import org.smartregister.opd.utils.OpdJsonFormUtils; -import org.smartregister.opd.utils.OpdUtils; import org.smartregister.view.fragment.BaseRegisterFragment; import timber.log.Timber; -public class AllClientsRegisterActivity extends CoreAllClientsRegisterActivity - implements BottomNavigationView.OnNavigationItemSelectedListener { +public class AllClientsRegisterActivity extends CoreAllClientsRegisterActivity { @Override public void onCreate(@Nullable Bundle savedInstanceState) { @@ -51,14 +38,14 @@ protected BaseRegisterFragment getRegisterFragment() { @Override public void startRegistration() { - startFormActivity(Constants.ALL_CLIENT_REGISTRATION_FORM,null, null); + startFormActivity(CoreConstants.JSON_FORM.getAllClientRegistrationForm(), null, null); } @Override public void startFormActivity(String formName, String entityId, String metaData) { try { String locationId = org.smartregister.family.util.Utils.context().allSharedPreferences().getPreference(AllConstants.CURRENT_LOCATION_ID); - ((ChwAllClientRegisterPresenter)presenter()).startForm(formName, entityId, metaData, locationId); + ((ChwAllClientRegisterPresenter) presenter()).startForm(formName, entityId, metaData, locationId); } catch (Exception e) { Timber.e(e); @@ -66,44 +53,6 @@ public void startFormActivity(String formName, String entityId, String metaData) } } - @Override - public void startFormActivity(JSONObject jsonObject) { - Intent intent = new Intent(this, BaseOpdFormActivity.class); - intent.putExtra(OpdConstants.JSON_FORM_EXTRA.JSON, jsonObject.toString()); - - Form form = new Form(); - form.setName(getString(R.string.client_registration)); - form.setActionBarBackground(R.color.family_actionbar); - form.setNavigationBackground(R.color.family_navigation); - form.setHomeAsUpIndicator(R.mipmap.ic_cross_white); - form.setPreviousLabel(getResources().getString(R.string.back)); - intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); - - startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); - } - - @Override - protected void onActivityResultExtended(int requestCode, int resultCode, Intent data) { - if (requestCode == OpdJsonFormUtils.REQUEST_CODE_GET_JSON && resultCode == RESULT_OK) { - try { - String jsonString = data.getStringExtra(OpdConstants.JSON_FORM_EXTRA.JSON); - Timber.d("JSONResult : %s", jsonString); - - JSONObject form = new JSONObject(jsonString); - String encounterType = form.getString(OpdJsonFormUtils.ENCOUNTER_TYPE); - if (encounterType.equals(Constants.EventType.FAMILY_REGISTRATION)) { - RegisterParams registerParam = new RegisterParams(); - registerParam.setEditMode(false); - registerParam.setFormTag(OpdJsonFormUtils.formTag(OpdUtils.context().allSharedPreferences())); - showProgressDialog(R.string.saving_dialog_title); - presenter().saveForm(jsonString, registerParam); - } - } catch (JSONException e) { - Timber.e(e); - } - } - } - @Override protected void registerBottomNavigation() { bottomNavigationHelper = new BottomNavigationHelper(); @@ -120,7 +69,7 @@ protected BaseOpdRegisterActivityPresenter createPresenter( @Override public void switchToBaseFragment() { - Intent intent = new Intent(this, FamilyRegisterActivity.class); + Intent intent = new Intent(this, AllClientsRegisterActivity.class); startActivity(intent); finish(); } @@ -144,6 +93,6 @@ public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { } public OpdRegisterActivityContract.Model createActivityModel() { - return new ChwAllClientsRegisterModel(); + return new ChwAllClientsRegisterModel(this); } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllMaleClientsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllMaleClientsActivity.java new file mode 100644 index 0000000000..e663dd0e36 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AllMaleClientsActivity.java @@ -0,0 +1,45 @@ +package org.smartregister.chw.activity; + +import android.view.View; +import android.widget.ImageView; + +import org.smartregister.chw.R; +import org.smartregister.chw.fragment.AllMaleClientsRegisterFragment; +import org.smartregister.view.activity.SecuredActivity; + +import androidx.fragment.app.FragmentTransaction; + +public class AllMaleClientsActivity extends SecuredActivity implements View.OnClickListener { + @Override + protected void onCreation() { + setContentView(R.layout.activity_all_male_clients); + setupViews(); + } + + @Override + protected void onResumption() { + //overridden + } + + public void setupViews() { + ImageView closeImageView = findViewById(R.id.close); + closeImageView.setOnClickListener(this); + + loadFragment(); + } + + private void loadFragment() { + FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); + // Replace the contents of the container with the new fragment + ft.replace(R.id.fragment_placeholder, new AllMaleClientsRegisterFragment()); + ft.commit(); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.close) { + finish(); + } + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHfMedicalHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHfMedicalHistoryActivity.java new file mode 100644 index 0000000000..684c24d3be --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHfMedicalHistoryActivity.java @@ -0,0 +1,38 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.view.View; + +import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.presenter.BaseAncMedicalHistoryPresenter; +import org.smartregister.chw.anc.util.Constants; +import org.smartregister.chw.core.activity.CoreAncMedicalHistoryActivity; +import org.smartregister.chw.interactor.AncHfMedicalHistoryInteractor; + +import java.util.List; + +public class AncHfMedicalHistoryActivity extends CoreAncMedicalHistoryActivity { + private Flavor flavor = new AncHfMedicalHistoryActivityFlv(); + + public static void startMe(Activity activity, MemberObject memberObject) { + Intent intent = new Intent(activity, AncHfMedicalHistoryActivity.class); + intent.putExtra(Constants.ANC_MEMBER_OBJECTS.MEMBER_PROFILE_OBJECT, memberObject); + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncMedicalHistoryPresenter(new AncHfMedicalHistoryInteractor(), this, memberObject.getBaseEntityId()); + } + @Override + public View renderView(List visits) { + super.renderView(visits); + View view = flavor.bindViews(this); + displayLoadingState(true); + flavor.processViewData(visits, this); + displayLoadingState(false); + return view; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHomeVisitActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHomeVisitActivity.java index fa4a415d93..d07ff8bf5f 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHomeVisitActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncHomeVisitActivity.java @@ -3,12 +3,14 @@ import android.app.Activity; import android.content.Context; import android.content.Intent; +import android.os.Build; import com.vijay.jsonwizard.constants.JsonFormConstants; import com.vijay.jsonwizard.domain.Form; import org.json.JSONObject; import org.smartregister.chw.anc.activity.BaseAncHomeVisitActivity; +import org.smartregister.chw.anc.model.BaseAncHomeVisitAction; import org.smartregister.chw.anc.presenter.BaseAncHomeVisitPresenter; import org.smartregister.chw.core.R; import org.smartregister.chw.core.task.RunnableTask; @@ -21,6 +23,8 @@ import org.smartregister.util.LangUtils; import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Map; import timber.log.Timber; @@ -78,4 +82,29 @@ public void onDestroy() { Timber.e(e); } } + + @Override + public void initializeActions(LinkedHashMap map) { + actionList.clear(); + //Necessary evil to rearrange the actions according to a specific arrangement + if (map.containsKey(getString(R.string.anc_home_visit_danger_signs))) { + BaseAncHomeVisitAction dangerSignsAction = map.get(getString(R.string.anc_home_visit_danger_signs)); + actionList.put(getString(R.string.anc_home_visit_danger_signs), dangerSignsAction); + } + //====================End of Necessary evil ==================================== + + for (Map.Entry entry : map.entrySet()) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + actionList.putIfAbsent(entry.getKey(), entry.getValue()); + } else { + actionList.put(entry.getKey(), entry.getValue()); + } + } + + if (mAdapter != null) { + mAdapter.notifyDataSetChanged(); + } + displayProgressBar(false); + redrawVisitUI(); + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberMapActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberMapActivity.java index c08da92b6f..2a329608b9 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberMapActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberMapActivity.java @@ -42,6 +42,7 @@ public class AncMemberMapActivity extends AppCompatActivity { private GeoJsonSource communityTransportersSource; private LatLng userLocation; private static int BOUNDING_BOX_PADDING = 100; + public static final String GPS = "GPS"; @Override protected void onCreate(Bundle savedInstanceState) { @@ -92,8 +93,22 @@ private void featureClicked(@NonNull Feature feature) { @Nullable private LatLng extractUserLocation() { + double latitude = Double.parseDouble("-1.9885"); double longitude = Double.parseDouble("33.7799"); + + String gpsString = this.getIntent().getStringExtra(GPS); + + if (gpsString != null) { + try { + String[] gpsCoordinates = gpsString.split(" "); + latitude = Double.parseDouble(gpsCoordinates[0]); + longitude = Double.parseDouble(gpsCoordinates[1]); + } catch (Exception e) { + e.printStackTrace(); + } + } + return new LatLng(latitude, longitude); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberProfileActivity.java index 4df229134e..6c1a137bd4 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncMemberProfileActivity.java @@ -1,5 +1,12 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.core.utils.Utils.getCommonPersonObjectClient; +import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.chw.util.Utils.getClientGender; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + import android.app.Activity; import android.content.ContentValues; import android.content.Intent; @@ -10,9 +17,13 @@ import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +import com.vijay.jsonwizard.utils.FormUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.R; @@ -29,23 +40,29 @@ import org.smartregister.chw.core.application.CoreChwApplication; import org.smartregister.chw.core.form_data.NativeFormsDataBinder; import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.model.CoreAllClientsMemberModel; import org.smartregister.chw.core.utils.ChwNotificationUtil; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.core.utils.UpdateDetailsUtil; import org.smartregister.chw.custom_view.AncFloatingMenu; import org.smartregister.chw.dataloader.AncMemberDataLoader; import org.smartregister.chw.dataloader.FamilyMemberDataLoader; +import org.smartregister.chw.hivst.dao.HivstDao; import org.smartregister.chw.interactor.AncMemberProfileInteractor; +import org.smartregister.chw.kvp.dao.KvpDao; import org.smartregister.chw.malaria.dao.MalariaDao; import org.smartregister.chw.model.FamilyProfileModel; import org.smartregister.chw.model.ReferralTypeModel; import org.smartregister.chw.presenter.AncMemberProfilePresenter; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.util.UtilsFlv; import org.smartregister.clientandeventmodel.Event; import org.smartregister.commonregistry.AllCommonsRepository; import org.smartregister.commonregistry.CommonPersonObject; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.domain.AlertStatus; import org.smartregister.domain.Task; import org.smartregister.family.domain.FamilyEventClient; import org.smartregister.family.interactor.FamilyProfileInteractor; @@ -65,10 +82,6 @@ import io.reactivex.schedulers.Schedulers; import timber.log.Timber; -import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; -import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; -import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; - public class AncMemberProfileActivity extends CoreAncMemberProfileActivity implements AncMemberProfileContract.View { private List referralTypeModels = new ArrayList<>(); @@ -109,6 +122,22 @@ protected void onCreation() { } } + @Override + public void setupViews() { + super.setupViews(); + + RelativeLayout lastVisitHf = findViewById(R.id.rlLastVisitHf); + Visit firstVisit = getVisit(org.smartregister.chw.util.Constants.Events.ANC_FIRST_FACILITY_VISIT); + Visit recurringVisit = getVisit(org.smartregister.chw.util.Constants.Events.ANC_FIRST_FACILITY_VISIT); + + if (firstVisit != null || recurringVisit != null) { + lastVisitHf.setVisibility(View.VISIBLE); + lastVisitHf.setOnClickListener(this); + } else { + lastVisitHf.setVisibility(View.GONE); + } + } + @Override public void initializeFloatingMenu() { baseAncFloatingMenu = new AncFloatingMenu(this, getAncWomanName(), @@ -152,12 +181,6 @@ private void addAncReferralTypes() { BuildConfig.USE_UNIFIED_REFERRAL_APPROACH ? org.smartregister.chw.util.Constants.JSON_FORM.getAncUnifiedReferralForm() : org.smartregister.chw.util.Constants.JSON_FORM.getAncReferralForm(), CoreConstants.TASKS_FOCUS.ANC_DANGER_SIGNS)); if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { - referralTypeModels.add(new ReferralTypeModel(getString(R.string.hiv_referral), - org.smartregister.chw.util.Constants.JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_HIV)); - - referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), - org.smartregister.chw.util.Constants.JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); - referralTypeModels.add(new ReferralTypeModel(getString(R.string.gbv_referral), org.smartregister.chw.util.Constants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); } @@ -181,10 +204,32 @@ public boolean onOptionsItemSelected(MenuItem item) { IndividualProfileRemoveActivity.startIndividualProfileActivity(AncMemberProfileActivity.this, client, memberObject.getFamilyBaseEntityId(), memberObject.getFamilyHead(), memberObject.getPrimaryCareGiver(), AncRegisterActivity.class.getCanonicalName()); return true; } else if (itemId == R.id.action_pregnancy_out_come) { - CoreConstants.JSON_FORM.setLocaleAndAssetManager(ChwApplication.getCurrentLocale(), ChwApplication.getInstance().getApplicationContext().getAssets()); PncRegisterActivity.startPncRegistrationActivity(AncMemberProfileActivity.this, memberObject.getBaseEntityId(), null, CoreConstants.JSON_FORM.getPregnancyOutcome(), AncLibrary.getInstance().getUniqueIdRepository().getNextUniqueId().getOpenmrsId(), memberObject.getFamilyBaseEntityId(), memberObject.getFamilyName(), memberObject.getLastMenstrualPeriod()); return true; } + if (itemId == R.id.action_cbhs_registration) { + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(memberObject.getBaseEntityId()); + startCBHSRegister(commonPersonObject); + return true; + } + if(itemId == R.id.action_hivst_registration){ + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(memberObject.getBaseEntityId()); + final CommonPersonObjectClient client = + new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + HivstRegisterActivity.startHivstRegistrationActivity(this, baseEntityID, gender); + } + if(itemId == R.id.action_kvp_prep_registration){ + String gender = getClientGender(baseEntityID); + int age = memberObject.getAge(); + KvpPrEPRegisterActivity.startRegistration(AncMemberProfileActivity.this, baseEntityID, gender, age); + return true; + } return super.onOptionsItemSelected(item); } @@ -192,7 +237,19 @@ public boolean onOptionsItemSelected(MenuItem item) { public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.findItem(R.id.anc_danger_signs_outcome).setVisible(false); - menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); + menu.findItem(R.id.action_malaria_diagnosis).setVisible(!MalariaDao.isRegisteredForMalaria(baseEntityID)); + menu.findItem(R.id.action_pregnancy_out_come).setVisible(true); + menu.findItem(R.id.action_anc_registration).setVisible(false); + if(ChwApplication.getApplicationFlavor().hasHIVST()){ + int age = memberObject.getAge(); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(baseEntityID) && age >= 15); + } + if(ChwApplication.getApplicationFlavor().hasKvp()){ + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(baseEntityID)); + } + UtilsFlv.updateHivMenuItems(baseEntityID, menu); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + UtilsFlv.updateMalariaMenuItems(baseEntityID, menu); return true; } @@ -228,6 +285,11 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(CoreConstants.EventType.ANC_REFERRAL)) { ancMemberProfilePresenter().createReferralEvent(Utils.getAllSharedPreferences(), jsonString); showToast(this.getString(R.string.referral_submitted)); + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyRegister.updateEventType)) { + CommonPersonObjectClient client = getCommonPersonObjectClient(memberObject.getBaseEntityId()); + FamilyEventClient familyEventClient = new CoreAllClientsMemberModel().processJsonForm(jsonString, UpdateDetailsUtil.getFamilyBaseEntityId(client)); + familyEventClient.getEvent().setEntityType(CoreConstants.TABLE_NAME.INDEPENDENT_CLIENT); + new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, ancMemberProfilePresenter()); } } catch (Exception e) { @@ -265,6 +327,13 @@ public void startFormForEdit(Integer title_resource, String formName) { binder.setDataLoader(new FamilyMemberDataLoader(memberObject.getFamilyName(), isPrimaryCareGiver, titleString, eventName, memberObject.getChwMemberId())); form = binder.getPrePopulatedForm(CoreConstants.JSON_FORM.getFamilyMemberRegister()); + } else if (formName.equals(CoreConstants.JSON_FORM.getAllClientUpdateRegistrationInfoForm())) { + String eventName = org.smartregister.chw.util.Utils.metadata().familyMemberRegister.updateEventType; + + NativeFormsDataBinder binder = new NativeFormsDataBinder(this, memberObject.getBaseEntityId()); + binder.setDataLoader(new FamilyMemberDataLoader(memberObject.getFamilyName(), isPrimaryCareGiver, titleString, eventName, memberObject.getChwMemberId())); + + form = binder.getPrePopulatedForm(CoreConstants.JSON_FORM.getAllClientUpdateRegistrationInfoForm()); } startActivityForResult(org.smartregister.chw.util.JsonFormUtils.getAncPncStartFormIntent(form, this), JsonFormUtils.REQUEST_CODE_GET_JSON); @@ -305,9 +374,14 @@ public void openFamilyDueServices() { startActivity(intent); } + @Override + protected void startLDRegistration() { + //do nothing + } + @Override public void setFamilyLocation() { - if (ChwApplication.getApplicationFlavor().flvSetFamilyLocation()) { + if (ChwApplication.getApplicationFlavor().flvSetFamilyLocation() && getMemberGPS() != null) { view_family_location_row.setVisibility(View.VISIBLE); rlFamilyLocation.setVisibility(View.VISIBLE); } @@ -325,6 +399,8 @@ public void onClick(View view) { AncHomeVisitActivity.startMe(this, memberObject.getBaseEntityId(), false); } else if (id == R.id.textview_edit) { AncHomeVisitActivity.startMe(this, memberObject.getBaseEntityId(), true); + } else if (id == R.id.rlLastVisitHf) { + AncHfMedicalHistoryActivity.startMe(this, memberObject); } handleNotificationRowClick(this, view, notificationListAdapter, memberObject.getBaseEntityId()); } @@ -383,9 +459,32 @@ public void startFormActivity(JSONObject formJson) { } + protected void startCBHSRegister(CommonPersonObject commonPersonObject) { + String gender = org.smartregister.chw.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + String dob = org.smartregister.chw.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.DOB, false); + int age = org.smartregister.chw.util.Utils.getAgeFromDate(dob); + + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(AncMemberProfileActivity.this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + updateAgeAndGender(fields, age, gender); + + HivRegisterActivity.startHIVFormActivity(AncMemberProfileActivity.this, memberObject.getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + @Override public void openFamilyLocation() { Intent intent = new Intent(this, AncMemberMapActivity.class); + intent.putExtra(AncMemberMapActivity.GPS, getMemberGPS()); this.startActivity(intent); } @@ -400,10 +499,17 @@ public void onReceivedNotifications(List> notifications) { handleReceivedNotifications(this, notifications, notificationListAdapter); } + @Override + public void setFamilyStatus(AlertStatus status) { + super.setFamilyStatus(status); + if (memberObject.getFamilyBaseEntityId().isEmpty()) { + rlFamilyServicesDue.setVisibility(View.GONE); + } + } + public interface Flavor { Boolean hasFamilyLocationRow(); Boolean hasEmergencyTransport(); } - } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncPartnerFollowupReferralProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncPartnerFollowupReferralProfileActivity.java new file mode 100644 index 0000000000..c2dcfd9dd4 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncPartnerFollowupReferralProfileActivity.java @@ -0,0 +1,488 @@ +package org.smartregister.chw.activity; + +import static android.view.View.GONE; +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.INTENT_BASE_ENTITY_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.INTENT_FORM_SUBMISSION_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.REFERRAL_FORM_SUBMISSION_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.ReferralFormId; +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; +import static org.smartregister.util.JsonFormUtils.STEP1; +import static org.smartregister.util.JsonFormUtils.VALUE; + +import android.app.Activity; +import android.content.ContentValues; +import android.content.Intent; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Pair; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +import androidx.appcompat.widget.AppCompatButton; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.util.Constants; +import org.smartregister.chw.anc.util.DBConstants; +import org.smartregister.chw.anc.util.NCUtils; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.contract.AncMemberProfileContract; +import org.smartregister.chw.core.activity.CoreAncMemberProfileActivity; +import org.smartregister.chw.core.adapter.NotificationListAdapter; +import org.smartregister.chw.core.application.CoreChwApplication; +import org.smartregister.chw.core.form_data.NativeFormsDataBinder; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.utils.ChwNotificationUtil; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.custom_view.AncFloatingMenu; +import org.smartregister.chw.dao.AncPartnerDao; +import org.smartregister.chw.dataloader.AncMemberDataLoader; +import org.smartregister.chw.dataloader.FamilyMemberDataLoader; +import org.smartregister.chw.interactor.AncMemberProfileInteractor; +import org.smartregister.chw.model.FamilyProfileModel; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.presenter.AncMemberProfilePresenter; +import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.util.UtilsFlv; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.commonregistry.AllCommonsRepository; +import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.domain.AlertStatus; +import org.smartregister.domain.Task; +import org.smartregister.family.domain.FamilyEventClient; +import org.smartregister.family.interactor.FamilyProfileInteractor; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import io.reactivex.Observable; +import io.reactivex.Observer; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.Disposable; +import io.reactivex.schedulers.Schedulers; +import timber.log.Timber; + +public class AncPartnerFollowupReferralProfileActivity extends CoreAncMemberProfileActivity implements AncMemberProfileContract.View { + + private List referralTypeModels = new ArrayList<>(); + private NotificationListAdapter notificationListAdapter = new NotificationListAdapter(); + private String referralFormSubmissionId; + private RelativeLayout partnerView; + + public static void startMe(Activity activity, String baseEntityID, String formSubmissionId) { + Intent intent = new Intent(activity, AncPartnerFollowupReferralProfileActivity.class); + passToolbarTitle(activity, intent); + intent.putExtra(Constants.ANC_MEMBER_OBJECTS.BASE_ENTITY_ID, baseEntityID); + intent.putExtra(INTENT_FORM_SUBMISSION_ID, formSubmissionId); + activity.startActivity(intent); + } + + private void checkPhoneNumberProvided() { + ((AncFloatingMenu) baseAncFloatingMenu).redraw(!StringUtils.isBlank(memberObject.getPhoneNumber()) + || !StringUtils.isBlank(getFamilyHeadPhoneNumber())); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + notificationAndReferralRecyclerView.setAdapter(notificationListAdapter); + notificationListAdapter.setOnClickListener(this); + this.referralFormSubmissionId = getIntent().getStringExtra(INTENT_FORM_SUBMISSION_ID); + } + + @Override + public void setupViews() { + super.setupViews(); + CustomFontTextView titleView = findViewById(R.id.toolbar_title); + String titleText = TextUtils.isEmpty(getTitleViewText()) ? getString(R.string.return_to_all_partner_followup_clients) : getTitleViewText(); + titleView.setText(titleText); + layoutRecordView.setVisibility(View.VISIBLE); + if (AncPartnerDao.isPartnerFollowedUp(referralFormSubmissionId)) { + textview_record_visit.setVisibility(View.GONE); + } + textViewAncVisitNot.setVisibility(GONE); + tvEdit.setVisibility(View.GONE); + textview_record_visit.setText(R.string.record_followup_feedback); + textview_record_visit.setBackgroundResource(org.smartregister.chw.core.R.drawable.record_btn_anc_selector); + textview_record_visit.setOnClickListener(view -> { + JSONObject formJsonObject = null; + try { + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, CoreConstants.JSON_FORM.getAncPartnerCommunityFollowupFeedback()); + AllSharedPreferences preferences = ChwApplication.getInstance().getContext().allSharedPreferences(); + JSONObject chwName = getFieldJSONObject(fields(formJsonObject, STEP1), "chw_name"); + chwName.put(VALUE, preferences.getANMPreferredName(preferences.fetchRegisteredANM())); + startFormActivity(formJsonObject); + } catch (JSONException e) { + e.printStackTrace(); + } + }); + + partnerView = findViewById(R.id.rlPartnerView); + AppCompatButton registerBtn = findViewById(R.id.register_partner_btn); + if (AncPartnerDao.hasPartnerAgreeForRegistration(referralFormSubmissionId) && !AncPartnerDao.isPartnerRegistered(referralFormSubmissionId)) { + partnerView.setVisibility(View.VISIBLE); + } + + if (AncPartnerDao.isPartnerAlreadyRegistered(referralFormSubmissionId)) + partnerView.setVisibility(View.GONE); + + partnerView.setOnClickListener(this); + registerBtn.setOnClickListener(this); + } + + @Override + protected void onResume() { + super.onResume(); + notificationListAdapter.canOpen = true; + ChwNotificationUtil.retrieveNotifications(ChwApplication.getApplicationFlavor().hasReferrals(), + memberObject.getBaseEntityId(), this); + } + + @Override + protected void onCreation() { + super.onCreation(); + } + + @Override + public void initializeFloatingMenu() { + baseAncFloatingMenu = new AncFloatingMenu(this, getAncWomanName(), + memberObject.getPhoneNumber(), getFamilyHeadName(), getFamilyHeadPhoneNumber(), getProfileType()); + + baseAncFloatingMenu.findViewById(R.id.refer_to_facility_layout).setVisibility(GONE); + + OnClickFloatingMenu onClickFloatingMenu = viewId -> { + switch (viewId) { + case R.id.anc_fab: + checkPhoneNumberProvided(); + ((AncFloatingMenu) baseAncFloatingMenu).animateFAB(); + break; + case R.id.call_layout: + ((AncFloatingMenu) baseAncFloatingMenu).launchCallWidget(); + ((AncFloatingMenu) baseAncFloatingMenu).animateFAB(); + break; + case R.id.refer_to_facility_layout: + ((AncMemberProfilePresenter) ancMemberProfilePresenter()).referToFacility(); + ((AncFloatingMenu) baseAncFloatingMenu).animateFAB(); + break; + default: + Timber.d("Unknown fab action"); + break; + } + + }; + + ((AncFloatingMenu) baseAncFloatingMenu).setFloatMenuClickListener(onClickFloatingMenu); + baseAncFloatingMenu.setGravity(Gravity.BOTTOM | Gravity.END); + LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + addContentView(baseAncFloatingMenu, linearLayoutParams); + } + + @Override + protected void onResumption() { + super.onResumption(); + setupViews(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_cbhs_registration) { + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(memberObject.getBaseEntityId()); + startCBHSRegister(commonPersonObject); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + menu.findItem(R.id.anc_danger_signs_outcome).setVisible(false); + menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); + menu.findItem(R.id.action_pregnancy_out_come).setVisible(false); + menu.findItem(R.id.action_anc_registration).setVisible(false); + menu.findItem(R.id.action_remove_member).setVisible(false); + menu.findItem(R.id.action_cbhs_registration).setVisible(false); + UtilsFlv.updateHivMenuItems(baseEntityID, menu); + return true; + } + + @Override // to chw + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode != RESULT_OK) return; + + if (requestCode == JsonFormUtils.REQUEST_CODE_GET_JSON) { + try { + String jsonString = data.getStringExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON); + JSONObject form = new JSONObject(jsonString); + if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyMemberRegister.updateEventType)) { + FamilyEventClient familyEventClient = + new FamilyProfileModel(memberObject.getFamilyName()).processUpdateMemberRegistration(jsonString, memberObject.getBaseEntityId()); + new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, ancMemberProfilePresenter()); + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(CoreConstants.EventType.UPDATE_ANC_REGISTRATION)) { + AllSharedPreferences allSharedPreferences = org.smartregister.util.Utils.getAllSharedPreferences(); + Event baseEvent = org.smartregister.chw.anc.util.JsonFormUtils.processJsonForm(allSharedPreferences, jsonString, Constants.TABLES.ANC_MEMBERS); + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(baseEvent))); + AllCommonsRepository commonsRepository = CoreChwApplication.getInstance().getAllCommonsRepository(CoreConstants.TABLE_NAME.ANC_MEMBER); + + JSONArray field = org.smartregister.util.JsonFormUtils.fields(form); + JSONObject phoneNumberObject = org.smartregister.util.JsonFormUtils.getFieldJSONObject(field, DBConstants.KEY.PHONE_NUMBER); + String phoneNumber = phoneNumberObject.getString(CoreJsonFormUtils.VALUE); + String baseEntityId = baseEvent.getBaseEntityId(); + if (commonsRepository != null) { + ContentValues values = new ContentValues(); + values.put(DBConstants.KEY.PHONE_NUMBER, phoneNumber); + CoreChwApplication.getInstance().getRepository().getWritableDatabase().update(CoreConstants.TABLE_NAME.ANC_MEMBER, values, DBConstants.KEY.BASE_ENTITY_ID + " = ? ", new String[]{baseEntityId}); + } + + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(CoreConstants.EventType.ANC_REFERRAL)) { + ancMemberProfilePresenter().createReferralEvent(Utils.getAllSharedPreferences(), jsonString); + showToast(this.getString(R.string.referral_submitted)); + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equalsIgnoreCase(CoreConstants.EventType.ANC_PARTNER_COMMUNITY_FOLLOWUP_FEEDBACK)) { + AllSharedPreferences allSharedPreferences = org.smartregister.util.Utils.getAllSharedPreferences(); + Event baseEvent = org.smartregister.chw.anc.util.JsonFormUtils.processJsonForm(allSharedPreferences, tagReferralFormId(jsonString, referralFormSubmissionId), CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP_FEEDBACK); + org.smartregister.chw.anc.util.JsonFormUtils.tagEvent(allSharedPreferences, baseEvent); + baseEvent.setBaseEntityId(baseEntityID); + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(baseEvent))); + setupViews(); + } + + } catch (Exception e) { + Timber.e(e, "AncMemberProfileActivity -- > onActivityResult"); + } + } else if (requestCode == Constants.REQUEST_CODE_HOME_VISIT) { + refreshViewOnHomeVisitResult(); + } else if (requestCode == CoreConstants.ProfileActivityResults.CHANGE_COMPLETED) { + ChwScheduleTaskExecutor.getInstance().execute(memberObject.getBaseEntityId(), CoreConstants.EventType.ANC_HOME_VISIT, new Date()); + finish(); + } + } + + private String tagReferralFormId(String jsonString, String formSubmissionId) throws JSONException { + JSONObject form = new JSONObject(jsonString); + JSONArray fields = org.smartregister.util.JsonFormUtils.fields(form); + JSONObject referralFormId = org.smartregister.util.JsonFormUtils.getFieldJSONObject(fields, ReferralFormId); + assert referralFormId != null; + referralFormId.put(JsonFormUtils.VALUE, formSubmissionId); + return form.toString(); + } + + @Override + public void startFormForEdit(Integer title_resource, String formName) { + try { + JSONObject form = null; + boolean isPrimaryCareGiver = memberObject.getPrimaryCareGiver().equals(memberObject.getBaseEntityId()); + String titleString = title_resource != null ? getResources().getString(title_resource) : null; + + if (formName.equals(CoreConstants.JSON_FORM.getAncRegistration())) { + + NativeFormsDataBinder binder = new NativeFormsDataBinder(this, memberObject.getBaseEntityId()); + binder.setDataLoader(new AncMemberDataLoader(titleString)); + form = binder.getPrePopulatedForm(formName); + if (form != null) { + form.put(JsonFormUtils.ENCOUNTER_TYPE, CoreConstants.EventType.UPDATE_ANC_REGISTRATION); + } + + } else if (formName.equals(CoreConstants.JSON_FORM.getFamilyMemberRegister())) { + + String eventName = org.smartregister.chw.util.Utils.metadata().familyMemberRegister.updateEventType; + + NativeFormsDataBinder binder = new NativeFormsDataBinder(this, memberObject.getBaseEntityId()); + binder.setDataLoader(new FamilyMemberDataLoader(memberObject.getFamilyName(), isPrimaryCareGiver, titleString, eventName, memberObject.getChwMemberId())); + + form = binder.getPrePopulatedForm(CoreConstants.JSON_FORM.getFamilyMemberRegister()); + } + + startActivityForResult(org.smartregister.chw.util.JsonFormUtils.getAncPncStartFormIntent(form, this), JsonFormUtils.REQUEST_CODE_GET_JSON); + } catch (Exception e) { + Timber.e(e); + } + } + + @Override + protected void registerPresenter() { + presenter = new AncMemberProfilePresenter(this, new AncMemberProfileInteractor(this), memberObject); + } + + @Override + public void openUpcomingService() { + Timber.i("openUpcomingService"); + } + + @Override + public void openFamilyDueServices() { + Timber.i("openFamilyDueServices"); + } + + @Override + protected void startLDRegistration() { + //implement + } + + @Override + public boolean usesPregnancyRiskProfileLayout() { + return false; + } + + @Override + public void setFamilyLocation() { + if (ChwApplication.getApplicationFlavor().flvSetFamilyLocation() && getMemberGPS() != null) { + view_family_location_row.setVisibility(View.VISIBLE); + rlFamilyLocation.setVisibility(View.VISIBLE); + } + } + + protected String getMemberGPS() { + return memberObject.getGps(); + } + + @Override + public void onClick(View view) { + super.onClick(view); + int id = view.getId(); + if (id == R.id.textview_record_visit || id == R.id.textview_record_reccuring_visit) { + AncHomeVisitActivity.startMe(this, memberObject.getBaseEntityId(), false); + } else if (id == R.id.textview_edit) { + AncHomeVisitActivity.startMe(this, memberObject.getBaseEntityId(), true); + } else if (id == R.id.rlPartnerView || id == R.id.register_partner_btn) { + Intent intent = new Intent(this, PartnerRegistrationActivity.class); + intent.putExtra(INTENT_FORM_SUBMISSION_ID, AncPartnerDao.getFeedbackFormId(referralFormSubmissionId)); + intent.putExtra(REFERRAL_FORM_SUBMISSION_ID, referralFormSubmissionId); + intent.putExtra(INTENT_BASE_ENTITY_ID, baseEntityID); + startActivity(intent); + } + handleNotificationRowClick(this, view, notificationListAdapter, memberObject.getBaseEntityId()); + } + + @Override + public void setClientTasks(Set taskList) { + //overridden + } + + @Override + public void onMemberDetailsReloaded(MemberObject memberObject) { + this.memberObject = memberObject; + super.onMemberDetailsReloaded(memberObject); + } + + private void refreshViewOnHomeVisitResult() { + Observable observable = Observable.create(visitObservableEmitter -> { + Visit lastVisit = getVisit(CoreConstants.EventType.ANC_HOME_VISIT); + visitObservableEmitter.onNext(lastVisit); + visitObservableEmitter.onComplete(); + }); + + final Disposable[] disposable = new Disposable[1]; + observable.subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(new Observer() { + @Override + public void onSubscribe(Disposable d) { + disposable[0] = d; + } + + @Override + public void onNext(Visit visit) { + displayView(); + setLastVisit(visit.getDate()); + onMemberDetailsReloaded(memberObject); + } + + @Override + public void onError(Throwable e) { + Timber.e(e); + } + + @Override + public void onComplete() { + disposable[0].dispose(); + disposable[0] = null; + } + }); + } + + @Override + public void startFormActivity(JSONObject formJson) { + startActivityForResult(CoreJsonFormUtils.getJsonIntent(this, formJson, Utils.metadata().familyMemberFormActivity), + JsonFormUtils.REQUEST_CODE_GET_JSON); + } + + + protected void startCBHSRegister(CommonPersonObject commonPersonObject) { + String gender = org.smartregister.chw.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + String dob = org.smartregister.chw.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.DOB, false); + int age = org.smartregister.chw.util.Utils.getAgeFromDate(dob); + + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(AncPartnerFollowupReferralProfileActivity.this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + updateAgeAndGender(fields, age, gender); + + HivRegisterActivity.startHIVFormActivity(AncPartnerFollowupReferralProfileActivity.this, memberObject.getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void openFamilyLocation() { + Intent intent = new Intent(this, AncMemberMapActivity.class); + this.startActivity(intent); + } + + + @Override + public List getReferralTypeModels() { + return referralTypeModels; + } + + @Override + public void onReceivedNotifications(List> notifications) { + handleReceivedNotifications(this, notifications, notificationListAdapter); + } + + @Override + public void setUpComingServicesStatus(String service, AlertStatus status, Date date) { + this.rlUpcomingServices.setVisibility(GONE); + } + + @Override + public void setFamilyStatus(AlertStatus status) { + this.rlFamilyServicesDue.setVisibility(GONE); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncRegisterActivity.java index 9345158aeb..414c87d802 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncRegisterActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/AncRegisterActivity.java @@ -1,26 +1,44 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.core.utils.CoreConstants.EventType.ANC_REGISTRATION; + import android.app.Activity; import android.content.Intent; +import android.view.MenuItem; + +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; + +import com.google.android.material.bottomnavigation.BottomNavigationView; +import com.vijay.jsonwizard.constants.JsonFormConstants; +import com.vijay.jsonwizard.domain.Form; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.smartregister.chw.R; import org.smartregister.chw.anc.util.Constants; +import org.smartregister.chw.anc.util.DBConstants; import org.smartregister.chw.core.activity.CoreAncRegisterActivity; import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.chw.fragment.AncPartnerFollowupRegisterFragment; import org.smartregister.chw.fragment.AncRegisterFragment; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.family.util.Utils; import org.smartregister.helper.BottomNavigationHelper; import org.smartregister.job.SyncServiceJob; import org.smartregister.view.fragment.BaseRegisterFragment; import java.util.Date; +import java.util.HashMap; +import java.util.Map; import timber.log.Timber; -import static org.smartregister.chw.core.utils.CoreConstants.EventType.ANC_REGISTRATION; - -public class AncRegisterActivity extends CoreAncRegisterActivity { +public class AncRegisterActivity extends CoreAncRegisterActivity implements BottomNavigationView.OnNavigationItemSelectedListener { public static void startAncRegistrationActivity(Activity activity, String memberBaseEntityID, String phoneNumber, String formName, String uniqueId, String familyBaseID, String family_name) { @@ -46,10 +64,12 @@ public Class getRegisterActivity(String register) { @Override protected void registerBottomNavigation() { - super.registerBottomNavigation(); bottomNavigationHelper = new BottomNavigationHelper(); bottomNavigationView = findViewById(R.id.bottom_navigation); - FamilyRegisterActivity.registerBottomNavigation(bottomNavigationHelper, bottomNavigationView, this); + bottomNavigationView.getMenu().clear(); + + bottomNavigationView.inflateMenu(R.menu.anc_bottom_nav_menu); + bottomNavigationView.setOnNavigationItemSelectedListener(this); } @Override @@ -57,13 +77,59 @@ protected BaseRegisterFragment getRegisterFragment() { return new AncRegisterFragment(); } + @Override + public void startFormActivity(JSONObject jsonForm) { + + try { + JSONObject stepOne = jsonForm.getJSONObject(JsonFormUtils.STEP1); + JSONArray jsonArray = stepOne.getJSONArray(JsonFormUtils.FIELDS); + + Map values = new HashMap<>(); + + values.put(DBConstants.KEY.TEMP_UNIQUE_ID, unique_id); + values.put(CoreConstants.JsonAssets.FAM_NAME, familyName); + values.put(CoreConstants.JsonAssets.FAMILY_MEMBER.PHONE_NUMBER, phone_number); + values.put(org.smartregister.family.util.DBConstants.KEY.RELATIONAL_ID, familyBaseEntityId); + values.put(DBConstants.KEY.LAST_MENSTRUAL_PERIOD, lastMenstrualPeriod); + try { + JSONObject min_date = CoreJsonFormUtils.getFieldJSONObject(jsonArray, "delivery_date"); + min_date.put("min_date", lastMenstrualPeriod); + }catch (Exception e){ + Timber.e(e); + } + + FormUtils.updateFormField(jsonArray, values); + + Intent intent = new Intent(this, Utils.metadata().familyMemberFormActivity); + intent.putExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON, jsonForm.toString()); + + Form form = new Form(); + form.setActionBarBackground(org.smartregister.chw.core.R.color.family_actionbar); + form.setNavigationBackground(org.smartregister.chw.core.R.color.family_navigation); + form.setName(getString(R.string.anc_registration)); + form.setWizard(true); + intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); + + startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } catch (JSONException e) { + Timber.e(e); + } + } + @Override public void switchToBaseFragment() { - Intent intent = new Intent(this, FamilyRegisterActivity.class); + Intent intent = new Intent(this, AncRegisterActivity.class); startActivity(intent); this.finish(); } + @Override + protected Fragment[] getOtherFragments() { + return new AncPartnerFollowupRegisterFragment[]{ + new AncPartnerFollowupRegisterFragment()}; + } + + protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK && requestCode == Constants.REQUEST_CODE_GET_JSON) { @@ -87,4 +153,16 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { finish(); } } + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { + if(menuItem.getItemId() == R.id.action_anc){ + switchToFragment(0); + return true; + } else if (menuItem.getItemId() == R.id.action_received_referrals){ + switchToFragment(1); + return true; + } + return false; + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsActivity.java new file mode 100644 index 0000000000..dac076457a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsActivity.java @@ -0,0 +1,127 @@ +package org.smartregister.chw.activity; + +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; + +import com.google.android.material.appbar.AppBarLayout; +import com.whiteelephant.monthpicker.MonthPickerDialog; + +import org.smartregister.chw.R; +import org.smartregister.chw.util.ReportUtils; +import org.smartregister.view.activity.SecuredActivity; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.widget.Toolbar; +import androidx.constraintlayout.widget.ConstraintLayout; +import timber.log.Timber; + +public class CBHSReportsActivity extends SecuredActivity implements View.OnClickListener { + + protected ConstraintLayout monthlyReport; + protected AppBarLayout appBarLayout; + Menu menu; + protected String reportPeriod = ReportUtils.getDefaultReportPeriod(); + + @Override + protected void onCreation() { + setContentView(R.layout.activity_cbhs_reports); + setUpToolbar(); + setupViews(); + } + + public void setupViews() { + monthlyReport = findViewById(R.id.cbhs_monthly_summary); + monthlyReport.setOnClickListener(this); + } + + @Override + protected void onResumption() { + // Do nothing + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.reports_menu, menu); + this.menu = menu; + this.menu.findItem(R.id.action_select_month).setTitle(ReportUtils.displayMonthAndYear()); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_select_month) { + showMonthPicker(this, menu); + return true; + } + return super.onOptionsItemSelected(item); + } + + + public void setUpToolbar() { + Toolbar toolbar = findViewById(org.smartregister.chw.core.R.id.back_to_nav_toolbar); + setSupportActionBar(toolbar); + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + final Drawable upArrow = getResources().getDrawable(org.smartregister.chw.core.R.drawable.ic_arrow_back_white_24dp); + actionBar.setHomeAsUpIndicator(upArrow); + actionBar.setElevation(0); + } + toolbar.setNavigationOnClickListener(v -> finish()); + appBarLayout = findViewById(org.smartregister.chw.core.R.id.app_bar); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + appBarLayout.setOutlineProvider(null); + } + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.cbhs_monthly_summary) { + CBHSReportsViewActivity.startMe(this, "cbhs-summary-monthly", reportPeriod); + } + } + + private void showMonthPicker(Context context, Menu menu) { + //shows the month picker and returns selected period and updated the menu + MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(context, (selectedMonth, selectedYear) -> { + int month = selectedMonth + 1; + String monthString = String.valueOf(month); + if (month < 10) { + monthString = "0" + monthString; + } + String yearString = String.valueOf(selectedYear); + reportPeriod = monthString + "-" + yearString; + menu.findItem(R.id.action_select_month).setTitle(ReportUtils.displayMonthAndYear(selectedMonth, selectedYear)); + + }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH)); + try { + Date reportDate = new SimpleDateFormat("MM-yyyy", Locale.getDefault()).parse(reportPeriod); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(reportDate); + builder.setActivatedMonth(calendar.get(Calendar.MONTH)); + builder.setMinYear(2021); + builder.setActivatedYear(calendar.get(Calendar.YEAR)); + builder.setMaxYear(Calendar.getInstance().get(Calendar.YEAR)); + builder.setMinMonth(Calendar.JANUARY); + builder.setMaxMonth(Calendar.DECEMBER); + builder.setTitle(getString(R.string.select_reporting_month)); + builder.build().show(); + } catch (ParseException e) { + Timber.e(e); + } + + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsViewActivity.java new file mode 100644 index 0000000000..d7551ca1f8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CBHSReportsViewActivity.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.R; +import org.smartregister.chw.util.Constants; + +public class CBHSReportsViewActivity extends ChwReportsViewActivity { + public static void startMe(Activity activity, String reportPath, String reportDate) { + Intent intent = new Intent(activity, CBHSReportsViewActivity.class); + intent.putExtra(ARG_REPORT_PATH, reportPath); + intent.putExtra(ARG_REPORT_DATE, reportDate); + intent.putExtra(ARG_REPORT_TITLE, R.string.cbhs_reports_title); + intent.putExtra(ARG_REPORT_TYPE, Constants.ReportConstants.ReportTypes.CBHS_REPORT); + activity.startActivity(intent); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivity.java new file mode 100644 index 0000000000..f54dbc7f1f --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivity.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.presenter.BaseAncMedicalHistoryPresenter; +import org.smartregister.chw.core.activity.CoreAncMedicalHistoryActivity; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.interactor.CbhsMedicalHistoryInteractor; + +import java.util.List; + +public class CbhsMedicalHistoryActivity extends CoreAncMedicalHistoryActivity { + private static HivMemberObject cbhsMemberObject; + private final Flavor flavor = new CbhsMedicalHistoryActivityFlv(); + private ProgressBar progressBar; + + public static void startMe(Activity activity, HivMemberObject memberObject) { + Intent intent = new Intent(activity, CbhsMedicalHistoryActivity.class); + cbhsMemberObject = memberObject; + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncMedicalHistoryPresenter(new CbhsMedicalHistoryInteractor(), this, cbhsMemberObject.getBaseEntityId()); + } + + @Override + public void setUpView() { + linearLayout = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.linearLayoutMedicalHistory); + progressBar = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.progressBarMedicalHistory); + + TextView tvTitle = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.tvTitle); + tvTitle.setText(getString(org.smartregister.chw.opensrp_chw_anc.R.string.back_to, cbhsMemberObject.getFirstName() + " " + cbhsMemberObject.getMiddleName() + " " + cbhsMemberObject.getLastName())); + + ((TextView) findViewById(R.id.medical_history)).setText(getString(R.string.visits_history)); + } + + @Override + public View renderView(List visits) { + super.renderView(visits); + View view = flavor.bindViews(this); + displayLoadingState(true); + flavor.processViewData(visits, this); + displayLoadingState(false); + TextView heiVisitTitle = view.findViewById(org.smartregister.chw.core.R.id.customFontTextViewHealthFacilityVisitTitle); + heiVisitTitle.setText(R.string.cbhs_visit); + return view; + } + + @Override + public void displayLoadingState(boolean state) { + progressBar.setVisibility(state ? View.VISIBLE : View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivityFlv.java new file mode 100644 index 0000000000..e1ccfa39fc --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsMedicalHistoryActivityFlv.java @@ -0,0 +1,203 @@ +package org.smartregister.chw.activity; + +import android.content.Context; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.BulletSpan; +import android.text.style.StyleSpan; +import android.view.View; +import android.widget.TextView; + +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.NCUtils; +import org.smartregister.chw.core.activity.DefaultAncMedicalHistoryActivityFlv; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import timber.log.Timber; + +public class CbhsMedicalHistoryActivityFlv extends DefaultAncMedicalHistoryActivityFlv { + private final StyleSpan boldSpan = new StyleSpan(android.graphics.Typeface.BOLD); + + @Override + protected void processAncCard(String has_card, Context context) { + // super.processAncCard(has_card, context); + linearLayoutAncCard.setVisibility(View.GONE); + } + + @Override + protected void processHealthFacilityVisit(List> hf_visits, Context context) { + //super.processHealthFacilityVisit(hf_visits, context); + } + + @Override + public void processViewData(List visits, Context context) { + + if (visits.size() > 0) { + int days = 0; + List> hf_visits = new ArrayList<>(); + + int x = 0; + while (x < visits.size()) { + + // the first object in this list is the days difference + if (x == 0) { + days = Days.daysBetween(new DateTime(visits.get(visits.size() - 1).getDate()), new DateTime()).getDays(); + } + + + String[] visitParams = {"followup_visit_date", "registration_or_followup_status", "client_condition", "health_problem", "social_problem", "supplies_provided", "medicine_provided", "hiv_services_provided", "referrals_issued_to_other_services", "referrals_to_other_services_completed", "state_of_therapy", "client_moved_location"}; + extractVisitDetails(visits, visitParams, hf_visits, x, context); + + x++; + } + + processLastVisit(days, context); + processVisit(hf_visits, context); + } + } + + private void extractVisitDetails(List sourceVisits, String[] hf_params, List> hf_visits, int iteration, Context context) { + // get the hf details + Map map = new HashMap<>(); + for (String param : hf_params) { + try { + List details = sourceVisits.get(iteration).getVisitDetails().get(param); + map.put(param, getTexts(context, details)); + } catch (Exception e) { + e.printStackTrace(); + } + + } + hf_visits.add(map); + } + + @Override + public String getTexts(Context context, List visitDetails) { + if (visitDetails == null) + return ""; + + List texts = new ArrayList<>(); + for (VisitDetail vd : visitDetails) { + String val = getText(vd); + if (StringUtils.isNotBlank(val)) + texts.add(val); + } + return NCUtils.toCSV(texts); + } + + /** + * Extract value from VisitDetail + * + * @return + */ + @NotNull + public static String getText(@Nullable VisitDetail visitDetail) { + if (visitDetail == null) + return ""; + return (StringUtils.isNotBlank(visitDetail.getDetails())) ? visitDetail.getDetails().trim() : ""; + } + + + private void processLastVisit(int days, Context context) { + linearLayoutLastVisit.setVisibility(View.VISIBLE); + if (days < 1) { + customFontTextViewLastVisit.setText(org.smartregister.chw.core.R.string.less_than_twenty_four); + } else { + customFontTextViewLastVisit.setText(StringUtils.capitalize(MessageFormat.format(context.getString(org.smartregister.chw.core.R.string.days_ago), String.valueOf(days)))); + } + } + + + protected void processVisit(List> hf_visits, Context context) { + if (hf_visits != null && hf_visits.size() > 0) { + linearLayoutHealthFacilityVisit.setVisibility(View.VISIBLE); + + int x = 0; + for (Map vals : hf_visits) { + View view = inflater.inflate(R.layout.medical_history_cbhs_visit, null); + TextView tvTitle = view.findViewById(R.id.title); + evaluateTitle(context, x, vals, tvTitle); + + evaluateView(context, vals, view.findViewById(R.id.registration_or_followup_status), "registration_or_followup_status", R.string.cbhs_registration_or_followup_status, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.health_problem), "health_problem", R.string.cbhs_health_problem, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.social_problem), "social_problem", R.string.cbhs_social_problem, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.medicine_provided), "medicine_provided", R.string.cbhs_medicine_provided, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.hiv_services_provided), "hiv_services_provided", R.string.cbhs_hiv_services_provided, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.referrals_issued_other_services), "referrals_issued_to_other_services", R.string.cbhs_referrals_issued_to_other_services, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.referrals_to_other_services_completed), "referrals_to_other_services_completed", R.string.cbhs_referrals_to_other_services_completed, "cbhs_"); + evaluateView(context, vals, view.findViewById(R.id.state_of_therapy), "state_of_therapy", R.string.cbhs_state_of_therapy, "cbhs_"); + + linearLayoutHealthFacilityVisitDetails.addView(view, 0); + + x++; + } + } + } + + + private void evaluateTitle(Context context, int x, Map vals, TextView tvTitle) { + String visitDate = vals.get("followup_visit_date"); + if (StringUtils.isBlank(visitDate)) { + tvTitle.setVisibility(View.GONE); + } else { + try { + tvTitle.setText(MessageFormat.format(context.getString(R.string.mother_champion_visit_title), x + 1, visitDate)); + } catch (Exception e) { + Timber.e(e); + } + } + } + + private void evaluateView(Context context, Map vals, TextView tv, String valueKey, int viewTitleStringResource, String valuePrefixInStringResources) { + if (StringUtils.isNotBlank(getMapValue(vals, valueKey))) { + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); + spannableStringBuilder.append(context.getString(viewTitleStringResource), boldSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).append("\n"); + + String stringValue = getMapValue(vals, valueKey); + String[] stringValueArray; + if (stringValue.contains(",")) { + stringValueArray = stringValue.split(","); + for (String value : stringValueArray) { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, value.trim()) + "\n", new BulletSpan(10), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } else { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, stringValue)).append("\n"); + } + tv.setText(spannableStringBuilder); + } else { + tv.setVisibility(View.GONE); + } + } + + + private String getMapValue(Map map, String key) { + if (map.containsKey(key)) { + return map.get(key); + } + return ""; + } + + private String getStringResource(Context context, String prefix, String resourceName) { + int resourceId = context.getResources(). + getIdentifier(prefix + resourceName.trim(), "string", context.getPackageName()); + try { + return context.getString(resourceId); + } catch (Exception e) { + Timber.e(e); + return prefix + resourceName; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsUpcomingServiceActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsUpcomingServiceActivity.java new file mode 100644 index 0000000000..4ed39193b8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CbhsUpcomingServiceActivity.java @@ -0,0 +1,23 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.presenter.BaseAncUpcomingServicesPresenter; +import org.smartregister.chw.anc.util.Constants; +import org.smartregister.chw.core.activity.CoreHivUpcomingServicesActivity; +import org.smartregister.chw.interactor.CbhsUpcomingServicesInteractor; + +public class CbhsUpcomingServiceActivity extends CoreHivUpcomingServicesActivity { + public static void startMe(Activity activity, MemberObject memberObject) { + Intent intent = new Intent(activity, CbhsUpcomingServiceActivity.class); + intent.putExtra(Constants.ANC_MEMBER_OBJECTS.MEMBER_PROFILE_OBJECT, memberObject); + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncUpcomingServicesPresenter(memberObject, new CbhsUpcomingServicesInteractor(), this); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpProfileActivity.java new file mode 100644 index 0000000000..ed13657a98 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpProfileActivity.java @@ -0,0 +1,208 @@ +package org.smartregister.chw.activity; + +import static com.vijay.jsonwizard.constants.JsonFormConstants.FIELDS; +import static com.vijay.jsonwizard.constants.JsonFormConstants.STEP1; +import static com.vijay.jsonwizard.constants.JsonFormConstants.VALUE; +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.chw.cdp.util.Constants.FORMS.EDIT_CDP_OUTLET; +import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; + +import android.app.Activity; +import android.content.Intent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.util.NCUtils; +import org.smartregister.chw.cdp.CdpLibrary; +import org.smartregister.chw.cdp.dao.CdpDao; +import org.smartregister.chw.cdp.domain.Visit; +import org.smartregister.chw.cdp.pojo.RegisterParams; +import org.smartregister.chw.cdp.util.CdpJsonFormUtils; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.cdp.util.VisitUtils; +import org.smartregister.chw.core.activity.CoreCdpProfileActivity; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.repository.AllSharedPreferences; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.UUID; + +import timber.log.Timber; + +public class CdpProfileActivity extends CoreCdpProfileActivity { + + public static void startProfile(Activity activity, String baseEntityId) { + Intent intent = new Intent(activity, CdpProfileActivity.class); + passToolbarTitle(activity, intent); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + activity.startActivity(intent); + } + + public static void disableOrEnableOutlet(AllSharedPreferences allSharedPreferences, String baseEntityId, String eventType) { + Event event = (Event) new Event().withBaseEntityId(baseEntityId).withEventDate(new Date()).withEventType(eventType).withLocationId(org.smartregister.chw.anc.util.JsonFormUtils.locationId(allSharedPreferences)).withProviderId(allSharedPreferences.fetchRegisteredANM()).withEntityType(Constants.TABLES.CDP_OUTLET).withFormSubmissionId(UUID.randomUUID().toString()).withDateCreated(new Date()); + try { + NCUtils.processEvent(event.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(event))); + } catch (Exception e) { + Timber.e(e); + } + } + + @Override + protected void startRestockingHistory() { + RestockingVisitHistoryActivity.startMe(this, outletObject); + } + + @Override + protected void setupViews() { + super.setupViews(); + tvLastVisitTitle.setText(R.string.restock_history); + } + + @Override + protected void onResume() { + super.onResume(); + setupViews(); + outletObject = CdpDao.getOutlet(outletObject.getBaseEntityId()); + initializePresenter(); + updateFollowupButton(); + + try { + List restockVisits = VisitUtils.getVisits(outletObject.getBaseEntityId()); + if (restockVisits.size() > 0) { + Date lastRestockDate = restockVisits.get(restockVisits.size() - 1).getDate(); + tvLastVisitSub.setText(String.format(this.getString(R.string.last_restock_date), new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(lastRestockDate))); + } else { + tvLastVisitSub.setVisibility(View.GONE); + } + + } catch (Exception e) { + Timber.e(e); + tvLastVisitSub.setVisibility(View.GONE); + } + + } + + public boolean onCreateOptionsMenu(Menu menu) { + this.getMenuInflater().inflate(R.menu.cdp_outlet_profile_menu, menu); + + if (outletObject.isClosed()) { + menu.findItem(R.id.action_disable_outlet).setVisible(false); + menu.findItem(R.id.action_edit_outlet).setVisible(false); + menu.findItem(R.id.action_enable_outlet).setVisible(true); + } else { + menu.findItem(R.id.action_edit_outlet).setVisible(true); + menu.findItem(R.id.action_disable_outlet).setVisible(true); + menu.findItem(R.id.action_enable_outlet).setVisible(false); + } + return true; + } + + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_edit_outlet) { + this.startFormForEdit(R.string.registration_info, EDIT_CDP_OUTLET); + return true; + } else if (itemId == R.id.action_disable_outlet) { + AllSharedPreferences allSharedPreferences = org.smartregister.util.Utils.getAllSharedPreferences(); + disableOrEnableOutlet(allSharedPreferences, outletObject.getBaseEntityId(), Constants.EVENT_TYPE.DISABLE_CDP_OUTLET); + onResume(); + invalidateOptionsMenu(); + return true; + } else if (itemId == R.id.action_enable_outlet) { + AllSharedPreferences allSharedPreferences = org.smartregister.util.Utils.getAllSharedPreferences(); + disableOrEnableOutlet(allSharedPreferences, outletObject.getBaseEntityId(), Constants.EVENT_TYPE.ENABLE_CDP_OUTLET); + onResume(); + invalidateOptionsMenu(); + return true; + } + return false; + } + + /** + * This method starts the form for edit with the given title resource and form name. + * + * @param title_resource The resource ID of the form's title + * @param formName The name of the form + */ + public void startFormForEdit(Integer title_resource, String formName) { + try { + JSONObject form = null; + if (formName.equals(EDIT_CDP_OUTLET)) { + form = CoreJsonFormUtils.getAutoJsonEditAncFormString(outletObject.getBaseEntityId(), CdpProfileActivity.this, formName, Constants.EVENT_TYPE.UPDATE_CDP_OUTLET_REGISTRATION, getResources().getString(title_resource)); + + JSONArray fields = form.getJSONObject(STEP1).getJSONArray(FIELDS); + + // Populate the form fields with the outlet data + JSONObject uniqueIdObj = JsonFormUtils.getFieldJSONObject(fields, "unique_id"); + uniqueIdObj.put(VALUE, outletObject.getOutletId()); + + JSONObject outletNameObj = JsonFormUtils.getFieldJSONObject(fields, "outlet_name"); + outletNameObj.put(VALUE, outletObject.getOutletName()); + + JSONObject outletWardNameObj = JsonFormUtils.getFieldJSONObject(fields, "outlet_ward_name"); + outletWardNameObj.put(VALUE, outletObject.getOutletWardName()); + + JSONObject outletVillageStreetNameObj = JsonFormUtils.getFieldJSONObject(fields, "outlet_village_street_name"); + outletVillageStreetNameObj.put(VALUE, outletObject.getOutletWardName()); + + JSONObject focalPersonNameObj = JsonFormUtils.getFieldJSONObject(fields, "focal_person_name"); + focalPersonNameObj.put(VALUE, outletObject.getFocalPersonName()); + + JSONObject focalPersonPhoneObj = JsonFormUtils.getFieldJSONObject(fields, "focal_person_phone"); + focalPersonPhoneObj.put(VALUE, outletObject.getFocalPersonNumber()); + + JSONObject outletTypeObj = JsonFormUtils.getFieldJSONObject(fields, "outlet_type"); + outletTypeObj.put(VALUE, outletObject.getOutletType()); + + JSONObject otherOutletTypeObj = JsonFormUtils.getFieldJSONObject(fields, "other_outlet_type"); + otherOutletTypeObj.put(VALUE, outletObject.getOtherOutletType()); + + // Start the form activity + startActivityForResult(org.smartregister.chw.util.JsonFormUtils.getAncPncStartFormIntent(form, this), JsonFormUtils.REQUEST_CODE_GET_JSON); + + } + } catch (Exception e) { + Timber.e(e); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == Constants.REQUEST_CODE_GET_JSON && resultCode == RESULT_OK) { + String jsonString = data.getStringExtra(Constants.JSON_FORM_EXTRA.JSON); + try { + JSONObject jsonObject = new JSONObject(jsonString); + String encounter_type = jsonObject.getString("encounter_type"); + if (encounter_type.equalsIgnoreCase(Constants.EVENT_TYPE.UPDATE_CDP_OUTLET_REGISTRATION)) { + RegisterParams registerParam = new RegisterParams(); + registerParam.setEditMode(true); + registerParam.setFormTag(CdpJsonFormUtils.formTag(CdpLibrary.getInstance().context().allSharedPreferences())); + showProgressDialog(org.smartregister.cdp.R.string.saving_dialog_title); + profilePresenter.saveForm(jsonString, registerParam); + finish(); + } else if (encounter_type.equalsIgnoreCase(Constants.EVENT_TYPE.CDP_OUTLET_VISIT)) { + JSONObject restockTheOutlet = getFieldJSONObject(fields(jsonObject, org.smartregister.util.JsonFormUtils.STEP1), "restock_the_outlet"); + if (restockTheOutlet != null && restockTheOutlet.has(VALUE) && restockTheOutlet.getString(VALUE).equalsIgnoreCase("yes")) { + startRestockingHistory(); + } + + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpRegisterActivity.java new file mode 100644 index 0000000000..cfedbefce7 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpRegisterActivity.java @@ -0,0 +1,65 @@ +package org.smartregister.chw.activity; + +import androidx.annotation.MenuRes; +import androidx.fragment.app.Fragment; + +import com.google.android.material.bottomnavigation.LabelVisibilityMode; + +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.core.activity.CoreCdpRegisterActivity; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.chw.fragment.CdpReceiveFromOrganizationsRegisterFragment; +import org.smartregister.chw.fragment.CdpRegisterFragment; +import org.smartregister.chw.fragment.OrdersRegisterFragment; +import org.smartregister.chw.listener.CdpBottomNavigationListener; +import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.listener.BottomNavigationListener; +import org.smartregister.view.fragment.BaseRegisterFragment; + +public class CdpRegisterActivity extends CoreCdpRegisterActivity { + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new CdpRegisterFragment(); + } + + @Override + protected Fragment[] getOtherFragments() { + return new Fragment[]{ + new OrdersRegisterFragment(), + new CdpReceiveFromOrganizationsRegisterFragment() + }; + } + + @Override + public void startOutletForm() { + JSONObject form = FormUtils.getFormUtils().getFormJson(Constants.FORMS.CDP_OUTLET_REGISTRATION); + startFormActivity(form, Constants.FORMS.CDP_OUTLET_REGISTRATION); + } + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + + if (bottomNavigationView != null) { + bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); + bottomNavigationView.getMenu().removeItem(org.smartregister.cdp.R.id.action_register); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); + bottomNavigationView.inflateMenu(getMenuResource()); + bottomNavigationHelper.disableShiftMode(bottomNavigationView); + BottomNavigationListener familyBottomNavigationListener = new CdpBottomNavigationListener(this); + bottomNavigationView.setOnNavigationItemSelectedListener(familyBottomNavigationListener); + } + } + + @Override + @MenuRes + public int getMenuResource() { + return R.menu.cdp_bottom_nav_menu; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsActivity.java new file mode 100644 index 0000000000..03340fa034 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsActivity.java @@ -0,0 +1,142 @@ +package org.smartregister.chw.activity; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Toast; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.widget.Toolbar; +import androidx.constraintlayout.widget.ConstraintLayout; + +import com.google.android.material.appbar.AppBarLayout; +import com.whiteelephant.monthpicker.MonthPickerDialog; + +import org.smartregister.chw.R; +import org.smartregister.chw.util.Constants; +import org.smartregister.chw.util.ReportUtils; +import org.smartregister.view.activity.SecuredActivity; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import timber.log.Timber; + +public class CdpReportsActivity extends SecuredActivity implements View.OnClickListener { + protected ConstraintLayout cdpIssuingReport; + protected ConstraintLayout cdpReceivingReport; + protected AppBarLayout appBarLayout; + Menu menu; + private String reportPeriod = ReportUtils.getDefaultReportPeriod(); + + public void setupViews() { + cdpIssuingReport = findViewById(R.id.cdp_issuing_report); + cdpReceivingReport = findViewById(R.id.cdp_receiving_report); + + + cdpIssuingReport.setOnClickListener(this); + cdpReceivingReport.setOnClickListener(this); + } + + public void setUpToolbar() { + Toolbar toolbar = findViewById(org.smartregister.chw.core.R.id.back_to_nav_toolbar); + setSupportActionBar(toolbar); + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + final Drawable upArrow = getResources().getDrawable(org.smartregister.chw.core.R.drawable.ic_arrow_back_white_24dp); + actionBar.setHomeAsUpIndicator(upArrow); + actionBar.setElevation(0); + } + toolbar.setNavigationOnClickListener(v -> finish()); + appBarLayout = findViewById(org.smartregister.chw.core.R.id.app_bar); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + appBarLayout.setOutlineProvider(null); + } + } + + @Override + protected void onResumption() { + //overridden + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.reports_menu, menu); + this.menu = menu; + this.menu.findItem(R.id.action_select_month).setTitle(ReportUtils.displayMonthAndYear()); + return true; + } + + @Override + protected void onCreation() { + setContentView(R.layout.activity_cdp_reports); + setUpToolbar(); + setupViews(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_select_month) { + showMonthPicker(this, menu); + return true; + } + return super.onOptionsItemSelected(item); + } + + @SuppressLint("NonConstantResourceId") + @Override + public void onClick(View v) { + int id = v.getId(); + switch (id) { + case R.id.cdp_issuing_report: + CdpReportsViewActivity.startMe(this, Constants.ReportConstants.ReportPaths.CONDOM_DISTRIBUTION_ISSUING_REPORT_PATH, R.string.cdp_issuing_report, reportPeriod); + break; + case R.id.cdp_receiving_report: + CdpReportsViewActivity.startMe(this, Constants.ReportConstants.ReportPaths.CONDOM_DISTRIBUTION_RECEIVING_REPORT_PATH, R.string.cdp_receiving_report, reportPeriod); + break; + default: + Toast.makeText(this, "Action Not Defined", Toast.LENGTH_SHORT).show(); + break; + } + } + + private void showMonthPicker(Context context, Menu menu) { + //shows the month picker and returns selected period and updated the menu + MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(context, (selectedMonth, selectedYear) -> { + int month = selectedMonth + 1; + String monthString = String.valueOf(month); + if (month < 10) { + monthString = "0" + monthString; + } + String yearString = String.valueOf(selectedYear); + reportPeriod = monthString + "-" + yearString; + menu.findItem(R.id.action_select_month).setTitle(ReportUtils.displayMonthAndYear(selectedMonth, selectedYear)); + + }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH)); + try { + Date reportDate = new SimpleDateFormat("MM-yyyy", Locale.getDefault()).parse(reportPeriod); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(reportDate); + builder.setActivatedMonth(calendar.get(Calendar.MONTH)); + builder.setMinYear(2021); + builder.setActivatedYear(calendar.get(Calendar.YEAR)); + builder.setMaxYear(Calendar.getInstance().get(Calendar.YEAR)); + builder.setMinMonth(Calendar.JANUARY); + builder.setMaxMonth(Calendar.DECEMBER); + builder.setTitle("Select Month 0"); + builder.build().show(); + } catch (ParseException e) { + Timber.e(e); + } + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsViewActivity.java new file mode 100644 index 0000000000..29f7e4fccb --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/CdpReportsViewActivity.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.util.Constants; + + +public class CdpReportsViewActivity extends ChwReportsViewActivity{ + public static void startMe(Activity activity, String reportPath, int reportTitle, String reportDate) { + Intent intent = new Intent(activity, CdpReportsViewActivity.class); + intent.putExtra(ARG_REPORT_PATH, reportPath); + intent.putExtra(ARG_REPORT_TITLE, reportTitle); + intent.putExtra(ARG_REPORT_DATE, reportDate); + intent.putExtra(ARG_REPORT_TYPE, Constants.ReportConstants.ReportTypes.CONDOM_DISTRIBUTION_REPORT); + activity.startActivity(intent); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChildProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChildProfileActivity.java index 343a88bdb1..bb16d977af 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChildProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChildProfileActivity.java @@ -1,5 +1,12 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.anc.util.Constants.ANC_MEMBER_OBJECTS.MEMBER_PROFILE_OBJECT; +import static org.smartregister.chw.core.utils.Utils.updateToolbarTitle; +import static org.smartregister.chw.util.Constants.MALARIA_REFERRAL_FORM; +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.opd.utils.OpdConstants.DateFormat.YYYY_MM_DD; + import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -30,6 +37,7 @@ import org.smartregister.chw.model.ReferralTypeModel; import org.smartregister.chw.presenter.ChildProfilePresenter; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.util.UtilsFlv; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.family.util.Constants; @@ -37,13 +45,6 @@ import java.util.Date; import java.util.List; -import static org.smartregister.chw.anc.util.Constants.ANC_MEMBER_OBJECTS.MEMBER_PROFILE_OBJECT; -import static org.smartregister.chw.core.utils.Utils.updateToolbarTitle; -import static org.smartregister.chw.util.Constants.MALARIA_REFERRAL_FORM; -import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; -import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; -import static org.smartregister.opd.utils.OpdConstants.DateFormat.YYYY_MM_DD; - public class ChildProfileActivity extends CoreChildProfileActivity implements OnRetrieveNotifications { public FamilyMemberFloatingMenu familyFloatingMenu; private Flavor flavor = new ChildProfileActivityFlv(); @@ -144,6 +145,12 @@ public void updateHasPhone(boolean hasPhone) { } } + @Override + public void setProfileImage(String baseEntityId) { + int defaultImage = org.smartregister.chw.core.R.drawable.rowavatar_child;// gender.equalsIgnoreCase(Gender.MALE.toString()) ? R.drawable.row_boy : R.drawable.row_girl; + imageViewProfile.setImageResource(defaultImage); + } + @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -165,14 +172,15 @@ public boolean onOptionsItemSelected(MenuItem item) { @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); - menu.findItem(R.id.action_sick_child_form).setVisible(ChwApplication.getApplicationFlavor().hasChildSickForm() - && flavor.isChildOverTwoMonths(((CoreChildProfilePresenter) presenter).getChildClient()) - && !ChwApplication.getApplicationFlavor().useThinkMd()); + menu.findItem(R.id.action_sick_child_form).setVisible(false); + menu.findItem(R.id.action_sick_child_follow_up).setVisible(false); menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); menu.findItem(R.id.action_malaria_followup_visit).setVisible(false); menu.findItem(R.id.action_thinkmd_health_assessment).setVisible(ChwApplication.getApplicationFlavor().useThinkMd() && flavor.isChildOverTwoMonths(((CoreChildProfilePresenter) presenter).getChildClient())); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + UtilsFlv.updateMalariaMenuItems(memberObject.getBaseEntityId(), menu); return true; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwHIA2ReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwHIA2ReportsActivity.java new file mode 100644 index 0000000000..27dcf453d2 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwHIA2ReportsActivity.java @@ -0,0 +1,56 @@ +package org.smartregister.chw.activity; + +import android.os.Bundle; + +import androidx.appcompat.widget.Toolbar; +import androidx.fragment.app.Fragment; + +import org.smartregister.chw.adapter.ChwSectionsPagerAdapter; +import org.smartregister.chw.core.activity.HIA2ReportsActivity; +import org.smartregister.chw.core.fragment.DraftMonthlyFragment; +import org.smartregister.chw.task.ChwStartDraftMonthlyFormTask; +import org.smartregister.util.Utils; + +import java.util.Date; + +import timber.log.Timber; + +public class ChwHIA2ReportsActivity extends HIA2ReportsActivity { + + private ChwSectionsPagerAdapter mSectionsPagerAdapter; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(org.smartregister.chw.core.R.layout.app_hia2_reports); + Toolbar toolbar = findViewById(getToolbarId()); + setSupportActionBar(toolbar); + + tabLayout = findViewById(org.smartregister.chw.core.R.id.hia_tabs); + mSectionsPagerAdapter = new ChwSectionsPagerAdapter(getSupportFragmentManager(), this); + + // Set up the ViewPager with the sections adapter. + mViewPager = findViewById(org.smartregister.chw.core.R.id.container); + mViewPager.setAdapter(mSectionsPagerAdapter); + + tabLayout.setupWithViewPager(mViewPager); + refreshDraftMonthlyTitle(); + // mSectionsPagerAdapter.getItem(1); + mViewPager.setCurrentItem(1); + findViewById(org.smartregister.chw.core.R.id.toggle_action_menu).setOnClickListener(v -> onClickReport(v)); + } + + @Override + public void startMonthlyReportForm(String formName, Date date) { + try { + Fragment currentFragment = currentFragment(); + if (currentFragment instanceof DraftMonthlyFragment) { + Utils.startAsyncTask(new ChwStartDraftMonthlyFormTask(this, date, formName), null); + } + } catch (Exception e) { + Timber.e(e); + } + + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReferralDetailsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReferralDetailsViewActivity.java new file mode 100644 index 0000000000..46ca752696 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReferralDetailsViewActivity.java @@ -0,0 +1,197 @@ +package org.smartregister.chw.activity; + +import static org.hl7.fhir.r4.model.codesystems.VariantState.NEGATIVE; +import static org.hl7.fhir.r4.model.codesystems.VariantState.POSITIVE; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Intent; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.CoreReferralUtils; +import org.smartregister.chw.dao.ChwHivOutcomeDao; +import org.smartregister.chw.dao.ReferralDao; +import org.smartregister.chw.referral.activity.ReferralDetailsViewActivity; +import org.smartregister.chw.referral.domain.MemberObject; +import org.smartregister.chw.referral.util.Constants; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.domain.Location; +import org.smartregister.domain.Task; +import org.smartregister.repository.LocationRepository; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import timber.log.Timber; + +public class ChwReferralDetailsViewActivity extends ReferralDetailsViewActivity { + TextView tvActionTaken; + TextView tvComments; + TextView tvTestResult; + TextView tvEnrolledClinic; + TextView tvClinicNumber; + LinearLayout commentSection; + LinearLayout actionTakenGroup; + LinearLayout enrolledClinicGroup; + LinearLayout feedBackViewGroup; + + public static void startChwReferralDetailsViewActivity(Activity activity, MemberObject memberObject, CommonPersonObjectClient client) { + Intent intent = new Intent(activity, ChwReferralDetailsViewActivity.class); + intent.putExtra(Constants.ReferralMemberObject.MEMBER_OBJECT, memberObject); + activity.startActivity(intent); + } + + @Override + protected void onCreation() { + super.onCreation(); + tvActionTaken = findViewById(R.id.referral_action_taken_value); + tvTestResult = findViewById(R.id.referral_feedback_test_result); + tvEnrolledClinic = findViewById(R.id.referral_feedback_enrolled_clinic_value); + tvClinicNumber = findViewById(R.id.referral_feedback_clinic_number); + tvComments = findViewById(R.id.referral_feedback_comments); + commentSection = findViewById(R.id.referral_feedback_comments_section); + actionTakenGroup = findViewById(R.id.referral_feedback_action_taken_group); + enrolledClinicGroup = findViewById(R.id.referral_feedback_clinic_enrolled); + feedBackViewGroup = findViewById(R.id.referral_details_feedback); + + setupViews(); + } + + private void createCancelReferral(Task task) { + LinearLayout referralVisitBar = findViewById(R.id.record_visit_bar); + referralVisitBar.setVisibility(View.VISIBLE); + + CustomFontTextView markAsDone = findViewById(R.id.mark_ask_done); + markAsDone.setText(R.string.cancel_referral); + + View viewReferralRow = findViewById(R.id.view_referal_row); + viewReferralRow.setVisibility(View.GONE); + + markAsDone.setOnClickListener(view -> { + closeReferralDialog(task); + }); + + } + + private void cancelReferral(Task task) { + MemberObject memberObject = getMemberObject(); + assert memberObject != null; + task.setForEntity(memberObject.getBaseEntityId()); + + CoreReferralUtils.cancelTask(task); + } + + private void closeReferralDialog(Task task) { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(getString(R.string.cancel_referral_title)); + builder.setMessage(getString(R.string.cancel_referral_message)); + builder.setCancelable(true); + + builder.setPositiveButton(this.getString(R.string.cancel_referral), (dialog, id) -> { + try { + cancelReferral(task); + finish(); + } catch (Exception e) { + Timber.e(e, "ReferralTaskViewActivity --> closeReferralDialog"); + } + }); + builder.setNegativeButton(this.getString(R.string.exit), ((dialog, id) -> dialog.cancel())); + + AlertDialog alertDialog = builder.create(); + alertDialog.show(); + } + + private void setupViews() { + LocationRepository locationRepository = new LocationRepository(); + Location location = locationRepository.getLocationById(getMemberObject().getChwReferralHf()); + ((CustomFontTextView) findViewById(R.id.referral_facility)).setText(location.getProperties().getName()); + + if (getMemberObject().getServicesBeforeReferral() != null && getMemberObject().getServicesBeforeReferral().equalsIgnoreCase("None")) + ((CustomFontTextView) findViewById(R.id.pre_referral_management)).setText(getResources().getString(R.string.none)); + + String taskId = ReferralDao.getTaskIdByReasonReference(getMemberObject().getBaseEntityId()); + Task task = ChwApplication.getInstance().getTaskRepository().getTaskByIdentifier(taskId); + if (!task.getBusinessStatus().equalsIgnoreCase("Complete")) { + createCancelReferral(task); + } else { + showFeedBackView(task); + } + } + + private void showFeedBackView(Task task) { + + + if (getMemberObject().getChwReferralService().equals(CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST)) { + String servicesProvided = ChwHivOutcomeDao.servicesProvided(task.getForEntity(), task.getLastModified().getMillis()); + String hivStatus = ChwHivOutcomeDao.hivStatus(task.getForEntity(), task.getLastModified().getMillis()); + String enrolledToCTC = ChwHivOutcomeDao.hivEnrolledToCTC(task.getForEntity(), task.getLastModified().getMillis()); + String ctcNumber = ChwHivOutcomeDao.ctcNumber(task.getForEntity(), task.getLastModified().getMillis()); + String reasonsForNotEnrolling = ChwHivOutcomeDao.reasonsForNotEnrolling(task.getForEntity(), task.getLastModified().getMillis()); + String commentsFromHF = ChwHivOutcomeDao.hivCommentsFromHF(task.getForEntity(), task.getLastModified().getMillis()); + + if (checkHasFeedBack(servicesProvided, enrolledToCTC, commentsFromHF)) { + feedBackViewGroup.setVisibility(View.VISIBLE); + if (servicesProvided != null) { + actionTakenGroup.setVisibility(View.VISIBLE); + tvActionTaken.setText(getTranslatedHivServicesProvided(servicesProvided)); + } + if (hivStatus != null) { + if (hivStatus.equalsIgnoreCase(POSITIVE.toString())) + tvTestResult.setText(getResources().getText(R.string.cbhs_positive)); + else if (hivStatus.equalsIgnoreCase(NEGATIVE.toString())) + tvTestResult.setText(getResources().getText(R.string.cbhs_negative)); + else + tvTestResult.setText(hivStatus); + } else { + tvTestResult.setVisibility(View.GONE); + } + if (enrolledToCTC != null) { + enrolledClinicGroup.setVisibility(View.VISIBLE); + tvEnrolledClinic.setText(getTranslatedEnrolment(enrolledToCTC)); + if (enrolledToCTC.equalsIgnoreCase("Yes")) { + tvClinicNumber.setText(ctcNumber); + } else { + tvClinicNumber.setText(reasonsForNotEnrolling); + } + } + if (commentsFromHF != null) + commentSection.setVisibility(View.VISIBLE); + tvComments.setText(commentsFromHF); + } else { + feedBackViewGroup.setVisibility(View.GONE); + } + + } + } + + private boolean checkHasFeedBack(String servicesProvided, String enrolledToCTC, String commentsFromHF) { + return servicesProvided != null || enrolledToCTC != null && commentsFromHF != null; + } + + private String getTranslatedHivServicesProvided(String serviceProvided) { + switch (serviceProvided) { + case "no_action_taken": + return getString(R.string.no_action_taken); + case "tested": + return getString(R.string.tests_done); + case "referred": + return getString(R.string.referred); + default: + return serviceProvided; + } + } + + private String getTranslatedEnrolment(String enrolledToCTC) { + switch (enrolledToCTC) { + case "yes": + return getString(R.string.yes); + case "no": + return getString(R.string.no); + default: + return enrolledToCTC; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReportsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReportsViewActivity.java new file mode 100644 index 0000000000..a7dfd5a5e3 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ChwReportsViewActivity.java @@ -0,0 +1,94 @@ +package org.smartregister.chw.activity; + +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.os.Bundle; +import android.view.Menu; +import android.view.MenuItem; +import android.webkit.WebView; +import android.widget.Toast; + +import com.google.android.material.appbar.AppBarLayout; + +import org.apache.commons.lang3.StringUtils; +import org.smartregister.chw.R; +import org.smartregister.chw.util.ReportUtils; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; + +public class ChwReportsViewActivity extends AppCompatActivity { + protected static final String ARG_REPORT_PATH = "ARG_REPORT_PATH"; + protected static final String ARG_REPORT_TITLE = "ARG_REPORT_TITLE"; + protected static final String ARG_REPORT_DATE = "ARG_REPORT_DATE"; + protected static final String ARG_REPORT_TYPE = "ARG_REPORT_TYPE"; + public static WebView printWebView; + protected CustomFontTextView toolBarTextView; + protected AppBarLayout appBarLayout; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_reports_view); + String reportPath = getIntent().getStringExtra(ARG_REPORT_PATH); + String reportDate = getIntent().getStringExtra(ARG_REPORT_DATE); + String reportType = getIntent().getStringExtra(ARG_REPORT_TYPE); + int reportTitle = getIntent().getIntExtra(ARG_REPORT_TITLE, 0); + setUpToolbar(reportTitle); + WebView webView = findViewById(R.id.webview); + ReportUtils.setReportPeriod(reportDate); + ReportUtils.loadReportView(reportPath, webView, this, reportType); + } + + public void setUpToolbar(int reportTitle) { + Toolbar toolbar = findViewById(org.smartregister.chw.core.R.id.back_to_nav_toolbar); + toolBarTextView = toolbar.findViewById(org.smartregister.chw.core.R.id.toolbar_title); + setSupportActionBar(toolbar); + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + final Drawable upArrow = getResources().getDrawable(org.smartregister.chw.core.R.drawable.ic_arrow_back_white_24dp); + actionBar.setHomeAsUpIndicator(upArrow); + actionBar.setElevation(0); + } + toolbar.setNavigationOnClickListener(v -> finish()); + if (StringUtils.isNotBlank(getString(reportTitle))) { + toolBarTextView.setText(getString(reportTitle)); + } else { + toolBarTextView.setText(R.string.reports_title); + } + toolBarTextView.setOnClickListener(v -> finish()); + appBarLayout = findViewById(org.smartregister.chw.core.R.id.app_bar); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + appBarLayout.setOutlineProvider(null); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.reports_view_menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == R.id.action_print) { + if (printWebView != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + ReportUtils.printTheWebPage(printWebView, this); + } else { + Toast.makeText(this, "Not available for device below Android LOLLIPOP", Toast.LENGTH_SHORT).show(); + } + } else { + Toast.makeText(this, "WebPage not fully loaded", Toast.LENGTH_SHORT).show(); + } + return true; + } + return super.onOptionsItemSelected(item); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ClientReferralActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ClientReferralActivity.java index 3bf4fb564f..44e6329e64 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ClientReferralActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ClientReferralActivity.java @@ -2,15 +2,9 @@ import android.app.Activity; import android.content.Intent; -import android.os.Bundle; import android.view.View; import android.widget.ImageView; -import androidx.annotation.Nullable; -import androidx.appcompat.app.AppCompatActivity; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; - import org.json.JSONObject; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.R; @@ -24,16 +18,20 @@ import org.smartregister.family.util.JsonFormUtils; import org.smartregister.family.util.Utils; import org.smartregister.util.FormUtils; +import org.smartregister.view.activity.SecuredActivity; import java.util.HashMap; import java.util.List; import java.util.Map; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import timber.log.Timber; import static org.smartregister.chw.util.Constants.REFERRAL_TASK_FOCUS; -public class ClientReferralActivity extends AppCompatActivity implements ClientReferralContract.View, View.OnClickListener { +public class ClientReferralActivity extends SecuredActivity implements ClientReferralContract.View, View.OnClickListener { private ReferralTypeAdapter referralTypeAdapter; private FormUtils formUtils; @@ -41,8 +39,7 @@ public class ClientReferralActivity extends AppCompatActivity implements ClientR private Map encounterTypeToTableMap; @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + protected void onCreation() { setContentView(R.layout.activity_client_referral); referralTypeAdapter = new ReferralTypeAdapter(); encounterTypeToTableMap = new HashMap<>(); @@ -82,7 +79,7 @@ public void startReferralForm(JSONObject jsonObject, ReferralTypeModel referralT if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { //TODO Define custom layout on referral library for family planning referrals otherwise do not use custom layout for now ReferralRegistrationActivity.startGeneralReferralFormActivityForResults(this, - baseEntityId, jsonObject, !CoreConstants.TASKS_FOCUS.FP_SIDE_EFFECTS.equalsIgnoreCase(referralTypeModel.getFocus())); + baseEntityId, jsonObject, false); } else { startActivityForResult(CoreJsonFormUtils.getJsonIntent(this, jsonObject, Utils.metadata().familyMemberFormActivity), JsonFormUtils.REQUEST_CODE_GET_JSON); @@ -133,8 +130,7 @@ public void onClick(View v) { } @Override - protected void onResume() { - super.onResume(); + protected void onResumption() { referralTypeAdapter.canStart = true; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultFamilyOtherMemberProfileActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultFamilyOtherMemberProfileActivityFlv.java index fc6210ae45..f2f74b365b 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultFamilyOtherMemberProfileActivityFlv.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultFamilyOtherMemberProfileActivityFlv.java @@ -3,6 +3,8 @@ import android.app.Activity; import android.view.Menu; +import androidx.annotation.Nullable; + import org.smartregister.chw.R; import org.smartregister.chw.core.fragment.FamilyCallDialogFragment; import org.smartregister.chw.core.listener.OnClickFloatingMenu; @@ -49,6 +51,16 @@ public void updateMalariaMenuItems(String baseEntityId, Menu menu) { // TODO implement if wcaro would need malaria module } + @Override + public void updateHivMenuItems(@Nullable String baseEntityId, @Nullable Menu menu) { +// TODO implement if wcaro would need hiv module + } + + @Override + public void updateTbMenuItems(@Nullable String baseEntityId, @Nullable Menu menu) { +// TODO implement if wcaro would need tb module + } + @Override public boolean hasANC() { return true; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultHivProfileActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultHivProfileActivityFlv.java new file mode 100644 index 0000000000..9556a930c9 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultHivProfileActivityFlv.java @@ -0,0 +1,13 @@ +package org.smartregister.chw.activity; + +import android.view.Menu; + +import org.smartregister.chw.R; + +public abstract class DefaultHivProfileActivityFlv implements HivProfileActivity.Flavor { + +// @Override +// public void updateTbMenuItems(String baseEntityId, Menu menu) { +// menu.findItem(R.id.action_tb_registration).setVisible(false); +// } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultTbProfileActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultTbProfileActivityFlv.java new file mode 100644 index 0000000000..7067ac70da --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/DefaultTbProfileActivityFlv.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.activity; + +import android.view.Menu; + +import org.smartregister.chw.R; + +public abstract class DefaultTbProfileActivityFlv implements TbProfileActivity.Flavor { + @Override + public void updateHivMenuItems(String baseEntityId, Menu menu) { + menu.findItem(R.id.action_cbhs_registration).setVisible(false); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyOtherMemberProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyOtherMemberProfileActivity.java index 2252fe1e2c..5c603d28fe 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyOtherMemberProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyOtherMemberProfileActivity.java @@ -1,5 +1,9 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.core.utils.Utils.updateToolbarTitle; +import static org.smartregister.chw.util.Utils.getClientGender; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + import android.app.Activity; import android.content.Context; import android.view.Menu; @@ -7,8 +11,14 @@ import androidx.annotation.Nullable; import androidx.viewpager.widget.ViewPager; +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.smartregister.chw.R; +import org.smartregister.chw.agyw.dao.AGYWDao; +import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.core.activity.CoreFamilyOtherMemberProfileActivity; import org.smartregister.chw.core.activity.CoreFamilyProfileActivity; import org.smartregister.chw.core.form_data.NativeFormsDataBinder; @@ -18,7 +28,10 @@ import org.smartregister.chw.dataloader.FamilyMemberDataLoader; import org.smartregister.chw.fp.util.FamilyPlanningConstants; import org.smartregister.chw.fragment.FamilyOtherMemberProfileFragment; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.kvp.dao.KvpDao; import org.smartregister.chw.presenter.FamilyOtherMemberActivityPresenter; +import org.smartregister.chw.util.Constants; import org.smartregister.chw.util.Utils; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.family.adapter.ViewPagerAdapter; @@ -29,8 +42,6 @@ import timber.log.Timber; -import static org.smartregister.chw.core.utils.Utils.updateToolbarTitle; - public class FamilyOtherMemberProfileActivity extends CoreFamilyOtherMemberProfileActivity { private FamilyMemberFloatingMenu familyFloatingMenu; private Flavor flavor = new FamilyOtherMemberProfileActivityFlv(); @@ -47,22 +58,63 @@ public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); String gender = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.GENDER, false); // Check if woman is already registered - if (flavor.hasANC() && !presenter().isWomanAlreadyRegisteredOnAnc(commonPersonObject) && flavor.isOfReproductiveAge(commonPersonObject, "Female") && gender.equalsIgnoreCase("Female") ) { + if (flavor.hasANC() && !presenter().isWomanAlreadyRegisteredOnAnc(commonPersonObject) && flavor.isOfReproductiveAge(commonPersonObject, "Female") && gender.equalsIgnoreCase("Female")) { flavor.updateFpMenuItems(baseEntityId, menu); menu.findItem(R.id.action_anc_registration).setVisible(true); } else { menu.findItem(R.id.action_anc_registration).setVisible(false); } + if (flavor.hasANC() && flavor.isOfReproductiveAge(commonPersonObject, "Female") && gender.equalsIgnoreCase("Female")) { + flavor.updateFpMenuItems(baseEntityId, menu); + menu.findItem(R.id.action_pregnancy_out_come).setVisible(true); + } else { + menu.findItem(R.id.action_pregnancy_out_come).setVisible(false); + } menu.findItem(R.id.action_sick_child_follow_up).setVisible(false); menu.findItem(R.id.action_malaria_diagnosis).setVisible(false); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + flavor.updateMalariaMenuItems(baseEntityId, menu); + + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(baseEntityId) && age >= 15); + } + + if(ChwApplication.getApplicationFlavor().hasKvp()){ + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(baseEntityId) && age >= 15); + } + + if (ChwApplication.getApplicationFlavor().hasAGYW()) { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + if (gender.equalsIgnoreCase("Female") && age >= 10 && age <= 24 && !AGYWDao.isRegisteredForAgyw(baseEntityId)) { + menu.findItem(R.id.action_agyw_screening).setVisible(true); + } + } flavor.updateMalariaMenuItems(baseEntityId, menu); if (gender.equalsIgnoreCase("Male") && flavor.isOfReproductiveAge(commonPersonObject, "Male")) { flavor.updateMaleFpMenuItems(baseEntityId, menu); } + if (!ChwApplication.getApplicationFlavor().hasHIV()) { + menu.findItem(R.id.action_cbhs_registration).setVisible(false); + } else { + flavor.updateHivMenuItems(baseEntityId, menu); + } + + if (!ChwApplication.getApplicationFlavor().hasTB()) { + menu.findItem(R.id.action_tb_registration).setVisible(false); + } else { + //flavor.updateTbMenuItems(baseEntityId, menu); + //will update when the TB module is complete + } + menu.findItem(R.id.action_fp_initiation).setVisible(false); return true; } @@ -74,7 +126,13 @@ public FamilyOtherMemberActivityPresenter presenter() { @Override protected void startAncRegister() { AncRegisterActivity.startAncRegistrationActivity(FamilyOtherMemberProfileActivity.this, baseEntityId, PhoneNumber, - org.smartregister.chw.util.Constants.JSON_FORM.getAncRegistration(), null, familyBaseEntityId, familyName); + Constants.JSON_FORM.getAncRegistration(), null, familyBaseEntityId, familyName); + } + + @Override + protected void startPncRegister() { + PncRegisterActivity.startPncRegistrationActivity(FamilyOtherMemberProfileActivity.this, baseEntityId, PhoneNumber, + CoreConstants.JSON_FORM.getPregnancyOutcome(), null, familyBaseEntityId, familyName, null); } @Override @@ -104,6 +162,38 @@ protected void removeIndividualProfile() { commonPersonObject, familyBaseEntityId, familyHead, primaryCaregiver, FamilyRegisterActivity.class.getCanonicalName()); } + @Override + protected void startHivRegister() { + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.GENDER, false); + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + + try { + String formName = Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(FamilyOtherMemberProfileActivity.this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + updateAgeAndGender(fields, age, gender); + + HivRegisterActivity.startHIVFormActivity(FamilyOtherMemberProfileActivity.this, baseEntityId, formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + protected void startTbRegister() { + try { + TbRegisterActivity.startTbFormActivity(FamilyOtherMemberProfileActivity.this, baseEntityId, Constants.JSON_FORM.getTbRegistration(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, Constants.JSON_FORM.getTbRegistration()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + @Override protected void startEditMemberJsonForm(Integer title_resource, CommonPersonObjectClient client) { String titleString = title_resource != null ? getResources().getString(title_resource) : null; @@ -154,7 +244,7 @@ protected Class getFamilyProfileActivity() @Override protected void initializePresenter() { super.initializePresenter(); - onClickFloatingMenu = flavor.getOnClickFloatingMenu(this, familyBaseEntityId,baseEntityId); + onClickFloatingMenu = flavor.getOnClickFloatingMenu(this, familyBaseEntityId, baseEntityId); } @Override @@ -173,11 +263,67 @@ protected BaseFamilyOtherMemberProfileFragment getFamilyOtherMemberProfileFragme return FamilyOtherMemberProfileFragment.newInstance(getIntent().getExtras()); } + @Override + protected void startMalariaFollowUpVisit() { + MalariaFollowUpVisitActivity.startMalariaFollowUpActivity(this, baseEntityId); + } + + @Override + protected void setIndependentClient(boolean isIndependentClient) { + super.isIndependent = isIndependentClient; + } + + @Override + protected void startHfMalariaFollowupForm() { + //Implements from super + } + + @Override + protected void startPmtctRegisration() { + //do nothing - implementation in hf + } + + @Override + protected void startLDRegistration() { + //do nothing - implementation in hf + } + + @Override + protected void startHivstRegistration() { + String gender = org.smartregister.family.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + HivstRegisterActivity.startHivstRegistrationActivity(FamilyOtherMemberProfileActivity.this, baseEntityId, gender); + } + + @Override + protected void startAgywScreening() { + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + AgywRegisterActivity.startRegistration(FamilyOtherMemberProfileActivity.this, baseEntityId, age); + } + + @Override + protected void startKvpPrEPRegistration() { + String gender = getClientGender(baseEntityId); + String dob = Utils.getValue(commonPersonObject.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + KvpPrEPRegisterActivity.startRegistration(FamilyOtherMemberProfileActivity.this, baseEntityId, gender, age); + } + + @Override + protected void startKvpRegistration() { + //do nothing + } + + @Override + protected void startPrEPRegistration() { + //do nothing + } + /** * build implementation differences file */ public interface Flavor { - OnClickFloatingMenu getOnClickFloatingMenu(final Activity activity, final String familyBaseEntityId , final String baseEntityId); + OnClickFloatingMenu getOnClickFloatingMenu(final Activity activity, final String familyBaseEntityId, final String baseEntityId); boolean isOfReproductiveAge(CommonPersonObjectClient commonPersonObject, String gender); @@ -187,21 +333,10 @@ public interface Flavor { void updateMaleFpMenuItems(@Nullable String baseEntityId, @Nullable Menu menu); - boolean hasANC(); - } - - @Override - protected void startMalariaFollowUpVisit() { - MalariaFollowUpVisitActivity.startMalariaFollowUpActivity(this, baseEntityId); - } + void updateHivMenuItems(@Nullable String baseEntityId, @Nullable Menu menu); - @Override - protected void startHfMalariaFollowupForm() { - //Implements from super - } + void updateTbMenuItems(@Nullable String baseEntityId, @Nullable Menu menu); - @Override - protected void setIndependentClient(boolean isIndependentClient) { - super.isIndependent = isIndependentClient; + boolean hasANC(); } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyPlanningMemberProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyPlanningMemberProfileActivity.java index 0bb2fa5b44..c020f00362 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyPlanningMemberProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyPlanningMemberProfileActivity.java @@ -247,7 +247,7 @@ private void addFpReferralTypes() { JSON_FORM.getMalariaReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_MALARIA)); referralTypeModels.add(new ReferralTypeModel(getString(R.string.hiv_referral), - JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_HIV)); + JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST)); referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyProfileActivity.java index 33071f9369..b75899318d 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FamilyProfileActivity.java @@ -27,9 +27,11 @@ import org.smartregister.chw.fragment.FamilyProfileActivityFragment; import org.smartregister.chw.fragment.FamilyProfileDueFragment; import org.smartregister.chw.fragment.FamilyProfileMemberFragment; +import org.smartregister.chw.hiv.dao.HivDao; import org.smartregister.chw.model.FamilyProfileModel; import org.smartregister.chw.pnc.activity.BasePncMemberProfileActivity; import org.smartregister.chw.presenter.FamilyProfilePresenter; +import org.smartregister.chw.tb.dao.TbDao; import org.smartregister.commonregistry.CommonPersonObject; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.family.adapter.ViewPagerAdapter; @@ -40,6 +42,7 @@ import org.smartregister.view.fragment.BaseRegisterFragment; import java.util.HashMap; +import java.util.Objects; import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; @@ -160,6 +163,11 @@ protected Class getAncMemberProfileActiv return AncMemberProfileActivity.class; } + @Override + public void goToAncProfileActivity(CommonPersonObjectClient patient, Bundle bundle) { + AncMemberProfileActivity.startMe(this,patient.getCaseId()); + } + @Override protected Class getPncMemberProfileActivityClass() { return PncMemberProfileActivity.class; @@ -170,6 +178,16 @@ protected void goToFpProfile(String baseEntityId, Activity activity) { FamilyPlanningMemberProfileActivity.startFpMemberProfileActivity(activity, FpDao.getMember(baseEntityId)); } + @Override + protected void goToHivProfile(String baseEntityId, Activity activity) { + HivProfileActivity.startHivProfileActivity(this, Objects.requireNonNull(HivDao.getMember(baseEntityId))); + } + + @Override + protected void goToTbProfile(String baseEntityId, Activity activity) { + TbProfileActivity.startTbProfileActivity(this, Objects.requireNonNull(TbDao.getMember(baseEntityId))); + } + @Override protected boolean isAncMember(String baseEntityId) { diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FpFollowUpVisitActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FpFollowUpVisitActivity.java index bdc43e2073..ac9f7536a3 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/FpFollowUpVisitActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/FpFollowUpVisitActivity.java @@ -1,7 +1,6 @@ package org.smartregister.chw.activity; import android.app.Activity; -import android.content.Context; import android.content.Intent; import com.vijay.jsonwizard.constants.JsonFormConstants; @@ -20,7 +19,6 @@ import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; import org.smartregister.family.util.Constants; import org.smartregister.family.util.JsonFormUtils; -import org.smartregister.util.LangUtils; import java.util.Date; @@ -80,11 +78,4 @@ public void startFormActivity(JSONObject jsonForm) { startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); } - @Override - protected void attachBaseContext(Context base) { - // get language from prefs - String lang = LangUtils.getLanguage(base.getApplicationContext()); - super.attachBaseContext(LangUtils.setAppLocale(base, lang)); - } } - diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactProfileActivity.java new file mode 100644 index 0000000000..2d27ea9aab --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactProfileActivity.java @@ -0,0 +1,316 @@ +package org.smartregister.chw.activity; + +import static org.smartregister.chw.hiv.util.Constants.ActivityPayload.HIV_MEMBER_OBJECT; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.util.Pair; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreHivIndexContactProfileActivity; +import org.smartregister.chw.core.adapter.NotificationListAdapter; +import org.smartregister.chw.core.contract.FamilyProfileExtendedContract; +import org.smartregister.chw.core.interactor.CoreHivIndexContactProfileInteractor; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.listener.OnRetrieveNotifications; +import org.smartregister.chw.core.model.CoreAllClientsMemberModel; +import org.smartregister.chw.core.utils.ChwNotificationUtil; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.UpdateDetailsUtil; +import org.smartregister.chw.custom_view.HivIndexContactFloatingMenu; +import org.smartregister.chw.hiv.activity.BaseHivFormsActivity; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.dao.HivIndexDao; +import org.smartregister.chw.hiv.domain.HivIndexContactObject; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.kvp.dao.KvpDao; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.presenter.HivIndexContactProfilePresenter; +import org.smartregister.chw.tb.util.Constants; +import org.smartregister.chw.util.Utils; +import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.family.contract.FamilyProfileContract; +import org.smartregister.family.domain.FamilyEventClient; +import org.smartregister.family.interactor.FamilyProfileInteractor; +import org.smartregister.family.util.DBConstants; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.opd.utils.OpdConstants; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import timber.log.Timber; + +public class HivIndexContactProfileActivity extends CoreHivIndexContactProfileActivity implements FamilyProfileExtendedContract.PresenterCallBack, OnRetrieveNotifications { + + public final static String REGISTERED_TO_HIV_REGISTRY = "registered_to_hiv_registry"; + private CommonPersonObjectClient commonPersonObjectClient; + private List referralTypeModels = new ArrayList<>(); + private NotificationListAdapter notificationListAdapter = new NotificationListAdapter(); + + public static void startHivIndexContactProfileActivity(Activity activity, HivIndexContactObject hivIndexContactObject) { + Intent intent = new Intent(activity, HivIndexContactProfileActivity.class); + intent.putExtra(HIV_MEMBER_OBJECT, hivIndexContactObject); + activity.startActivity(intent); + } + + public static void startHivIndexContactFollowupActivity(Activity activity, String baseEntityID) throws JSONException { + + Intent intent = new Intent(activity, BaseHivFormsActivity.class); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + + HivIndexContactObject hivIndexContactObject = HivIndexDao.getMember(baseEntityID); + + JSONObject form = (new FormUtils()).getFormJsonFromRepositoryOrAssets(activity, CoreConstants.JSON_FORM.getHivIndexContactFollowupVisit()); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.JSON_FORM, form.toString()); + + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.ACTION, Constants.ActivityPayloadType.FOLLOW_UP_VISIT); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.USE_DEFAULT_NEAT_FORM_LAYOUT, false); + + activity.startActivityForResult(intent, org.smartregister.chw.anc.util.Constants.REQUEST_CODE_HOME_VISIT); + } + + @Override + public void setupViews() { + super.setupViews(); + if (getHivIndexContactObject().getFollowedUpByChw()) { + + } + } + + + @Override + protected void onCreation() { + super.onCreation(); + setCommonPersonObjectClient(getClientDetailsByBaseEntityID(getHivIndexContactObject().getBaseEntityId())); + addHivReferralTypes(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + notificationAndReferralRecyclerView.setAdapter(notificationListAdapter); + notificationListAdapter.setOnClickListener(this); + } + + @Override + protected void onResume() { + super.onResume(); + notificationListAdapter.canOpen = true; + ChwNotificationUtil.retrieveNotifications(ChwApplication.getApplicationFlavor().hasReferrals(), + getHivIndexContactObject().getBaseEntityId(), this); + } + + public CommonPersonObjectClient getCommonPersonObjectClient() { + return commonPersonObjectClient; + } + + public void setCommonPersonObjectClient(CommonPersonObjectClient commonPersonObjectClient) { + this.commonPersonObjectClient = commonPersonObjectClient; + } + + @Override + protected void initializePresenter() { + showProgressBar(true); + setHivContactProfilePresenter(new HivIndexContactProfilePresenter(this, new CoreHivIndexContactProfileInteractor(), getHivIndexContactObject())); + fetchProfileData(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + try { + if (itemId == R.id.action_issue_hiv_community_followup_referral) { + HivRegisterActivity.startHIVFormActivity(this, getHivIndexContactObject().getBaseEntityId(), CoreConstants.JSON_FORM.getHivIndexContactCommunityFollowupReferral(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, CoreConstants.JSON_FORM.getHivIndexContactCommunityFollowupReferral()).toString()); + return true; + } else if (itemId == R.id.action_kvp_prep_registration) { + String gender = Utils.getClientGender(getHivIndexContactObject().getBaseEntityId()); + String dob = getHivIndexContactObject().getDob(); + int age = Utils.getAgeFromDate(dob); + KvpPrEPRegisterActivity.startRegistration(HivIndexContactProfileActivity.this, getHivIndexContactObject().getBaseEntityId(), gender, age); + return true; + } else if (itemId == R.id.action_hivst_registration) { + startHivstRegistration(); + return true; + } + } catch (JSONException e) { + Timber.e(e); + } + return super.onOptionsItemSelected(item); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(org.smartregister.chw.core.R.menu.hiv_profile_menu, menu); + menu.findItem(R.id.action_location_info).setVisible(UpdateDetailsUtil.isIndependentClient(getHivIndexContactObject().getBaseEntityId())); + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + String dob = Utils.getValue(commonPersonObjectClient.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(getHivIndexContactObject().getBaseEntityId()) && age >= 15); + } + if (ChwApplication.getApplicationFlavor().hasKvp()) { + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(getHivIndexContactObject().getBaseEntityId())); + } + return true; + } + + @Override + public void openFollowUpVisitForm(boolean isEdit) { + if (!isEdit) { + try { + startHivIndexContactFollowupActivity(this, getHivIndexContactObject().getBaseEntityId()); + } catch (JSONException e) { + Timber.e(e); + } + } + } + + @Override + protected void removeMember() { + // Not required for HF (as seen in other profile activities)? + } + + @Override + public void onClick(View view) { + super.onClick(view); + int id = view.getId(); + if (id == R.id.record_hiv_followup_visit) { + openFollowUpVisitForm(false); + } + } + + private void addHivReferralTypes() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.hts_referral), + CoreConstants.JSON_FORM.getHtsReferralForm(), CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST)); + + referralTypeModels.add(new ReferralTypeModel(getString(R.string.gbv_referral), + CoreConstants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); + } + + } + + public List getReferralTypeModels() { + return referralTypeModels; + } + + @Override + public void initializeCallFAB() { + setHivFloatingMenu(new HivIndexContactFloatingMenu(this, getHivIndexContactObject())); + + OnClickFloatingMenu onClickFloatingMenu = viewId -> { + switch (viewId) { + case R.id.hiv_fab: + checkPhoneNumberProvided(); + ((HivIndexContactFloatingMenu) getHivFloatingMenu()).animateFAB(); + break; + case R.id.call_layout: + ((HivIndexContactFloatingMenu) getHivFloatingMenu()).launchCallWidget(); + ((HivIndexContactFloatingMenu) getHivFloatingMenu()).animateFAB(); + break; + case R.id.refer_to_facility_layout: + ((HivIndexContactProfilePresenter) getHivContactProfilePresenter()).referToFacility(); + break; + default: + Timber.d("Unknown fab action"); + break; + } + }; + + ((HivIndexContactFloatingMenu) getHivFloatingMenu()).setFloatMenuClickListener(onClickFloatingMenu); + getHivFloatingMenu().setGravity(Gravity.BOTTOM | Gravity.END); + LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + addContentView(getHivFloatingMenu(), linearLayoutParams); + } + + private void checkPhoneNumberProvided() { + boolean phoneNumberAvailable = (StringUtils.isNotBlank(getHivIndexContactObject().getPhoneNumber())); + ((HivIndexContactFloatingMenu) getHivFloatingMenu()).redraw(phoneNumberAvailable); + } + + @Override + public Context getContext() { + return HivIndexContactProfileActivity.this; + } + + @Override + public void verifyHasPhone() { + // Implement + } + + @Override + public void notifyHasPhone(boolean b) { + // Implement + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode != Activity.RESULT_OK) return; + try { + String jsonString = data.getStringExtra(OpdConstants.JSON_FORM_EXTRA.JSON); + if (jsonString == null) { + finish(); + } + JSONObject form = new JSONObject(jsonString); + if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyRegister.updateEventType)) { + FamilyEventClient familyEventClient = new CoreAllClientsMemberModel().processJsonForm(jsonString, getHivIndexContactObject().getFamilyBaseEntityId()); + familyEventClient.getEvent().setEntityType(CoreConstants.TABLE_NAME.INDEPENDENT_CLIENT); + new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, (FamilyProfileContract.InteractorCallBack) getHivContactProfilePresenter()); + } else { + boolean savedToHivRegistry = data.getBooleanExtra(REGISTERED_TO_HIV_REGISTRY, false); + if (savedToHivRegistry) { + HivProfileActivity.startHivProfileActivity(this, Objects.requireNonNull(HivDao.getMember(getHivIndexContactObject().getBaseEntityId()))); + finish(); + } else { + setHivIndexContactObject(HivIndexDao.getMember(getHivIndexContactObject().getBaseEntityId())); + initializePresenter(); + fetchProfileData(); + } + } + } catch (Exception e) { + Timber.e(e); + } + } + + @Override + public void setFollowUpButtonDue() { + super.setFollowUpButtonDue(); + showFollowUpVisitButton(!getHivIndexContactObject().getFollowedUpByChw()); + } + + @Override + public void onReceivedNotifications(List> list) { + + } + + private void startHivstRegistration() { + CommonRepository commonRepository = org.smartregister.family.util.Utils.context().commonrepository(org.smartregister.family.util.Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(getHivIndexContactObject().getBaseEntityId()); + final CommonPersonObjectClient client = new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + String gender = org.smartregister.family.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + + HivstRegisterActivity.startHivstRegistrationActivity(this, getHivIndexContactObject().getBaseEntityId(), gender); + } +} + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactsContactsRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactsContactsRegisterActivity.java new file mode 100644 index 0000000000..0b9807f63c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivIndexContactsContactsRegisterActivity.java @@ -0,0 +1,76 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import androidx.fragment.app.Fragment; + +import com.google.android.material.bottomnavigation.LabelVisibilityMode; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.activity.CoreHivIndexContactsRegisterActivity; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.fragment.HivIndexContactsRegisterFragment; +import org.smartregister.chw.hiv.fragment.BaseHivIndexContactsRegisterFragment; +import org.smartregister.helper.BottomNavigationHelper; + +public class HivIndexContactsContactsRegisterActivity extends CoreHivIndexContactsRegisterActivity { + + public static void startHIVFormActivity(Activity activity, String baseEntityID, String formName, String payloadType) { + Intent intent = new Intent(activity, HivIndexContactsContactsRegisterActivity.class); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.ACTION, payloadType); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.HIV_REGISTRATION_FORM_NAME, formName); + activity.startActivity(intent); + } + + @NotNull + @Override + protected BaseHivIndexContactsRegisterFragment getRegisterFragment() { + return new HivIndexContactsRegisterFragment(); + } + + @NotNull + @Override + protected Fragment[] getOtherFragments() { + return new Fragment[0]; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + + if (bottomNavigationView != null) { + bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.hiv.R.id.action_register); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.hiv.R.id.action_received_referrals); + + bottomNavigationView.inflateMenu(getMenuResource()); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.hiv.R.id.action_received_referrals); + bottomNavigationHelper.disableShiftMode(bottomNavigationView); + } + } + + @Override + protected void onResumption() { + super.onResumption(); + NavigationMenu menu = NavigationMenu.getInstance(this, null, null); + if (menu != null) { + menu.getNavigationAdapter().setSelectedView(CoreConstants.DrawerMenu.HIV_INDEX_CLIENTS); + } + } + + +} + \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivProfileActivity.java new file mode 100644 index 0000000000..748eec9dc8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivProfileActivity.java @@ -0,0 +1,767 @@ +package org.smartregister.chw.activity; + +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.util.Pair; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.Nullable; + +import com.google.gson.Gson; +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.AncLibrary; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreHivProfileActivity; +import org.smartregister.chw.core.adapter.NotificationListAdapter; +import org.smartregister.chw.core.contract.FamilyProfileExtendedContract; +import org.smartregister.chw.core.dao.AncDao; +import org.smartregister.chw.core.dao.PNCDao; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.listener.OnRetrieveNotifications; +import org.smartregister.chw.core.task.RunnableTask; +import org.smartregister.chw.core.utils.ChwNotificationUtil; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.UpdateDetailsUtil; +import org.smartregister.chw.custom_view.HivFloatingMenu; +import org.smartregister.chw.dao.ChwCBHSDao; +import org.smartregister.chw.hiv.activity.BaseHivFormsActivity; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.hiv.util.Constants; +import org.smartregister.chw.hiv.util.DBConstants; +import org.smartregister.chw.hiv.util.HivUtil; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.interactor.CbhsProfileInteractor; +import org.smartregister.chw.kvp.dao.KvpDao; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.pmtct.PmtctLibrary; +import org.smartregister.chw.pmtct.domain.Visit; +import org.smartregister.chw.presenter.HivProfilePresenter; +import org.smartregister.chw.referral.domain.NeatFormMetaData; +import org.smartregister.chw.referral.domain.NeatFormOption; +import org.smartregister.chw.referral.util.JsonFormConstants; +import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.util.CbhsUtils; +import org.smartregister.chw.util.UtilsFlv; +import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.domain.AlertStatus; +import org.smartregister.domain.Location; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.LocationRepository; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Objects; + +import timber.log.Timber; + +public class HivProfileActivity extends CoreHivProfileActivity implements FamilyProfileExtendedContract.PresenterCallBack, OnRetrieveNotifications { + + public static final String UPDATE_HIV_REGISTRATION = "Update CBHS Registration"; + public static final String ENCOUNTER_TYPE = "encounter_type"; + public static final String NAME = "name"; + public static final String PROPERTIES = "properties"; + public static final String TEXT = "text"; + public static final String SELECTION = "selection"; + private static final String FOLLOWUP_STATUS_DECEASED = "deceased"; + private static final String FOLLOWUP_STATUS_QUALIFIED_FROM_SERVICE = "completed_and_qualified_from_the_services"; + private final List referralTypeModels = new ArrayList<>(); + private final NotificationListAdapter notificationListAdapter = new NotificationListAdapter(); + private Flavor flavor = new HivProfileActivityFlv(); + + public static void startHivProfileActivity(Activity activity, HivMemberObject memberObject) { + Intent intent = new Intent(activity, HivProfileActivity.class); + intent.putExtra(Constants.ActivityPayload.HIV_MEMBER_OBJECT, memberObject); + activity.startActivity(intent); + } + + public static void startHivFollowupActivity(Activity activity, String baseEntityID) throws JSONException { + Intent intent = new Intent(activity, BaseHivFormsActivity.class); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + + HivMemberObject hivMemberObject = HivDao.getMember(baseEntityID); + JSONObject formJsonObject; + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(activity, org.smartregister.chw.util.Constants.CBHSJsonForms.getCbhsFollowupForm()); + + JSONArray steps = null; + if (formJsonObject != null) { + steps = formJsonObject.getJSONArray("steps"); + } + JSONObject step = null; + if (steps != null) { + step = steps.getJSONObject(0); + } + JSONArray fields = null; + if (step != null) { + fields = step.getJSONArray("fields"); + } + + if (fields != null && hivMemberObject != null) { + + if (ChwCBHSDao.hasFollowupVisits(hivMemberObject.getBaseEntityId())) { //Removing the New Client option as followup status for clients with previous followup visits + JSONObject registrationOrFollowupStatus = getJsonObject(fields, "registration_or_followup_status"); + if (registrationOrFollowupStatus != null) { + removeField(registrationOrFollowupStatus.getJSONArray("options"), "new_client"); + } + } else { //Removing options for completed referrals to other services completed for first visit + for (int i = fields.length() - 1; i >= 0; i--) { + JSONObject jsonObject = fields.getJSONObject(i); + if (jsonObject != null && jsonObject.has("name") && jsonObject.getString("name").equalsIgnoreCase("referrals_to_other_services_completed")) { + fields.remove(i); + } + } + } + + + if (StringUtils.isNotBlank(hivMemberObject.getCtcNumber())) { + removeField(fields, "client_hiv_status_after_testing"); + removeField(fields, "was_the_client_tested_for_hiv"); + JSONObject stateOfHivCareAndTreatment = getJsonObject(fields, "state_of_hiv_care_and_treatment"); + removeField(stateOfHivCareAndTreatment.getJSONArray("options"), "na"); + removeField(stateOfHivCareAndTreatment.getJSONArray("options"), "not_registered_in_ctc_clinic"); + } + + String clientHivStatus; + if (StringUtils.isNotBlank(hivMemberObject.getClientHivStatusAfterTesting())) { + clientHivStatus = hivMemberObject.getClientHivStatusAfterTesting(); + } else { + clientHivStatus = hivMemberObject.getClientHivStatusDuringRegistration(); + } + if (clientHivStatus != null && (clientHivStatus.equalsIgnoreCase("negative") || clientHivStatus.equalsIgnoreCase("unknown"))) { + removeField(fields, "state_of_hiv_care_and_treatment"); + } + + int age = org.smartregister.chw.util.Utils.getAgeFromDate(hivMemberObject.getAge()); + + JSONObject referralsIssuedToOtherServices = getJsonObject(fields, "referrals_issued_to_other_services"); + JSONObject completedReferralsToOtherServices = getJsonObject(fields, "referrals_to_other_services_completed"); + + if (age < 15) { //Removing condoms and HIV self testing kits as supplies for children below 15 years + JSONObject supplies = getJsonObject(fields, "supplies_provided"); + if (supplies != null) { + removeField(supplies.getJSONArray("options"), "hiv_self_test_kits"); + removeField(supplies.getJSONArray("options"), "condoms"); + } + } + + if (age < 50) { //Removing Elderly service for clients below 50 years + if (referralsIssuedToOtherServices != null) + removeField(referralsIssuedToOtherServices.getJSONArray("options"), "elderly_centers"); + if (completedReferralsToOtherServices != null) + removeField(completedReferralsToOtherServices.getJSONArray("options"), "elderly_centers"); + } + + if (age > 18) { //Removing OVC (Orphans and Vulnerable Children) as referral services for clients above 18 years + if (referralsIssuedToOtherServices != null) + removeField(referralsIssuedToOtherServices.getJSONArray("options"), "ovc_services"); + + if (completedReferralsToOtherServices != null) + removeField(completedReferralsToOtherServices.getJSONArray("options"), "ovc_services"); + } + + + if (ChwCBHSDao.tbStatusAfterTestingDone(baseEntityID)) { + removeField(fields, "was_the_client_tested_for_tb"); + removeField(fields, "client_tb_status_after_testing"); + } + + if (StringUtils.isNotBlank(hivMemberObject.getTbNumber())) { + JSONObject stateOfRegistrationInTbAndPwidClinics = getJsonObject(fields, "state_of_registration_in_tb_and_pwid_clinics"); + removeField(stateOfRegistrationInTbAndPwidClinics.getJSONArray("options"), "na"); + + //Setting Registered in TB Clinic to Checked by default + JSONObject registeredInTbClinic = getJsonObject(stateOfRegistrationInTbAndPwidClinics.getJSONArray("options"), "registered_in_tb_clinic"); + JSONObject properties = new JSONObject(); + properties.put("checked", true); + registeredInTbClinic.put("properties", properties); + } + + } + + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.JSON_FORM, initializeHealthFacilitiesList(formJsonObject).toString()); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.ACTION, Constants.ActivityPayloadType.FOLLOW_UP_VISIT); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.USE_DEFAULT_NEAT_FORM_LAYOUT, false); + + activity.startActivityForResult(intent, CoreConstants.ProfileActivityResults.CHANGE_COMPLETED); + } + + private static void removeField(JSONArray fields, String fieldName) throws JSONException { + int position = 0; + boolean found = false; + for (int i = 0; i < fields.length(); i++) { + JSONObject field = fields.getJSONObject(i); + if (field.getString("name").equalsIgnoreCase(fieldName)) { + position = i; + found = true; + break; + } + } + if (found) { + fields.remove(position); + } + } + + + private static JSONObject getJsonObject(JSONArray fields, String fieldName) throws JSONException { + int position = 0; + boolean found = false; + for (int i = 0; i < fields.length(); i++) { + JSONObject field = fields.getJSONObject(i); + if (field.getString("name").equalsIgnoreCase(fieldName)) { + position = i; + found = true; + break; + } + } + if (found) { + return fields.getJSONObject(position); + } + return null; + } + + private static JSONObject initializeHealthFacilitiesList(JSONObject form) { + LocationRepository locationRepository = new LocationRepository(); + List locations = locationRepository.getAllLocations(); + if (locations != null && form != null) { + try { + JSONArray fields = form.getJSONArray(JsonFormConstants.STEPS).getJSONObject(0).getJSONArray(JsonFormConstants.FIELDS); + JSONObject referralHealthFacilities = null; + for (int i = 0; i < fields.length(); i++) { + if (fields.getJSONObject(i).getString(JsonFormConstants.NAME).equals(org.smartregister.chw.util.Constants.JsonFormConstants.CLIENT_MOVED_LOCATION)) { + referralHealthFacilities = fields.getJSONObject(i); + break; + } + } + + ArrayList healthFacilitiesOptions = new ArrayList<>(); + + for (Location location : locations) { + NeatFormOption healthFacilityOption = new NeatFormOption(); + healthFacilityOption.name = location.getProperties().getName(); + healthFacilityOption.text = location.getProperties().getName(); + + NeatFormMetaData metaData = new NeatFormMetaData(); + metaData.openmrsEntity = "location_uuid"; + metaData.openmrsEntityId = location.getProperties().getUid(); + + healthFacilityOption.neatFormMetaData = metaData; + healthFacilitiesOptions.add(healthFacilityOption); + } + /* + * Other Option field + */ + NeatFormOption otherFacilityOption = new NeatFormOption(); + otherFacilityOption.text = "Other"; + otherFacilityOption.name = "Other"; + + NeatFormMetaData metaData = new NeatFormMetaData(); + metaData.openmrsEntity = "concept"; + metaData.openmrsEntityId = "Other"; + + otherFacilityOption.neatFormMetaData = metaData; + + healthFacilitiesOptions.add(otherFacilityOption); + + + if (referralHealthFacilities != null) { + JSONArray optionsArray = new JSONArray(); + for (int i = 0; i < referralHealthFacilities.getJSONArray(JsonFormConstants.OPTIONS).length(); i++) { + optionsArray.put(referralHealthFacilities.getJSONArray(JsonFormConstants.OPTIONS).get(i)); + } + referralHealthFacilities.put(JsonFormConstants.OPTIONS, (new JSONArray((new Gson()).toJson(healthFacilitiesOptions)))); + } + } catch (JSONException e) { + Timber.e(e); + } + + } + return form; + } + + @Override + public void setProfileViewDetails(@androidx.annotation.Nullable HivMemberObject hivMemberObject) { + super.setProfileViewDetails(hivMemberObject); + + if (!getHivMemberObject().getClientFollowupStatus().equals("")) { + int labelTextColor; + int background; + String labelText; + + getTvStatus().setVisibility(View.VISIBLE); + switch (getHivMemberObject().getClientFollowupStatus()) { + case FOLLOWUP_STATUS_DECEASED: + labelTextColor = context().getColorResource(org.smartregister.chw.opensrp_chw_anc.R.color.high_risk_text_red); + background = org.smartregister.chw.opensrp_chw_anc.R.drawable.high_risk_label; + labelText = getResources().getString(R.string.client_followup_status_deceased); + hideFollowUpVisitButton(); + break; + case FOLLOWUP_STATUS_QUALIFIED_FROM_SERVICE: + labelTextColor = context().getColorResource(org.smartregister.chw.opensrp_chw_anc.R.color.low_risk_text_green); + background = org.smartregister.chw.opensrp_chw_anc.R.drawable.low_risk_label; + labelText = getResources().getString(R.string.client_followup_status_qualified_from_service); + hideFollowUpVisitButton(); + break; + default: + labelTextColor = context().getColorResource(org.smartregister.chw.opensrp_chw_anc.R.color.default_risk_text_black); + background = org.smartregister.chw.opensrp_chw_anc.R.drawable.risk_label; + labelText = ""; + getTvStatus().setVisibility(View.GONE); + break; + } + + getTvStatus().setText(labelText); + getTvStatus().setTextColor(labelTextColor); + getTvStatus().setBackgroundResource(background); + } + + } + + @Override + protected void onCreation() { + super.onCreation(); + addHivReferralTypes(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + notificationAndReferralRecyclerView.setAdapter(notificationListAdapter); + notificationListAdapter.setOnClickListener(this); + } + + @Override + protected void onResume() { + super.onResume(); + notificationListAdapter.canOpen = true; + ChwNotificationUtil.retrieveNotifications(ChwApplication.getApplicationFlavor().hasReferrals(), getHivMemberObject().getBaseEntityId(), this); + + //Refreshing the hiv Member object with new data just in-case it was updated in the background + setHivMemberObject(HivDao.getMember(getHivMemberObject().getBaseEntityId())); + onMemberDetailsReloaded(getHivMemberObject()); + setProfileViewDetails(HivDao.getMember(getHivMemberObject().getBaseEntityId())); + + try { + CbhsUtils.removeDeceasedClients(getHivMemberObject(), getContext()); + } catch (Exception e) { + Timber.e(e); + } + + if (ChwCBHSDao.completedServiceOrNoLongerContinuingWithService(getHivMemberObject().getBaseEntityId())) { + CbhsUtils.createCloseCbhsEvent(getHivMemberObject()); + } + } + + @Override + public void setupViews() { + super.setupViews(); + + } + + @Override + protected void removeMember() { + IndividualProfileRemoveActivity.startIndividualProfileActivity((Activity) getContext(), getClientDetailsByBaseEntityID(getHivMemberObject().getBaseEntityId()), getHivMemberObject().getFamilyBaseEntityId(), getHivMemberObject().getFamilyHead(), getHivMemberObject().getPrimaryCareGiver(), FpRegisterActivity.class.getCanonicalName()); + } + + @Override + protected void initializePresenter() { + showProgressBar(true); + setHivProfilePresenter(new HivProfilePresenter(this, new CbhsProfileInteractor(this), getHivMemberObject())); + fetchProfileData(); + } + + private void checkPhoneNumberProvided() { + boolean phoneNumberAvailable = (StringUtils.isNotBlank(getHivMemberObject().getPhoneNumber()) || StringUtils.isNotBlank(getHivMemberObject().getPrimaryCareGiverPhoneNumber())); + + ((HivFloatingMenu) getHivFloatingMenu()).redraw(phoneNumberAvailable); + } + + @Override + public void onClick(View view) { + super.onClick(view); + int id = view.getId(); + if (id == R.id.record_hiv_followup_visit) { + openFollowUpVisitForm(false); + } else if (id == R.id.rlHivRegistrationDate) { + startHivRegistrationDetailsActivity(); + } + handleNotificationRowClick(this, view, notificationListAdapter, getHivMemberObject().getBaseEntityId()); + } + + @Override + public Context getContext() { + return HivProfileActivity.this; + } + + @Override + public void verifyHasPhone() { + // Implement + } + + @Override + public void notifyHasPhone(boolean b) { + // Implement + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // recompute schedule + Runnable runnable = () -> ChwScheduleTaskExecutor.getInstance().execute(getHivMemberObject().getBaseEntityId(), org.smartregister.chw.hiv.util.Constants.EventType.FOLLOW_UP_VISIT, new Date()); + org.smartregister.chw.util.Utils.startAsyncTask(new RunnableTask(runnable), null); + try { + CbhsUtils.removeDeceasedClients(getHivMemberObject(), getContext()); + } catch (Exception e) { + Timber.e(e); + } + + if (ChwCBHSDao.completedServiceOrNoLongerContinuingWithService(getHivMemberObject().getBaseEntityId())) { + CbhsUtils.createCloseCbhsEvent(getHivMemberObject()); + } + + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == CoreConstants.ProfileActivityResults.CHANGE_COMPLETED && resultCode == Activity.RESULT_OK) { + Intent intent = new Intent(this, HivRegisterActivity.class); + intent.putExtras(getIntent().getExtras()); + startActivity(intent); + finish(); + } + } + + @Override + public void openMedicalHistory() { + CbhsMedicalHistoryActivity.startMe(this, getHivMemberObject()); + } + + @Override + public void openHivRegistrationForm() { + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + + int age = org.smartregister.chw.util.Utils.getAgeFromDate(getHivMemberObject().getAge()); + try { + updateAgeAndGender(fields, age, getHivMemberObject().getGender()); + } catch (Exception e) { + Timber.e(e); + } + + HivRegisterActivity.startHIVFormActivity(this, getHivMemberObject().getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } + + } + + @Override + public void openUpcomingServices() { + CbhsUpcomingServiceActivity.startMe(this, HivUtil.toMember(getHivMemberObject())); + } + + @Override + public void setFamilyStatus(@androidx.annotation.Nullable AlertStatus status) { + super.setFamilyStatus(status); + if (getHivMemberObject().getFamilyMemberEntityType().equals(Constants.FamilyMemberEntityType.EC_INDEPENDENT_CLIENT)) { + findViewById(R.id.rlFamilyServicesDue).setVisibility(View.GONE); + } + //TODO fix editing of CBHS registration then remove the line below + findViewById(R.id.rlHivRegistrationDate).setVisibility(View.GONE); + } + + @Override + public void openFamilyDueServices() { + Intent intent = new Intent(this, FamilyProfileActivity.class); + + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_BASE_ENTITY_ID, getHivMemberObject().getFamilyBaseEntityId()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_HEAD, getHivMemberObject().getFamilyHead()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.PRIMARY_CAREGIVER, getHivMemberObject().getPrimaryCareGiver()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_NAME, getHivMemberObject().getFamilyName()); + + intent.putExtra(CoreConstants.INTENT_KEY.SERVICE_DUE, true); + startActivity(intent); + } + + @Override + public void openFollowUpVisitForm(boolean isEdit) { + if (!isEdit) { + try { + startHivFollowupActivity(this, getHivMemberObject().getBaseEntityId()); + } catch (JSONException e) { + Timber.e(e); + } + } + } + + private void addHivReferralTypes() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + + //HIV Testing referrals will only be issued to non positive clients + if (getHivMemberObject().getCtcNumber().isEmpty()) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.hts_referral), CoreConstants.JSON_FORM.getHtsReferralForm(), CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST)); + } else { //HIV Treatment and care referrals will be issued to HIV Positive clients + referralTypeModels.add(new ReferralTypeModel(getString(R.string.hiv_referral), CoreConstants.JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.SICK_HIV)); + } + + referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), CoreConstants.JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); + + if (isClientEligibleForAnc(getHivMemberObject())) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.anc_danger_signs), org.smartregister.chw.util.Constants.JSON_FORM.getAncUnifiedReferralForm(), CoreConstants.TASKS_FOCUS.ANC_DANGER_SIGNS)); + referralTypeModels.add(new ReferralTypeModel(getString(R.string.pnc_referral), CoreConstants.JSON_FORM.getPncUnifiedReferralForm(), CoreConstants.TASKS_FOCUS.PNC_DANGER_SIGNS)); + if (!AncDao.isANCMember(getHivMemberObject().getBaseEntityId())) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.pregnancy_confirmation), CoreConstants.JSON_FORM.getPregnancyConfirmationReferralForm(), CoreConstants.TASKS_FOCUS.PREGNANCY_CONFIRMATION)); + } + } + referralTypeModels.add(new ReferralTypeModel(getString(R.string.gbv_referral), CoreConstants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); + } + + } + + public List getReferralTypeModels() { + return referralTypeModels; + } + + @Override + public void initializeCallFAB() { + setHivFloatingMenu(new HivFloatingMenu(this, getHivMemberObject())); + + OnClickFloatingMenu onClickFloatingMenu = viewId -> { + switch (viewId) { + case R.id.hiv_fab: + checkPhoneNumberProvided(); + ((HivFloatingMenu) getHivFloatingMenu()).animateFAB(); + break; + case R.id.call_layout: + ((HivFloatingMenu) getHivFloatingMenu()).launchCallWidget(); + ((HivFloatingMenu) getHivFloatingMenu()).animateFAB(); + break; + case R.id.refer_to_facility_layout: + ((HivProfilePresenter) getHivProfilePresenter()).referToFacility(); + break; + default: + Timber.d("Unknown fab action"); + break; + } + + }; + + ((HivFloatingMenu) getHivFloatingMenu()).setFloatMenuClickListener(onClickFloatingMenu); + getHivFloatingMenu().setGravity(Gravity.BOTTOM | Gravity.END); + LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); + addContentView(getHivFloatingMenu(), linearLayoutParams); + } + + @Override + public void onReceivedNotifications(List> notifications) { + handleReceivedNotifications(this, notifications, notificationListAdapter); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(org.smartregister.chw.core.R.menu.hiv_profile_menu, menu); + menu.findItem(R.id.action_anc_registration).setVisible(isClientEligibleForAnc(getHivMemberObject()) && !AncDao.isANCMember(getHivMemberObject().getBaseEntityId())); + menu.findItem(R.id.action_pregnancy_out_come).setVisible(isClientEligibleForAnc(getHivMemberObject()) && !PNCDao.isPNCMember(getHivMemberObject().getBaseEntityId())); + menu.findItem(R.id.action_location_info).setVisible(UpdateDetailsUtil.isIndependentClient(getHivMemberObject().getBaseEntityId())); + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + String dob = getHivMemberObject().getAge(); + int age = Utils.getAgeFromDate(dob); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(getHivMemberObject().getBaseEntityId()) && age >= 15); + } + if (ChwApplication.getApplicationFlavor().hasKvp()) { + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(getHivMemberObject().getBaseEntityId())); + } + // flavor.updateTbMenuItems(getHivMemberObject().getBaseEntityId(), menu); + if (ChwApplication.getApplicationFlavor().hasMalaria()) + UtilsFlv.updateMalariaMenuItems(getHivMemberObject().getBaseEntityId(), menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == org.smartregister.chw.core.R.id.action_tb_registration) { + startTbRegister(); + return true; + } + if (itemId == R.id.action_anc_registration) { + startAncRegister(); + return true; + } else if (itemId == R.id.action_pregnancy_out_come) { + PncRegisterActivity.startPncRegistrationActivity((Activity) getContext(), getHivMemberObject().getBaseEntityId(), null, CoreConstants.JSON_FORM.getPregnancyOutcome(), AncLibrary.getInstance().getUniqueIdRepository().getNextUniqueId().getOpenmrsId(), getHivMemberObject().getFamilyBaseEntityId(), getHivMemberObject().getFamilyName(), null); + return true; + } else if (itemId == R.id.action_hivst_registration) { + startHivstRegistration(); + return true; + } else if (itemId == R.id.action_kvp_prep_registration) { + startKvpPrepRegistration(); + return true; + } + return super.onOptionsItemSelected(item); + } + + private void startKvpPrepRegistration() { + String gender = org.smartregister.chw.util.Utils.getClientGender(getHivMemberObject().getBaseEntityId()); + String dob = getHivMemberObject().getAge(); + int age = Utils.getAgeFromDate(dob); + KvpPrEPRegisterActivity.startRegistration((Activity) getContext(), getHivMemberObject().getBaseEntityId(), gender, age); + } + + + private void startHivstRegistration() { + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(getHivMemberObject().getBaseEntityId()); + final CommonPersonObjectClient client = new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + + HivstRegisterActivity.startHivstRegistrationActivity(this, getHivMemberObject().getBaseEntityId(), gender); + } + + protected void startTbRegister() { + try { + TbRegisterActivity.startTbFormActivity((Activity) getContext(), getHivMemberObject().getBaseEntityId(), CoreConstants.JSON_FORM.getTbRegistration(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, CoreConstants.JSON_FORM.getTbRegistration()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + + protected void startAncRegister() { + AncRegisterActivity.startAncRegistrationActivity((Activity) getContext(), Objects.requireNonNull(getHivMemberObject()).getBaseEntityId(), getHivMemberObject().getPhoneNumber(), org.smartregister.chw.util.Constants.JSON_FORM.getAncRegistration(), null, getHivMemberObject().getFamilyBaseEntityId(), getHivMemberObject().getFamilyName()); + } + + /** + * Pre-populating the registration form before opening it + */ + public void startHivRegistrationDetailsActivity() { + Intent intent = new Intent(this, BaseHivFormsActivity.class); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.BASE_ENTITY_ID, getHivMemberObject().getBaseEntityId()); + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + + JSONObject formJsonObject = null; + try { + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + } catch (JSONException e) { + Timber.e(e); + } + + try { + + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + int age = org.smartregister.chw.util.Utils.getAgeFromDate(getHivMemberObject().getAge()); + updateAgeAndGender(fields, age, getHivMemberObject().getGender()); + + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + formJsonObject.put(ENCOUNTER_TYPE, UPDATE_HIV_REGISTRATION); + + for (int i = 0; i < fields.length(); i++) { + JSONObject field = fields.getJSONObject(i); + if (field.getString(NAME).equals(DBConstants.Key.CBHS_NUMBER)) { + field.getJSONObject(PROPERTIES).put(TEXT, getHivMemberObject().getCbhsNumber()); + } else if (field.getString(NAME).equals(DBConstants.Key.CLIENT_HIV_STATUS_DURING_REGISTRATION)) { + if (!getHivMemberObject().getCtcNumber().isEmpty()) + field.getJSONObject(PROPERTIES).put(SELECTION, "1"); + else field.getJSONObject(PROPERTIES).put(SELECTION, "0"); + } else if (field.getString(NAME).equals(DBConstants.Key.CTC_NUMBER) && !getHivMemberObject().getCtcNumber().isEmpty()) { + field.getJSONObject(PROPERTIES).put(TEXT, getHivMemberObject().getCtcNumber()); + } else if (field.getString(NAME).equals(DBConstants.Key.TB_NUMBER) && !getHivMemberObject().getTbNumber().isEmpty()) { + field.getJSONObject(PROPERTIES).put(TEXT, getHivMemberObject().getTbNumber()); + } else if (field.getString(NAME).equals(DBConstants.Key.MAT_NUMBER) && !getHivMemberObject().getMatNumber().isEmpty()) { + field.getJSONObject(PROPERTIES).put(TEXT, getHivMemberObject().getMatNumber()); + } else if (field.getString(NAME).equals(DBConstants.Key.RCH_NUMBER) && !getHivMemberObject().getRchNumber().isEmpty()) { + field.getJSONObject(PROPERTIES).put(TEXT, getHivMemberObject().getRchNumber()); + } + } + + } catch (Exception e) { + Timber.e(e); + } + + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.JSON_FORM, formJsonObject.toString()); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.ACTION, Constants.ActivityPayloadType.REGISTRATION); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.USE_DEFAULT_NEAT_FORM_LAYOUT, false); + + this.startActivityForResult(intent, org.smartregister.chw.anc.util.Constants.REQUEST_CODE_HOME_VISIT); + } + + protected boolean isClientEligibleForAnc(HivMemberObject hivMemberObject) { + if (hivMemberObject.getGender().equalsIgnoreCase("Female")) { + //Obtaining the clients CommonPersonObjectClient used for checking is the client is Of Reproductive Age + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(hivMemberObject.getBaseEntityId()); + final CommonPersonObjectClient client = new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + + return org.smartregister.chw.core.utils.Utils.isMemberOfReproductiveAge(client, 15, 49); + } + return false; + } + + @SuppressLint("StringFormatMatches") + @Override + public void updateLastVisitRow(@Nullable Date lastVisitDate) { + Visit lastFollowupVisit = getVisit(org.smartregister.chw.util.Constants.Events.CBHS_FOLLOWUP); + if (lastFollowupVisit != null) { + TextView tvLastVisitDay = findViewById(R.id.textview_last_vist_day); + tvLastVisitDay.setVisibility(View.VISIBLE); + + int numOfDays = Days.daysBetween(new DateTime(lastFollowupVisit.getDate()).toLocalDate(), new DateTime().toLocalDate()).getDays(); + + if (numOfDays <= 1) { + tvLastVisitDay.setText(getString(R.string.cbhs_visit_less_than_twenty_four)); + } else { + tvLastVisitDay.setText(getString(R.string.cbhs_last_visit_n_days_ago, numOfDays)); + } + + findViewById(R.id.rl_last_visit_layout).setVisibility(View.VISIBLE); + } + } + + public @javax.annotation.Nullable Visit getVisit(String eventType) { + return PmtctLibrary.getInstance().visitRepository().getLatestVisit(getHivMemberObject().getBaseEntityId(), eventType); + } + + public interface Flavor { + // void updateTbMenuItems(@Nullable String baseEntityId, @Nullable Menu menu); + } + + @Override + public void setUpComingServicesStatus(@Nullable String service, @Nullable AlertStatus status, @Nullable Date date) { + Date nextAppointmentDate = ChwCBHSDao.getNextVisitDate(getHivMemberObject().getBaseEntityId()); + if (nextAppointmentDate == null) { + getRlUpcomingServices().setVisibility(View.GONE); + } else { + super.setUpComingServicesStatus(service, status, nextAppointmentDate); + } + } +} + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivRegisterActivity.java new file mode 100644 index 0000000000..e71295135a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivRegisterActivity.java @@ -0,0 +1,79 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import com.google.android.material.bottomnavigation.LabelVisibilityMode; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.activity.CoreHivRegisterActivity; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.fragment.HivRegisterFragment; +import org.smartregister.chw.hiv.fragment.BaseHivCommunityFollowupRegisterFragment; +import org.smartregister.chw.hiv.fragment.BaseHivRegisterFragment; +import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.listener.BottomNavigationListener; + +import java.util.List; + +public class HivRegisterActivity extends CoreHivRegisterActivity { + + public static void startHIVFormActivity(Activity activity, String baseEntityID, String formName, String payloadType) { + Intent intent = new Intent(activity, HivRegisterActivity.class); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.ACTION, payloadType); + intent.putExtra(org.smartregister.chw.hiv.util.Constants.ActivityPayload.HIV_REGISTRATION_FORM_NAME, formName); + activity.startActivity(intent); + } + + @NotNull + @Override + protected BaseHivRegisterFragment getRegisterFragment() { + return new HivRegisterFragment(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + NavigationMenu.getInstance(this, null, null); + } + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + + if (bottomNavigationView != null) { + bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.hiv.R.id.action_register); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); + + bottomNavigationView.inflateMenu(getMenuResource()); + bottomNavigationHelper.disableShiftMode(bottomNavigationView); + + BottomNavigationListener hivBottomNavigationListener = getBottomNavigation(this); + bottomNavigationView.setOnNavigationItemSelectedListener(hivBottomNavigationListener); + + } + } + + @NotNull + @Override + protected BaseHivCommunityFollowupRegisterFragment[] getOtherFragments() { + return new BaseHivCommunityFollowupRegisterFragment[0]; + } + + @Override + protected void onResumption() { + super.onResumption(); + NavigationMenu menu = NavigationMenu.getInstance(this, null, null); + if (menu != null) { + menu.getNavigationAdapter().setSelectedView(CoreConstants.DrawerMenu.CBHS_CLIENTS); + } + } +} + \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstProfileActivity.java new file mode 100644 index 0000000000..00e3aed7d9 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstProfileActivity.java @@ -0,0 +1,221 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreFamilyProfileActivity; +import org.smartregister.chw.core.activity.CoreHivstProfileActivity; +import org.smartregister.chw.core.interactor.CoreHivstProfileInteractor; +import org.smartregister.chw.core.presenter.CoreFamilyOtherMemberActivityPresenter; +import org.smartregister.chw.core.presenter.CoreHivstMemberProfilePresenter; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.hivst.util.Constants; +import org.smartregister.chw.kvp.dao.KvpDao; +import org.smartregister.chw.util.HivstUtils; +import org.smartregister.chw.util.Utils; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.domain.AlertStatus; +import org.smartregister.family.util.DBConstants; + +import androidx.annotation.NonNull; +import timber.log.Timber; + +import static org.smartregister.chw.core.utils.Utils.getCommonPersonObjectClient; +import static org.smartregister.chw.util.Utils.getClientGender; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + + +public class HivstProfileActivity extends CoreHivstProfileActivity { + + public static void startProfile(Activity activity, String baseEntityId) { + Intent intent = new Intent(activity, HivstProfileActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + activity.startActivity(intent); + } + + @Override + protected void initializePresenter() { + showProgressBar(true); + String baseEntityId = getIntent().getStringExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID); + memberObject = HivstDao.getMember(baseEntityId); + profilePresenter = new CoreHivstMemberProfilePresenter(this, new CoreHivstProfileInteractor(), memberObject); + fetchProfileData(); + profilePresenter.refreshProfileBottom(); + } + + @Override + protected void startHivServicesRegistration() { + CommonPersonObjectClient commonPersonObjectClient = getCommonPersonObjectClient(memberObject.getBaseEntityId()); + String gender = Utils.getValue(commonPersonObjectClient.getColumnmaps(), DBConstants.KEY.GENDER, false); + String dob = Utils.getValue(commonPersonObjectClient.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = Utils.getAgeFromDate(dob); + + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new com.vijay.jsonwizard.utils.FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + updateAgeAndGender(fields, age, gender); + + HivRegisterActivity.startHIVFormActivity(this, memberObject.getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + protected Class getFamilyProfileActivityClass() { + return null; + } + + @Override + public void startIssueSelfTestingKitsForm(String baseEntityId) { + JSONObject form = FormUtils.getFormUtils().getFormJson(Constants.FORMS.HIVST_ISSUE_KITS); + try { + form.put(org.smartregister.util.JsonFormUtils.ENTITY_ID, baseEntityId); + JSONObject global = form.getJSONObject("global"); + boolean knownPositiveFromHIV = HivDao.isRegisteredForHiv(baseEntityId) && StringUtils.isNotBlank(HivDao.getMember(baseEntityId).getCtcNumber()); + global.put("known_positive", HivstDao.isTheClientKnownPositiveAtReg(baseEntityId) || knownPositiveFromHIV); + } catch (JSONException e) { + Timber.e(e); + } + startFormActivity(form); + } + + @Override + public void startResultViewActivity(Context context, String baseEntityId) { + HivstResultViewActivity.startResultViewActivity(context, baseEntityId); + } + + @Override + public void onClick(View view) { + int id = view.getId(); + if (id == R.id.rlSelfTestingResults) { + startResultViewActivity(this, memberObject.getBaseEntityId()); + } else { + super.onClick(view); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + menu.findItem(org.smartregister.chw.core.R.id.action_cbhs_registration).setVisible(!HivDao.isRegisteredForHiv(memberObject.getBaseEntityId())); + if(ChwApplication.getApplicationFlavor().hasKvp()){ + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(memberObject.getBaseEntityId())); + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if(itemId == R.id.action_kvp_prep_registration){ + String gender = getClientGender(memberObject.getBaseEntityId()); + String dob = memberObject.getAge(); + int age = Utils.getAgeFromDate(dob); + KvpPrEPRegisterActivity.startRegistration(HivstProfileActivity.this, memberObject.getBaseEntityId(), gender, age); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void startReferralForm() { + HivstUtils.startHIVSTReferral(this, memberObject.getBaseEntityId()); + } + + @Override + public void showReferralView() { + boolean knownPositiveFromHIV = HivDao.isRegisteredForHiv(memberObject.getBaseEntityId()) && StringUtils.isNotBlank(HivDao.getMember(memberObject.getBaseEntityId()).getCtcNumber()); + if (knownPositiveFromHIV || HivstDao.isTheClientKnownPositiveAtReg(memberObject.getBaseEntityId())) { + baseHivstFloatingMenu.findViewById(R.id.refer_to_facility_layout).setVisibility(View.GONE); + }else { + baseHivstFloatingMenu.findViewById(R.id.refer_to_facility_layout).setVisibility(View.VISIBLE); + } + } + + @Override + protected void removeMember() { + //implement + } + + + @NonNull + @Override + public CoreFamilyOtherMemberActivityPresenter presenter() { + return null; + } + + @Override + public void setProfileImage(String s, String s1) { + //implement + } + + @Override + public void setProfileDetailThree(String s) { + //implement + } + + @Override + public void toggleFamilyHead(boolean b) { + //implement + } + + @Override + public void togglePrimaryCaregiver(boolean b) { + //implement + } + + @Override + public void refreshList() { + //implement + } + + @Override + public void updateHasPhone(boolean b) { + //implement + } + + @Override + public void setFamilyServiceStatus(String s) { + //implement + } + + @Override + public void verifyHasPhone() { + //implement + } + + @Override + public void notifyHasPhone(boolean b) { + //implement + } + + @Override + public void refreshMedicalHistory(boolean hasHistory) { + rlLastVisit.setVisibility(View.GONE); + } + + @Override + public void refreshFamilyStatus(AlertStatus status) { + super.refreshFamilyStatus(status); + rlFamilyServicesDue.setVisibility(View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstRegisterActivity.java new file mode 100644 index 0000000000..c13e19f79f --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstRegisterActivity.java @@ -0,0 +1,38 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.core.activity.CoreHivstRegisterActivity; +import org.smartregister.chw.fragment.HivstMobilizationFragment; +import org.smartregister.chw.fragment.HivstRegisterFragment; +import org.smartregister.chw.hivst.util.Constants; +import org.smartregister.view.fragment.BaseRegisterFragment; + +import androidx.fragment.app.Fragment; + +public class HivstRegisterActivity extends CoreHivstRegisterActivity { + + + public static void startHivstRegistrationActivity(Activity activity, String memberBaseEntityID, String gender) { + Intent intent = new Intent(activity, HivstRegisterActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, memberBaseEntityID); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.ACTION, Constants.ACTIVITY_PAYLOAD_TYPE.REGISTRATION); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.HIVST_FORM_NAME, Constants.FORMS.HIVST_REGISTRATION); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.GENDER, gender); + activity.startActivity(intent); + } + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new HivstRegisterFragment(); + } + + @Override + protected Fragment[] getOtherFragments() { + return new Fragment[]{ + new HivstMobilizationFragment() + }; + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstResultViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstResultViewActivity.java new file mode 100644 index 0000000000..cca063c2cd --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/HivstResultViewActivity.java @@ -0,0 +1,55 @@ +package org.smartregister.chw.activity; + +import android.content.Context; +import android.content.Intent; + +import com.vijay.jsonwizard.constants.JsonFormConstants; +import com.vijay.jsonwizard.domain.Form; + +import org.smartregister.chw.R; +import org.smartregister.chw.fragment.HivstResultsViewFragment; +import org.smartregister.chw.hivst.activity.BaseHivstResultViewActivity; +import org.smartregister.chw.hivst.fragment.BaseHivstResultViewFragment; +import org.smartregister.chw.hivst.util.Constants; +import org.smartregister.family.util.Utils; + +public class HivstResultViewActivity extends BaseHivstResultViewActivity { + private static String baseEntityId; + + public static void startResultViewActivity(Context context, String baseEntityId) { + Intent intent = new Intent(context, HivstResultViewActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + HivstResultViewActivity.baseEntityId = baseEntityId; + context.startActivity(intent); + } + + public static void startResultsForm(Context context, String jsonString, String baseEntityId, String entityId) { + Intent intent = new Intent(context, HivstResultViewActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.HIVST_FORM_NAME, jsonString); + intent.putExtra(Constants.JSON_FORM_EXTRA.ENTITY_ID, entityId); + context.startActivity(intent); + } + + @Override + public void startFormActivity(String jsonString) { + Intent intent = new Intent(this, Utils.metadata().familyMemberFormActivity); + intent.putExtra(Constants.JSON_FORM_EXTRA.JSON, jsonString); + + Form form = new Form(); + form.setName(getString(R.string.hivst_result)); + form.setActionBarBackground(R.color.family_actionbar); + form.setNavigationBackground(R.color.family_navigation); + form.setHomeAsUpIndicator(R.mipmap.ic_cross_white); + form.setPreviousLabel(getResources().getString(R.string.back)); + intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); + + startActivityForResult(intent, Constants.REQUEST_CODE_GET_JSON); + } + + + @Override + public BaseHivstResultViewFragment getBaseFragment() { + return HivstResultsViewFragment.newInstance(baseEntityId); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/InAppReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/InAppReportsActivity.java new file mode 100644 index 0000000000..a3598cb7c1 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/InAppReportsActivity.java @@ -0,0 +1,112 @@ +package org.smartregister.chw.activity; + +import android.content.Intent; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.view.Menu; +import android.view.View; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.widget.Toolbar; +import androidx.constraintlayout.widget.ConstraintLayout; + +import com.google.android.material.appbar.AppBarLayout; + +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.job.ChwIndicatorGeneratingJob; +import org.smartregister.view.activity.SecuredActivity; +import org.smartregister.view.customcontrols.CustomFontTextView; + +public class InAppReportsActivity extends SecuredActivity implements View.OnClickListener { + + + protected CustomFontTextView toolBarTextView; + protected AppBarLayout appBarLayout; + protected ConstraintLayout cbhsReportsLayout; + protected ConstraintLayout motherChampionReportsLayout; + protected ConstraintLayout condomDistributionReports; + protected ConstraintLayout agyweports; + + @Override + protected void onCreation() { + ChwIndicatorGeneratingJob.scheduleJobImmediately(ChwIndicatorGeneratingJob.TAG); + setContentView(R.layout.activity_in_app_reports); + setUpToolbar(); + setUpViews(); + } + + @Override + protected void onResumption() { + //overridden + } + + + public void setUpViews() { + cbhsReportsLayout = findViewById(R.id.cbhs_summary); + motherChampionReportsLayout = findViewById(R.id.mother_champion_reports); + condomDistributionReports = findViewById(R.id.cdp_reports); + agyweports = findViewById(R.id.agyw_reports); + + if (ChwApplication.getApplicationFlavor().hasAGYW()) { + agyweports.setVisibility(View.VISIBLE); + } + + if (ChwApplication.getApplicationFlavor().hasCdp()) { + condomDistributionReports.setVisibility(View.VISIBLE); + } + motherChampionReportsLayout.setOnClickListener(this); + condomDistributionReports.setOnClickListener(this); + cbhsReportsLayout.setOnClickListener(this); + agyweports.setOnClickListener(this); + } + + public void setUpToolbar() { + Toolbar toolbar = findViewById(org.smartregister.chw.core.R.id.back_to_nav_toolbar); + toolBarTextView = toolbar.findViewById(org.smartregister.chw.core.R.id.toolbar_title); + setSupportActionBar(toolbar); + + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + final Drawable upArrow = getResources().getDrawable(org.smartregister.chw.core.R.drawable.ic_arrow_back_white_24dp); + actionBar.setHomeAsUpIndicator(upArrow); + actionBar.setElevation(0); + } + toolbar.setNavigationOnClickListener(v -> finish()); + toolBarTextView.setText(R.string.reports_title); + toolBarTextView.setOnClickListener(v -> finish()); + appBarLayout = findViewById(org.smartregister.chw.core.R.id.app_bar); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + appBarLayout.setOutlineProvider(null); + } + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + return false; + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.cbhs_summary) { + Intent intent = new Intent(this, CBHSReportsActivity.class); + startActivity(intent); + } + if (id == R.id.mother_champion_reports) { + Intent intent = new Intent(this, MotherChampionReportsActivity.class); + startActivity(intent); + } + if (id == R.id.cdp_reports) { + Intent intent = new Intent(this, CdpReportsActivity.class); + startActivity(intent); + } + if (id == R.id.agyw_reports) { + Intent intent = new Intent(this, AGYWReportsActivity.class); + startActivity(intent); + } + } + +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPMedicalHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPMedicalHistoryActivity.java new file mode 100644 index 0000000000..9c6eca945b --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPMedicalHistoryActivity.java @@ -0,0 +1,251 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.BulletSpan; +import android.text.style.StyleSpan; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.presenter.BaseAncMedicalHistoryPresenter; +import org.smartregister.chw.core.activity.CoreAncMedicalHistoryActivity; +import org.smartregister.chw.core.activity.DefaultAncMedicalHistoryActivityFlv; +import org.smartregister.chw.interactor.KvpPrEPMedicalHistoryInteractor; +import org.smartregister.chw.kvp.domain.MemberObject; +import org.smartregister.chw.util.Constants; + +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import timber.log.Timber; + +public class KvpPrEPMedicalHistoryActivity extends CoreAncMedicalHistoryActivity { + private static MemberObject kvpMemberObject; + private final Flavor flavor = new KvpPrEPMedicalHistoryActivityFlv(); + private ProgressBar progressBar; + + public static void startMe(Activity activity, MemberObject memberObject) { + Intent intent = new Intent(activity, KvpPrEPMedicalHistoryActivity.class); + kvpMemberObject = memberObject; + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncMedicalHistoryPresenter(new KvpPrEPMedicalHistoryInteractor(), this, kvpMemberObject.getBaseEntityId()); + } + + @Override + public void setUpView() { + linearLayout = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.linearLayoutMedicalHistory); + progressBar = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.progressBarMedicalHistory); + + TextView tvTitle = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.tvTitle); + tvTitle.setText(getString(org.smartregister.chw.opensrp_chw_anc.R.string.back_to, kvpMemberObject.getFullName())); + + ((TextView) findViewById(R.id.medical_history)).setText(getString(R.string.visits_history)); + } + + @Override + public View renderView(List visits) { + super.renderView(visits); + View view = flavor.bindViews(this); + displayLoadingState(true); + flavor.processViewData(visits, this); + displayLoadingState(false); + TextView kvpVisitTitle = view.findViewById(org.smartregister.chw.core.R.id.customFontTextViewHealthFacilityVisitTitle); + kvpVisitTitle.setText(R.string.kvp_visit); + return view; + } + + @Override + public void displayLoadingState(boolean state) { + progressBar.setVisibility(state ? View.VISIBLE : View.GONE); + } + + private static class KvpPrEPMedicalHistoryActivityFlv extends DefaultAncMedicalHistoryActivityFlv { + private final StyleSpan boldSpan = new StyleSpan(android.graphics.Typeface.BOLD); + + @Override + protected void processAncCard(String has_card, Context context) { + // super.processAncCard(has_card, context); + linearLayoutAncCard.setVisibility(View.GONE); + } + + @Override + protected void processHealthFacilityVisit(List> hf_visits, Context context) { + //super.processHealthFacilityVisit(hf_visits, context); + } + + @Override + public void processViewData(List visits, Context context) { + + if (visits.size() > 0) { + int days = 0; + List> hf_visits = new ArrayList<>(); + + int x = 0; + while (x < visits.size()) { + LinkedHashMap visitDetails = new LinkedHashMap<>(); + // the first object in this list is the days difference + if (x == 0) { + days = Days.daysBetween(new DateTime(visits.get(visits.size() - 1).getDate()), new DateTime()).getDays(); + } + + String[] visitTypeParams = {"visit_type", "client_hiv_status"}; + extractVisitDetails(visits, visitTypeParams, visitDetails, x, context); + + String[] structuralServicesParams = {"structural_services_provided", "other_structural_services_provided"}; + extractVisitDetails(visits, structuralServicesParams, visitDetails, x, context); + + String[] protectiveServicesParams = {"condoms_given", "type_of_issued_condoms", "number_of_male_condoms_issued", "number_of_female_condoms_issued", "number_of_iec_distributed", "number_of_needles_and_syringes_distributed", "number_of_sterile_water_for_injection_distributed", "number_of_alcohol_swabs_distributed", "number_of_disposable_safety_boxes_distributed", "number_of_plasters_distributed", "kits_distributed", "number_of_coupons_distributed_for_social_network"}; + extractVisitDetails(visits, protectiveServicesParams, visitDetails, x, context); + + String[] referralServicesParams = {"referral_to_structural_services", "other_referral_to_structural_services", "referrals_completed_to_structural_services", "other_referrals_completed_to_structural_services"}; + extractVisitDetails(visits, referralServicesParams, visitDetails, x, context); + + String[] sbccServicesParams = {"sbcc_services_offered"}; + extractVisitDetails(visits, sbccServicesParams, visitDetails, x, context); + hf_visits.add(visitDetails); + + x++; + } + + processLastVisit(days, context); + processVisit(hf_visits, context, visits); + } + } + + private void extractVisitDetails(List sourceVisits, String[] hf_params, LinkedHashMap visitDetailsMap, int iteration, Context context) { + // get the hf details + Map map = new HashMap<>(); + for (String param : hf_params) { + try { + List details = sourceVisits.get(iteration).getVisitDetails().get(param); + map.put(param, getTexts(context, details)); + } catch (Exception e) { + e.printStackTrace(); + } + + } + visitDetailsMap.putAll(map); + } + + + private void processLastVisit(int days, Context context) { + linearLayoutLastVisit.setVisibility(View.VISIBLE); + if (days < 1) { + customFontTextViewLastVisit.setText(org.smartregister.chw.core.R.string.less_than_twenty_four); + } else { + customFontTextViewLastVisit.setText(StringUtils.capitalize(MessageFormat.format(context.getString(org.smartregister.chw.core.R.string.days_ago), String.valueOf(days)))); + } + } + + + protected void processVisit(List> community_visits, Context context, List visits) { + final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()); + if (community_visits != null && community_visits.size() > 0) { + linearLayoutHealthFacilityVisit.setVisibility(View.VISIBLE); + + int x = 0; + for (LinkedHashMap vals : community_visits) { + View view = inflater.inflate(R.layout.medical_history_visit, null); + view.findViewById(R.id.title).setVisibility(View.GONE); + TextView tvTypeOfService = view.findViewById(R.id.type_of_service); + LinearLayout visitDetailsLayout = view.findViewById(R.id.visit_details_layout); + + String visitType; + + if (Constants.Events.KVP_PREP_FOLLOWUP_VISIT.equals(visits.get(x).getVisitType())) { + visitType = context.getString(R.string.kvp_prep_followup_visit); + } else { + visitType = visits.get(x).getVisitType(); + } + tvTypeOfService.setText(visitType + " - " + simpleDateFormat.format(visits.get(x).getDate())); + + + for (LinkedHashMap.Entry entry : vals.entrySet()) { + TextView visitDetailTv = new TextView(context); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams + ((int) LinearLayout.LayoutParams.MATCH_PARENT, (int) LinearLayout.LayoutParams.WRAP_CONTENT); + + visitDetailTv.setLayoutParams(params); + float scale = context.getResources().getDisplayMetrics().density; + int dpAsPixels = (int) (10 * scale + 0.5f); + visitDetailTv.setPadding(dpAsPixels, 0, 0, 0); + visitDetailsLayout.addView(visitDetailTv); + + + try { + int resource = context.getResources().getIdentifier("kvp_" + entry.getKey(), "string", context.getPackageName()); + evaluateView(context, vals, visitDetailTv, entry.getKey(), resource, ""); + } catch (Exception e) { + Timber.e(e); + } + } + linearLayoutHealthFacilityVisitDetails.addView(view, 0); + + x++; + } + } + } + + private void evaluateView(Context context, Map vals, TextView tv, String valueKey, int viewTitleStringResource, String valuePrefixInStringResources) { + if (StringUtils.isNotBlank(getMapValue(vals, valueKey))) { + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); + spannableStringBuilder.append(context.getString(viewTitleStringResource), boldSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).append("\n"); + + String stringValue = getMapValue(vals, valueKey); + String[] stringValueArray; + if (stringValue.contains(",")) { + stringValueArray = stringValue.split(","); + for (String value : stringValueArray) { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, value.trim()) + "\n", new BulletSpan(10), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } else { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, stringValue)).append("\n"); + } + tv.setText(spannableStringBuilder); + } else { + tv.setVisibility(View.GONE); + } + } + + + private String getMapValue(Map map, String key) { + if (map.containsKey(key)) { + return map.get(key); + } + return ""; + } + + private String getStringResource(Context context, String prefix, String resourceName) { + int resourceId = context.getResources(). + getIdentifier(prefix + resourceName.trim(), "string", context.getPackageName()); + try { + return context.getString(resourceId); + } catch (Exception e) { + Timber.e(e); + return prefix + resourceName; + } + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPProfileActivity.java new file mode 100644 index 0000000000..6e7874967d --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPProfileActivity.java @@ -0,0 +1,156 @@ +package org.smartregister.chw.activity; + +import static org.smartregister.chw.util.Utils.getCommonReferralTypes; +import static org.smartregister.chw.util.Utils.launchClientReferralActivity; + +import android.app.Activity; +import android.content.Intent; +import android.view.Menu; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import org.apache.commons.lang3.StringUtils; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreKvpProfileActivity; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.dao.ChwKvpDao; +import org.smartregister.chw.hivst.dao.HivstDao; +import org.smartregister.chw.kvp.KvpLibrary; +import org.smartregister.chw.kvp.domain.Visit; +import org.smartregister.chw.kvp.util.Constants; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.util.KvpVisitUtils; +import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.family.util.Utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import timber.log.Timber; + +public class KvpPrEPProfileActivity extends CoreKvpProfileActivity { + public static void startProfileActivity(Activity activity, String baseEntityId) { + Intent intent = new Intent(activity, KvpPrEPProfileActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.PROFILE_TYPE, Constants.PROFILE_TYPES.KVP_PrEP_PROFILE); + activity.startActivity(intent); + } + + @Override + public void openFollowupVisit() { + KvpPrEPVisitActivity.startKvpPrEPVisitActivity(this, memberObject.getBaseEntityId(), false); + } + + @Override + protected void onResumption() { + super.onResumption(); + setupViews(); + } + + @Override + protected boolean showReferralView() { + return true; + } + + @Override + public void startReferralForm() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + List referralTypeModels = new ArrayList<>(); + if (memberObject.getGender().equalsIgnoreCase("male")) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.kvp_friendly_services), + CoreConstants.JSON_FORM.getMaleKvpFriendlyServicesReferralForm(), CoreConstants.TASKS_FOCUS.KVP_FRIENDLY_SERVICES)); + } else { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.kvp_friendly_services), + CoreConstants.JSON_FORM.getFemaleKvpFriendlyServicesReferralForm(), CoreConstants.TASKS_FOCUS.KVP_FRIENDLY_SERVICES)); + } + referralTypeModels.addAll(getCommonReferralTypes(this, memberObject.getBaseEntityId())); + + launchClientReferralActivity(this, referralTypeModels, memberObject.getBaseEntityId()); + } else { + Toast.makeText(this, "Refer to facility", Toast.LENGTH_SHORT).show(); + } + } + + @Override + protected void setupViews() { + try { + KvpVisitUtils.processVisits(this); + } catch (Exception e) { + Timber.e(e); + } + super.setupViews(); + textViewId.setVisibility(View.GONE); + } + + + @Override + public void refreshMedicalHistory(boolean hasHistory) { + Visit lastVisit = getVisit(org.smartregister.chw.util.Constants.Events.KVP_PREP_FOLLOWUP_VISIT); + if (lastVisit != null) { + rlLastVisit.setVisibility(View.VISIBLE); + findViewById(R.id.view_notification_and_referral_row).setVisibility(View.VISIBLE); + ((TextView) findViewById(R.id.vViewHistory)).setText(R.string.visits_history_profile_title); + ((TextView) findViewById(R.id.ivViewHistoryArrow)).setText(getString(R.string.view_visits_history)); + } else { + rlLastVisit.setVisibility(View.GONE); + } + } + + @Override + public void openMedicalHistory() { + KvpPrEPMedicalHistoryActivity.startMe(this, memberObject); + } + + private Visit getVisit(String eventType) { + return KvpLibrary.getInstance().visitRepository().getLatestVisit(memberObject.getBaseEntityId(), eventType); + } + + @Override + protected void showKvpGroups(String baseEntityId) { + if (!profileType.equalsIgnoreCase(Constants.PROFILE_TYPES.PrEP_PROFILE)) { + String dominantKVPGroup = ChwKvpDao.getDominantKVPGroup(baseEntityId); + if (StringUtils.isNotBlank(dominantKVPGroup)) { + textViewDominantKvpGroup.setVisibility(View.VISIBLE); + List dominantKvpGroup = new ArrayList<>(Arrays.asList(dominantKVPGroup)); + textViewDominantKvpGroup.setText(getString(org.smartregister.kvp.R.string.dominant_kvp_group, readStringResourcesWithPrefix(dominantKvpGroup, "kvp_"))); + } else { + textViewDominantKvpGroup.setVisibility(View.GONE); + } + textViewOtherKvpGroups.setVisibility(View.GONE); + } else { + textViewDominantKvpGroup.setVisibility(View.GONE); + textViewOtherKvpGroups.setVisibility(View.GONE); + } + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + int age = memberObject.getAge(); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(memberObject.getBaseEntityId()) && age >= 15); + } + + return true; + } + + @Override + public void startHivstRegistration() { + CommonRepository commonRepository = Utils.context().commonrepository(Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(memberObject.getBaseEntityId()); + final CommonPersonObjectClient client = + new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + String gender = Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + HivstRegisterActivity.startHivstRegistrationActivity(this, memberObject.getBaseEntityId(), gender); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPRegisterActivity.java new file mode 100644 index 0000000000..46da983a5a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPRegisterActivity.java @@ -0,0 +1,28 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + + +import org.smartregister.chw.core.activity.CoreKvpRegisterActivity; +import org.smartregister.chw.fragment.KvpPrEPRegisterFragment; +import org.smartregister.chw.kvp.util.Constants; +import org.smartregister.view.fragment.BaseRegisterFragment; + +public class KvpPrEPRegisterActivity extends CoreKvpRegisterActivity { + public static void startRegistration(Activity activity, String memberBaseEntityID, String gender, int age) { + Intent intent = new Intent(activity, KvpPrEPRegisterActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, memberBaseEntityID); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.ACTION, Constants.ACTIVITY_PAYLOAD_TYPE.REGISTRATION); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.KVP_FORM_NAME, Constants.FORMS.KVP_PrEP_REGISTRATION); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.GENDER, gender); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.AGE, age); + + activity.startActivity(intent); + } + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new KvpPrEPRegisterFragment(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPVisitActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPVisitActivity.java new file mode 100644 index 0000000000..3ebb94ded9 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/KvpPrEPVisitActivity.java @@ -0,0 +1,65 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; + +import com.vijay.jsonwizard.constants.JsonFormConstants; +import com.vijay.jsonwizard.domain.Form; + +import org.json.JSONObject; +import org.smartregister.chw.core.task.RunnableTask; +import org.smartregister.chw.interactor.KvpPrEPVisitInteractor; +import org.smartregister.chw.kvp.activity.BaseKvpVisitActivity; +import org.smartregister.chw.kvp.presenter.BaseKvpVisitPresenter; +import org.smartregister.chw.kvp.util.Constants; +import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.family.util.Utils; +import org.smartregister.util.LangUtils; + +import java.util.Date; + +public class KvpPrEPVisitActivity extends BaseKvpVisitActivity { + + public static void startKvpPrEPVisitActivity(Activity activity, String baseEntityId, Boolean editMode) { + Intent intent = new Intent(activity, KvpPrEPVisitActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.EDIT_MODE, editMode); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.PROFILE_TYPE, Constants.PROFILE_TYPES.KVP_PrEP_PROFILE); + activity.startActivity(intent); + } + + @Override + protected void registerPresenter() { + presenter = new BaseKvpVisitPresenter(memberObject, this, new KvpPrEPVisitInteractor()); + } + + @Override + public void startFormActivity(JSONObject jsonForm) { + Form form = new Form(); + form.setActionBarBackground(org.smartregister.chw.core.R.color.family_actionbar); + form.setWizard(false); + + Intent intent = new Intent(this, Utils.metadata().familyMemberFormActivity); + intent.putExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON, jsonForm.toString()); + intent.putExtra(org.smartregister.family.util.Constants.WizardFormActivity.EnableOnCloseDialog, false); + intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); + startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } + + + @Override + public void submittedAndClose() { + Runnable runnable = () -> ChwScheduleTaskExecutor.getInstance().execute(memberObject.getBaseEntityId(), Constants.EVENT_TYPE.KVP_PrEP_FOLLOW_UP_VISIT, new Date()); + Utils.startAsyncTask(new RunnableTask(runnable), null); + super.submittedAndClose(); + } + + @Override + protected void attachBaseContext(Context base) { + // get language from prefs + String lang = LangUtils.getLanguage(base.getApplicationContext()); + super.attachBaseContext(LangUtils.setAppLocale(base, lang)); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURecordFeedbackActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURecordFeedbackActivity.java new file mode 100644 index 0000000000..634f38f068 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURecordFeedbackActivity.java @@ -0,0 +1,52 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import org.jetbrains.annotations.Nullable; +import org.json.JSONObject; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.presenter.LTFURecordFeedbackPresenter; +import org.smartregister.chw.referral.activity.BaseIssueReferralActivity; +import org.smartregister.chw.referral.contract.BaseIssueReferralContract; +import org.smartregister.chw.referral.interactor.BaseIssueReferralInteractor; +import org.smartregister.chw.referral.model.BaseIssueReferralModel; +import org.smartregister.chw.referral.presenter.BaseIssueReferralPresenter; +import org.smartregister.chw.referral.util.Constants; +import org.smartregister.chw.util.JsonFormUtils; + +import androidx.annotation.NonNull; + +public class LTFURecordFeedbackActivity extends BaseIssueReferralActivity { + + private static String BASE_ENTITY_ID; + private static String referralHf; + private static String taskId; + + public static void startFeedbackFormActivityForResults(Activity activity, String baseEntityId, JSONObject formJsonObject, boolean useCustomLayout, String locationId, String task_id) { + BASE_ENTITY_ID = baseEntityId; + referralHf = locationId; + taskId = task_id; + Intent intent = new Intent(activity, LTFURecordFeedbackActivity.class); + intent.putExtra(Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityId); + intent.putExtra(Constants.ActivityPayload.JSON_FORM, formJsonObject.toString()); + intent.putExtra(Constants.ActivityPayload.ACTION, Constants.ActivityPayloadType.REGISTRATION); + intent.putExtra(Constants.ActivityPayload.USE_CUSTOM_LAYOUT, useCustomLayout); + activity.startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + NavigationMenu.getInstance(this, null, null); + } + + + @NonNull + @Override + public BaseIssueReferralPresenter presenter() { + return new LTFURecordFeedbackPresenter(BASE_ENTITY_ID, taskId, referralHf, (BaseIssueReferralContract.View) this, + BaseIssueReferralModel.class, (BaseIssueReferralContract.Interactor) new BaseIssueReferralInteractor()); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFUReferralsDetailsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFUReferralsDetailsViewActivity.java new file mode 100644 index 0000000000..eaa5dc6981 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFUReferralsDetailsViewActivity.java @@ -0,0 +1,162 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.LinearLayout; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.core.activity.BaseReferralTaskViewActivity; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.chw.dao.ReferralDao; +import org.smartregister.chw.util.Constants; +import org.smartregister.chw.util.JsonFormUtils; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.domain.Location; +import org.smartregister.domain.Task; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.LocationRepository; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.sql.Date; + +import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; + +public class LTFUReferralsDetailsViewActivity extends BaseReferralTaskViewActivity implements View.OnClickListener { + + private static CommonPersonObjectClient commonPersonObjectClient; + private static String baseEntityId; + private static String locationId; + private static String taskId; + + public static void startLTFUReferralsDetailsViewActivity(Activity activity, CommonPersonObjectClient personObjectClient, Task task, String startingActivity) { + LTFUReferralsDetailsViewActivity.personObjectClient = personObjectClient; + Intent intent = new Intent(activity, LTFUReferralsDetailsViewActivity.class); + intent.putExtra(CoreConstants.INTENT_KEY.USERS_TASKS, task); + intent.putExtra(CoreConstants.INTENT_KEY.CHILD_COMMON_PERSON, personObjectClient); + intent.putExtra(CoreConstants.INTENT_KEY.STARTING_ACTIVITY, startingActivity); + commonPersonObjectClient = personObjectClient; + baseEntityId = Utils.getValue(personObjectClient.getColumnmaps(), CoreConstants.DB_CONSTANTS.BASE_ENTITY_ID, false); + locationId = Utils.getValue(commonPersonObjectClient.getColumnmaps(), org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_HF, false); + taskId = task.getIdentifier(); + passToolbarTitle(activity, intent); + activity.startActivity(intent); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.referrals_tasks_view_layout); + if (getIntent().getExtras() != null) { + extraClientTask(); + extraDetails(); + setStartingActivity((String) getIntent().getSerializableExtra(CoreConstants.INTENT_KEY.STARTING_ACTIVITY)); + inflateToolbar(); + setUpViews(); + } + } + + @Override + protected void onCreation() { + //overridden + } + + @Override + protected void onResumption() { + //Overridden + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode == Activity.RESULT_OK && requestCode == JsonFormUtils.REQUEST_CODE_GET_JSON) { + finish(); + } + } + + public void setUpViews() { + clientName = findViewById(R.id.client_name); + careGiverName = findViewById(R.id.care_giver_name); + childName = findViewById(R.id.child_name); + careGiverPhone = findViewById(R.id.care_giver_phone); + clientReferralProblem = findViewById(R.id.client_referral_problem); + chwDetailsNames = findViewById(R.id.chw_details_names); + referralDate = findViewById(R.id.referral_date); + + womanGaLayout = findViewById(R.id.woman_ga_layout); + careGiverLayout = findViewById(R.id.care_giver_name_layout); + childNameLayout = findViewById(R.id.child_name_layout); + + womanGa = findViewById(R.id.woman_ga); + + CustomFontTextView recordFeedbackBtn = findViewById(R.id.record_feedback); + recordFeedbackBtn.setOnClickListener(this); + + LinearLayout lastAppointmentLayout = findViewById(R.id.last_visit_date_layout); + CustomFontTextView tvLastAppointmentDate = findViewById(R.id.last_visit_date); + + getReferralDetails(); + LocationRepository locationRepository = new LocationRepository(); + String reasonReference = Utils.getValue(commonPersonObjectClient.getColumnmaps(), "reason_reference", false); + Location location = locationRepository.getLocationById(locationId); + if(location!= null){ + chwDetailsNames.setText(location.getProperties().getName()); + }else{ + chwDetailsNames.setText(locationId); + } + Date lastAppointmentDate = ReferralDao.getLastAppointmentDate(reasonReference); + if (lastAppointmentDate != null) { + lastAppointmentLayout.setVisibility(View.VISIBLE); + tvLastAppointmentDate.setText(org.smartregister.chw.core.utils.Utils.dd_MMM_yyyy.format(lastAppointmentDate)); + } + } + + public void setStartingActivity(String startingActivity) { + this.startingActivity = startingActivity; + } + + @Override + protected void updateProblemDisplay() { + clientReferralProblem.setText(getReferralClinic(Utils.getValue(commonPersonObjectClient.getColumnmaps(), "REFERRAL_CLINIC", false),this)); + } + + private String getReferralClinic(String key, Context context){ + switch (key.toLowerCase()){ + case "ctc": + return context.getString(R.string.ltfu_clinic_ctc); + case "pwid": + return context.getString(R.string.ltfu_clinic_pwid); + case "prep": + return context.getString(R.string.ltfu_clinic_prep); + case "pmtct": + return context.getString(R.string.ltfu_clinic_pmtct); + case "tb": + return context.getString(R.string.ltfu_clinic_tb); + default: + return key.toUpperCase(); + } + } + + public String getBaseEntityId() { + return baseEntityId; + } + + @Override + public void onClick(View v) { + if (v.getId() == R.id.record_feedback) { + JSONObject formJSONObject = FormUtils.getFormUtils().getFormJson("ltfu_community_followup_feedback"); + try { + formJSONObject.put(Constants.REFERRAL_TASK_FOCUS, "LTFU Community Followup Feedback"); + } catch (JSONException e) { + e.printStackTrace(); + } + LTFURecordFeedbackActivity.startFeedbackFormActivityForResults(this, baseEntityId, formJSONObject, false, locationId, taskId); + } + + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURegisterActivity.java new file mode 100644 index 0000000000..2cfc74e514 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LTFURegisterActivity.java @@ -0,0 +1,28 @@ +package org.smartregister.chw.activity; + +import org.smartregister.chw.core.activity.BaseReferralRegister; +import org.smartregister.chw.core.presenter.BaseReferralPresenter; +import org.smartregister.chw.fragment.LTFUReferralsRegisterFragment; +import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.view.fragment.BaseRegisterFragment; + +public class LTFURegisterActivity extends BaseReferralRegister { + @Override + protected void initializePresenter() { + presenter = new BaseReferralPresenter(); + } + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new LTFUReferralsRegisterFragment(); + } + + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + FamilyRegisterActivity.registerBottomNavigation(bottomNavigationHelper, bottomNavigationView, this); + bottomNavigationView.getMenu().removeItem(org.smartregister.family.R.id.action_register); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/LoginActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LoginActivity.java index 5a00917ac7..85d7092284 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/LoginActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/LoginActivity.java @@ -5,7 +5,11 @@ import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; +import android.widget.ImageView; +import androidx.core.content.ContextCompat; + +import org.smartregister.chw.BuildConfig; import org.smartregister.chw.R; import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.fragment.ChooseLoginMethodFragment; @@ -21,9 +25,8 @@ import org.smartregister.view.activity.BaseLoginActivity; import org.smartregister.view.contract.BaseLoginContract; - public class LoginActivity extends BaseLoginActivity implements BaseLoginContract.View { - public static final String TAG = BaseLoginActivity.class.getCanonicalName(); + private static final String WFH_CSV_PARSED = "WEIGHT_FOR_HEIGHT_CSV_PARSED"; private PinLogger pinLogger = PinLoginUtil.getPinLogger(); @@ -31,6 +34,12 @@ public class LoginActivity extends BaseLoginActivity implements BaseLoginContrac @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + ImageView imageView = findViewById(R.id.login_logo); + if (BuildConfig.BUILD_FOR_BORESHA_AFYA_SOUTH) { + imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_logo)); + } else { + imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_logo_ba)); + } } @Override @@ -62,7 +71,7 @@ private void pinLoginAttempt() { } } - private boolean hasPinLogin(){ + private boolean hasPinLogin() { return ChwApplication.getApplicationFlavor().hasPinLogin(); } @@ -104,7 +113,7 @@ public void goToHome(boolean remote) { if (hasPinLogin()) { startPinHome(remote); - }else{ + } else { startHome(remote); } @@ -112,8 +121,14 @@ public void goToHome(boolean remote) { } private void startHome(boolean remote) { - Intent intent = new Intent(this, ChwApplication.getApplicationFlavor().launchChildClientsAtLogin() ? - ChildRegisterActivity.class : FamilyRegisterActivity.class); + Intent intent; + if (BuildConfig.BUILD_FOR_BORESHA_AFYA_SOUTH) { + intent = new Intent(this, ChwApplication.getApplicationFlavor().launchChildClientsAtLogin() ? + ChildRegisterActivity.class : AllClientsRegisterActivity.class); + } else { + intent = new Intent(this, ChwApplication.getApplicationFlavor().launchChildClientsAtLogin() ? + ChildRegisterActivity.class : FamilyRegisterActivity.class); + } intent.putExtra(Constants.INTENT_KEY.IS_REMOTE_LOGIN, remote); startActivity(intent); } @@ -147,5 +162,4 @@ private void processWeightForHeightZscoreCSV() { allSharedPreferences.savePreference(WFH_CSV_PARSED, "true"); } } - } \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MalariaProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MalariaProfileActivity.java index 2d1c3cb205..e3ea19811f 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MalariaProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MalariaProfileActivity.java @@ -168,7 +168,7 @@ public void referToFacility() { if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { JSONObject formJson = getFormUtils().getFormJson(Constants.JSON_FORM.getMalariaReferralForm()); formJson.put(Constants.REFERRAL_TASK_FOCUS, referralTypeModels.get(0).getFocus()); - ReferralRegistrationActivity.startGeneralReferralFormActivityForResults(this, baseEntityId, formJson, true); + ReferralRegistrationActivity.startGeneralReferralFormActivityForResults(this, baseEntityId, formJson, false); } else { startFormActivity(getFormUtils().getFormJson(getReferralTypeModels().get(0).getFormName())); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivity.java new file mode 100644 index 0000000000..95d855f74b --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivity.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.view.View; +import android.widget.ProgressBar; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.presenter.BaseAncMedicalHistoryPresenter; +import org.smartregister.chw.core.activity.CoreAncMedicalHistoryActivity; +import org.smartregister.chw.interactor.MotherChampionMedicalHistoryInteractor; +import org.smartregister.chw.pmtct.domain.MemberObject; + +import java.util.List; + +public class MotherChampionMedicalHistoryActivity extends CoreAncMedicalHistoryActivity { + private static MemberObject heiMemberObject; + private final Flavor flavor = new MotherChampionMedicalHistoryActivityFlv(); + private ProgressBar progressBar; + + public static void startMe(Activity activity, MemberObject memberObject) { + Intent intent = new Intent(activity, MotherChampionMedicalHistoryActivity.class); + heiMemberObject = memberObject; + activity.startActivity(intent); + } + + @Override + public void initializePresenter() { + presenter = new BaseAncMedicalHistoryPresenter(new MotherChampionMedicalHistoryInteractor(), this, heiMemberObject.getBaseEntityId()); + } + + @Override + public void setUpView() { + linearLayout = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.linearLayoutMedicalHistory); + progressBar = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.progressBarMedicalHistory); + + TextView tvTitle = findViewById(org.smartregister.chw.opensrp_chw_anc.R.id.tvTitle); + tvTitle.setText(getString(org.smartregister.chw.opensrp_chw_anc.R.string.back_to, heiMemberObject.getFullName())); + + ((TextView) findViewById(R.id.medical_history)).setText(getString(R.string.visits_history)); + } + + @Override + public View renderView(List visits) { + super.renderView(visits); + View view = flavor.bindViews(this); + displayLoadingState(true); + flavor.processViewData(visits, this); + displayLoadingState(false); + TextView heiVisitTitle = view.findViewById(org.smartregister.chw.core.R.id.customFontTextViewHealthFacilityVisitTitle); + heiVisitTitle.setText(R.string.mother_champion_visit); + return view; + } + + @Override + public void displayLoadingState(boolean state) { + progressBar.setVisibility(state ? View.VISIBLE : View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivityFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivityFlv.java new file mode 100644 index 0000000000..73d1589f75 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionMedicalHistoryActivityFlv.java @@ -0,0 +1,174 @@ +package org.smartregister.chw.activity; + +import android.content.Context; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.BulletSpan; +import android.text.style.StyleSpan; +import android.view.View; +import android.widget.TextView; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.core.activity.DefaultAncMedicalHistoryActivityFlv; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import timber.log.Timber; + +public class MotherChampionMedicalHistoryActivityFlv extends DefaultAncMedicalHistoryActivityFlv { + private final StyleSpan boldSpan = new StyleSpan(android.graphics.Typeface.BOLD); + + @Override + protected void processAncCard(String has_card, Context context) { + // super.processAncCard(has_card, context); + linearLayoutAncCard.setVisibility(View.GONE); + } + + @Override + protected void processHealthFacilityVisit(List> hf_visits, Context context) { + //super.processHealthFacilityVisit(hf_visits, context); + } + + @Override + public void processViewData(List visits, Context context) { + + if (visits.size() > 0) { + int days = 0; + List> hf_visits = new ArrayList<>(); + + int x = 0; + while (x < visits.size()) { + + // the first object in this list is the days difference + if (x == 0) { + days = Days.daysBetween(new DateTime(visits.get(visits.size() - 1).getDate()), new DateTime()).getDays(); + } + + + String[] visitParams = {"followup_visit_date", "type_of_service", "linked_to_psychosocial_group", "counselling_given", "referrals_issued_other_services"}; + extractVisitDetails(visits, visitParams, hf_visits, x, context); + + x++; + } + + processLastVisit(days, context); + processVisit(hf_visits, context); + } + } + + private void extractVisitDetails(List sourceVisits, String[] hf_params, List> hf_visits, int iteration, Context context) { + // get the hf details + Map map = new HashMap<>(); + for (String param : hf_params) { + try { + List details = sourceVisits.get(iteration).getVisitDetails().get(param); + map.put(param, getTexts(context, details)); + } catch (Exception e) { + e.printStackTrace(); + } + + } + hf_visits.add(map); + } + + + private void processLastVisit(int days, Context context) { + linearLayoutLastVisit.setVisibility(View.VISIBLE); + if (days < 1) { + customFontTextViewLastVisit.setText(org.smartregister.chw.core.R.string.less_than_twenty_four); + } else { + customFontTextViewLastVisit.setText(StringUtils.capitalize(MessageFormat.format(context.getString(org.smartregister.chw.core.R.string.days_ago), String.valueOf(days)))); + } + } + + + protected void processVisit(List> hf_visits, Context context) { + if (hf_visits != null && hf_visits.size() > 0) { + linearLayoutHealthFacilityVisit.setVisibility(View.VISIBLE); + + int x = 0; + for (Map vals : hf_visits) { + View view = inflater.inflate(R.layout.medical_history_mother_champion_visit, null); + TextView tvTitle = view.findViewById(R.id.title); + TextView tvTypeOfService = view.findViewById(R.id.type_of_service); + TextView tvLinkedToPsychosocialGroup = view.findViewById(R.id.linked_to_psychosocial_group); + TextView counsellingGiven = view.findViewById(R.id.counselling_given); + TextView referralsIssuedToOtherServices = view.findViewById(R.id.referrals_issued_other_services); + evaluateTitle(context, x, vals, tvTitle); + + evaluateView(context, vals, tvTypeOfService, "type_of_service", R.string.mother_champion_type_of_service, "mother_champion_"); + evaluateView(context, vals, tvLinkedToPsychosocialGroup, "linked_to_psychosocial_group", R.string.mother_champion_linked_to_psychosocial_group, ""); + evaluateView(context, vals, counsellingGiven, "counselling_given", R.string.mother_champion_counselling_given, "mother_champion_counselling_"); + evaluateView(context, vals, referralsIssuedToOtherServices, "referrals_issued_other_services", R.string.mother_champion_referrals_issued_other_services, "mother_champion_referrals_issued_other_services_"); + + linearLayoutHealthFacilityVisitDetails.addView(view, 0); + + x++; + } + } + } + + + private void evaluateTitle(Context context, int x, Map vals, TextView tvTitle) { + String visitDate = vals.get("followup_visit_date"); + if (StringUtils.isBlank(visitDate)) { + tvTitle.setVisibility(View.GONE); + } else { + try { + tvTitle.setText(MessageFormat.format(context.getString(R.string.mother_champion_visit_title), x + 1, visitDate)); + } catch (Exception e) { + Timber.e(e); + } + } + } + + private void evaluateView(Context context, Map vals, TextView tv, String valueKey, int viewTitleStringResource, String valuePrefixInStringResources) { + if (StringUtils.isNotBlank(getMapValue(vals, valueKey))) { + SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); + spannableStringBuilder.append(context.getString(viewTitleStringResource), boldSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE).append("\n"); + + String stringValue = getMapValue(vals, valueKey); + String[] stringValueArray; + if (stringValue.contains(",")) { + stringValueArray = stringValue.split(","); + for (String value : stringValueArray) { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, value.trim()) + "\n", new BulletSpan(10), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } else { + spannableStringBuilder.append(getStringResource(context, valuePrefixInStringResources, stringValue)).append("\n"); + } + tv.setText(spannableStringBuilder); + } else { + tv.setVisibility(View.GONE); + } + } + + + private String getMapValue(Map map, String key) { + if (map.containsKey(key)) { + return map.get(key); + } + return ""; + } + + private String getStringResource(Context context, String prefix, String resourceName) { + int resourceId = context.getResources(). + getIdentifier(prefix + resourceName.trim(), "string", context.getPackageName()); + try { + return context.getString(resourceId); + } catch (Exception e) { + Timber.e(e); + return prefix + resourceName; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionProfileActivity.java new file mode 100644 index 0000000000..647eb0d301 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionProfileActivity.java @@ -0,0 +1,324 @@ +package org.smartregister.chw.activity; + +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.util.JsonFormUtils.STEP1; +import static org.smartregister.util.JsonFormUtils.VALUE; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Intent; +import android.view.Gravity; +import android.view.Menu; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; + +import com.vijay.jsonwizard.constants.JsonFormConstants; +import com.vijay.jsonwizard.domain.Form; +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreFamilyProfileActivity; +import org.smartregister.chw.core.activity.CorePmtctProfileActivity; +import org.smartregister.chw.core.interactor.CorePmtctProfileInteractor; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.model.CoreAllClientsMemberModel; +import org.smartregister.chw.core.presenter.CoreFamilyOtherMemberActivityPresenter; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.custom_view.MotherChampionFloatingMenu; +import org.smartregister.chw.dao.MotherChampionDao; +import org.smartregister.chw.model.FamilyProfileModel; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.pmtct.PmtctLibrary; +import org.smartregister.chw.pmtct.domain.Visit; +import org.smartregister.chw.pmtct.util.Constants; +import org.smartregister.chw.pmtct.util.NCUtils; +import org.smartregister.chw.presenter.PmtctMemberProfilePresenter; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.domain.AlertStatus; +import org.smartregister.family.domain.FamilyEventClient; +import org.smartregister.family.interactor.FamilyProfileInteractor; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.AllSharedPreferences; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Nullable; + +import timber.log.Timber; + +public class MotherChampionProfileActivity extends CorePmtctProfileActivity { + private static String baseEntityId; + private List referralTypeModels = new ArrayList<>(); + + public static void startProfile(Activity activity, String baseEntityId) { + MotherChampionProfileActivity.baseEntityId = baseEntityId; + Intent intent = new Intent(activity, MotherChampionProfileActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + activity.startActivity(intent); + } + + @Override + protected void initializePresenter() { + showProgressBar(true); + String baseEntityId = getIntent().getStringExtra(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID); + memberObject = MotherChampionDao.getMember(baseEntityId); + profilePresenter = new PmtctMemberProfilePresenter(this, new CorePmtctProfileInteractor(), memberObject); + fetchProfileData(); + profilePresenter.refreshProfileBottom(); + } + + @Override + public void onClick(View view) { + super.onClick(view); + int id = view.getId(); + if (id == R.id.textview_record_pmtct) { + JSONObject formJsonObject = null; + try { + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, org.smartregister.chw.util.Constants.JsonForm.getMotherChampionFollowupForm()); + AllSharedPreferences preferences = ChwApplication.getInstance().getContext().allSharedPreferences(); + JSONObject chwName = getFieldJSONObject(fields(formJsonObject, STEP1), "chw_name"); + chwName.put(VALUE, preferences.getANMPreferredName(preferences.fetchRegisteredANM())); + + JSONObject visitNumber = getFieldJSONObject(fields(formJsonObject, STEP1), "visit_number"); + visitNumber.put(VALUE, MotherChampionDao.getVisitNumber(memberObject.getBaseEntityId())); + + } catch (JSONException e) { + e.printStackTrace(); + } + startFormActivity(formJsonObject); + } + } + + @Override + protected void onCreation() { + super.onCreation(); + addPmtctReferralTypes(); + } + + @Override + public void startFormActivity(JSONObject jsonForm) { + try { + + Intent intent = new Intent(this, Utils.metadata().familyMemberFormActivity); + intent.putExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON, jsonForm.toString()); + + Form form = new Form(); + form.setActionBarBackground(org.smartregister.chw.core.R.color.family_actionbar); + form.setWizard(false); + intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); + + if (jsonForm.getString("encounter_type").equals(org.smartregister.chw.util.Constants.EncounterType.MOTHER_CHAMPION_FOLLOWUP)) { + form.setWizard(true); + form.setNavigationBackground(org.smartregister.chw.core.R.color.family_navigation); + form.setName(getString(R.string.record_followup_visit_mother_champion)); + form.setNextLabel(this.getResources().getString(org.smartregister.chw.core.R.string.next)); + form.setPreviousLabel(this.getResources().getString(org.smartregister.chw.core.R.string.back)); + } + + startActivityForResult(intent, org.smartregister.family.util.JsonFormUtils.REQUEST_CODE_GET_JSON); + } catch (JSONException e) { + Timber.e(e); + } + } + + @Override + protected void setupViews() { + super.setupViews(); + TextView toolbarTitle = findViewById(R.id.toolbar_title); + toolbarTitle.setText(R.string.return_to_mother_champion_clients); + + textViewRecordPmtct.setText(R.string.record_mother_champion_follouwp_visit); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + menu.findItem(R.id.action_remove_member).setVisible(false); + menu.findItem(R.id.action_issue_pmtct_followup_referral).setVisible(false); + return true; + } + + @SuppressLint("MissingSuperCall") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == Constants.REQUEST_CODE_GET_JSON && resultCode == RESULT_OK) { + try { + String jsonString = data.getStringExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON); + JSONObject form = new JSONObject(jsonString); + String encounterType = form.getString(JsonFormUtils.ENCOUNTER_TYPE); + if (encounterType.equals(org.smartregister.chw.util.Constants.EncounterType.MOTHER_CHAMPION_FOLLOWUP)) { + AllSharedPreferences allSharedPreferences = org.smartregister.util.Utils.getAllSharedPreferences(); + Event baseEvent = org.smartregister.chw.pmtct.util.JsonFormUtils.processJsonForm(allSharedPreferences, jsonString, org.smartregister.chw.util.Constants.TableName.MOTHER_CHAMPION_FOLLOWUP); + org.smartregister.chw.pmtct.util.JsonFormUtils.tagEvent(allSharedPreferences, baseEvent); + baseEvent.setBaseEntityId(baseEntityId); + try { + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.pmtct.util.JsonFormUtils.gson.toJson(baseEvent))); + } catch (Exception e) { + Timber.e(e); + } + } + if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyMemberRegister.updateEventType)) { + FamilyEventClient familyEventClient = + new FamilyProfileModel(memberObject.getFamilyName()).processUpdateMemberRegistration(jsonString, memberObject.getBaseEntityId()); + new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, presenter()); + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyRegister.updateEventType)) { + FamilyEventClient familyEventClient = new CoreAllClientsMemberModel().processJsonForm(jsonString, memberObject.getFamilyBaseEntityId()); + familyEventClient.getEvent().setEntityType(CoreConstants.TABLE_NAME.INDEPENDENT_CLIENT); + new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, presenter()); + } + } catch (Exception e) { + Timber.e(e, "MotherChampionProfileActivity -- > onActivityResult"); + } + } + } + + @Override + public void refreshFamilyStatus(AlertStatus status) { + super.refreshFamilyStatus(status); + rlFamilyServicesDue.setVisibility(View.GONE); + } + + @Override + protected Class getFamilyProfileActivityClass() { + return null; + } + + @Override + protected void removeMember() { + //implement + } + + @NonNull + @Override + public CoreFamilyOtherMemberActivityPresenter presenter() { + return null; + } + + @Override + public void setProfileImage(String s, String s1) { + //implement + } + + @Override + public void setProfileDetailThree(String s) { + //implement + } + + @Override + public void toggleFamilyHead(boolean b) { + //implement + } + + @Override + public void togglePrimaryCaregiver(boolean b) { + //implement + } + + @Override + public void refreshList() { + //implement + } + + @Override + public void updateHasPhone(boolean b) { + //implement + } + + @Override + public void setFamilyServiceStatus(String s) { + //implement + } + + @Override + public void verifyHasPhone() { + //implement + } + + @Override + public void notifyHasPhone(boolean b) { + //implement + } + + @Override + public void initializeFloatingMenu() { + basePmtctFloatingMenu = new MotherChampionFloatingMenu(this, memberObject); + + OnClickFloatingMenu onClickFloatingMenu = viewId -> { + switch (viewId) { + case R.id.anc_fab: + ((MotherChampionFloatingMenu) basePmtctFloatingMenu).animateFAB(); + break; + case R.id.call_layout: + ((MotherChampionFloatingMenu) basePmtctFloatingMenu).launchCallWidget(); + ((MotherChampionFloatingMenu) basePmtctFloatingMenu).animateFAB(); + break; + case R.id.refer_to_facility_layout: + ((PmtctMemberProfilePresenter) profilePresenter).referToFacility(); + ((MotherChampionFloatingMenu) basePmtctFloatingMenu).animateFAB(); + break; + default: + Timber.d("Unknown fab action"); + break; + } + + }; + + ((MotherChampionFloatingMenu) basePmtctFloatingMenu).setFloatMenuClickListener(onClickFloatingMenu); + basePmtctFloatingMenu.setGravity(Gravity.BOTTOM | Gravity.END); + LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + addContentView(basePmtctFloatingMenu, linearLayoutParams); + } + + @Override + public void refreshMedicalHistory(boolean hasHistory) { + Visit lastFollowupVisit = getVisit(org.smartregister.chw.util.Constants.Events.MOTHER_CHAMPION_FOLLOWUP); + if (lastFollowupVisit != null) { + rlLastVisit.setVisibility(View.VISIBLE); + findViewById(R.id.view_notification_and_referral_row).setVisibility(View.VISIBLE); + ((TextView) findViewById(R.id.vViewHistory)).setText(R.string.visits_history_profile_title); + ((TextView) findViewById(R.id.ivViewHistoryArrow)).setText(getString(R.string.view_visits_history)); + } else { + rlLastVisit.setVisibility(View.GONE); + } + } + + private void addPmtctReferralTypes() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.pmtct_referral), + CoreConstants.JSON_FORM.getPmtctReferralForm(), CoreConstants.TASKS_FOCUS.PMTCT)); + + } + + } + + public List getReferralTypeModels() { + return referralTypeModels; + } + + @Override + public void openMedicalHistory() { + MotherChampionMedicalHistoryActivity.startMe(this, memberObject); + } + + public @Nullable + Visit getVisit(String eventType) { + return PmtctLibrary.getInstance().visitRepository().getLatestVisit(memberObject.getBaseEntityId(), eventType); + } + + @Override + protected void onResume() { + super.onResume(); + refreshMedicalHistory(true); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionRegisterActivity.java new file mode 100644 index 0000000000..fd5e1955da --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionRegisterActivity.java @@ -0,0 +1,92 @@ +package org.smartregister.chw.activity; + + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import com.google.android.material.bottomnavigation.LabelVisibilityMode; + +import org.smartregister.chw.R; +import org.smartregister.chw.core.activity.CorePmtctRegisterActivity; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.fragment.AncPartnerFollowupRegisterFragment; +import org.smartregister.chw.fragment.MotherChampionRegisterFragment; +import org.smartregister.chw.fragment.PmtctFollowupRegisterFragment; +import org.smartregister.chw.fragment.SbccRegisterFragment; +import org.smartregister.chw.listener.ChwMotherChampionBottomNavigationListener; +import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.listener.BottomNavigationListener; +import org.smartregister.view.fragment.BaseRegisterFragment; + +import androidx.fragment.app.Fragment; + +public class MotherChampionRegisterActivity extends CorePmtctRegisterActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + NavigationMenu.getInstance(this, null, null); + } + + @Override + protected BaseRegisterFragment getRegisterFragment() { + return new MotherChampionRegisterFragment(); + } + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + + if (bottomNavigationView != null) { + bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.hiv.R.id.action_register); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); + + bottomNavigationView.inflateMenu(getMenuResource()); + bottomNavigationHelper.disableShiftMode(bottomNavigationView); + + BottomNavigationListener pmtctBottomNavigationListener = getBottomNavigation(this); + bottomNavigationView.setOnNavigationItemSelectedListener(pmtctBottomNavigationListener); + + } + } + + public BottomNavigationListener getBottomNavigation(Activity activity) { + return new ChwMotherChampionBottomNavigationListener(activity); + } + + @Override + protected Fragment[] getOtherFragments() { + return new Fragment[]{ + new AncPartnerFollowupRegisterFragment(), + new PmtctFollowupRegisterFragment(), + new SbccRegisterFragment() + }; + } + + + @Override + public int getMenuResource() { + return R.menu.pmtct_bottom_nav_menu; + } + + @Override + protected void onResumption() { + super.onResumption(); + NavigationMenu menu = NavigationMenu.getInstance(this, null, null); + if (menu != null) { + menu.getNavigationAdapter().setSelectedView(CoreConstants.DrawerMenu.MOTHER_CHAMPION); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + finish(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsActivity.java new file mode 100644 index 0000000000..d375ba6883 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsActivity.java @@ -0,0 +1,23 @@ +package org.smartregister.chw.activity; + +import android.view.View; +import android.widget.TextView; + +import org.smartregister.chw.R; + +public class MotherChampionReportsActivity extends CBHSReportsActivity { + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.cbhs_monthly_summary) { + MotherChampionReportsViewActivity.startMe(this, "mother-champion-report", reportPeriod); + } + } + + @Override + public void setUpToolbar() { + super.setUpToolbar(); + TextView title = findViewById(R.id.toolbar_title); + title.setText(R.string.mother_champion_reports); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsViewActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsViewActivity.java new file mode 100644 index 0000000000..a99b7f3f05 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/MotherChampionReportsViewActivity.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.smartregister.chw.R; +import org.smartregister.chw.util.Constants; + +public class MotherChampionReportsViewActivity extends ChwReportsViewActivity { + public static void startMe(Activity activity, String reportPath, String reportDate) { + Intent intent = new Intent(activity, MotherChampionReportsViewActivity.class); + intent.putExtra(ARG_REPORT_PATH, reportPath); + intent.putExtra(ARG_REPORT_DATE, reportDate); + intent.putExtra(ARG_REPORT_TITLE, R.string.mother_champion_reports); + intent.putExtra(ARG_REPORT_TYPE, Constants.ReportConstants.ReportTypes.MOTHER_CHAMPION_REPORT); + activity.startActivity(intent); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/OrderDetailsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/OrderDetailsActivity.java new file mode 100644 index 0000000000..52d8054930 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/OrderDetailsActivity.java @@ -0,0 +1,25 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.json.JSONObject; +import org.smartregister.chw.cdp.activity.BaseOrderDetailsActivity; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.family.util.JsonFormUtils; + +public class OrderDetailsActivity extends BaseOrderDetailsActivity { + + public static void startMe(Activity activity, CommonPersonObjectClient pc) { + Intent intent = new Intent(activity, OrderDetailsActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.CLIENT, pc); + activity.startActivity(intent); + } + + @Override + public void startFormActivity(JSONObject jsonForm) { + startActivityForResult(FormUtils.getStartFormActivity(jsonForm, null, this), JsonFormUtils.REQUEST_CODE_GET_JSON); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PartnerRegistrationActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PartnerRegistrationActivity.java new file mode 100644 index 0000000000..d2d5036f33 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PartnerRegistrationActivity.java @@ -0,0 +1,491 @@ +package org.smartregister.chw.activity; + +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.chw.anc.util.NCUtils.getClientProcessorForJava; +import static org.smartregister.chw.anc.util.NCUtils.getSyncHelper; +import static org.smartregister.chw.util.Constants.JsonForm.getPartnerRegistrationForm; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.EXISTING_PARTNER_REQUEST_CODE; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.FEEDBACK_FORM_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.INTENT_BASE_ENTITY_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.INTENT_FORM_SUBMISSION_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.REFERRAL_FORM_SUBMISSION_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.NEW_PARTNER_REQUEST_CODE; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.PARTNER_BASE_ENTITY_ID; +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.PARTNER_REGISTRATION_EVENT; +import static org.smartregister.chw.util.JsonFormUtils.METADATA; +import static org.smartregister.family.util.JsonFormUtils.STEP2; +import static org.smartregister.util.JsonFormUtils.ENCOUNTER_LOCATION; +import static org.smartregister.util.JsonFormUtils.STEP1; +import static org.smartregister.util.JsonFormUtils.generateRandomUUIDString; +import static org.smartregister.util.Utils.getAllSharedPreferences; + +import android.app.Activity; +import android.content.Intent; +import android.view.View; +import android.widget.ImageView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.constraintlayout.widget.ConstraintLayout; + +import com.vijay.jsonwizard.constants.JsonFormConstants; +import com.vijay.jsonwizard.domain.Form; +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.anc.util.NCUtils; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.referral.ReferralLibrary; +import org.smartregister.chw.referral.domain.ReferralTask; +import org.smartregister.chw.referral.util.DBConstants; +import org.smartregister.chw.referral.util.ReferralUtil; +import org.smartregister.chw.util.AllClientsUtils; +import org.smartregister.clientandeventmodel.Client; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.clientandeventmodel.Obs; +import org.smartregister.domain.Location; +import org.smartregister.domain.UniqueId; +import org.smartregister.family.util.Constants; +import org.smartregister.family.util.Utils; +import org.smartregister.opd.OpdLibrary; +import org.smartregister.opd.pojo.OpdEventClient; +import org.smartregister.opd.pojo.RegisterParams; +import org.smartregister.opd.utils.OpdConstants; +import org.smartregister.opd.utils.OpdJsonFormUtils; +import org.smartregister.opd.utils.OpdUtils; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.repository.EventClientRepository; +import org.smartregister.repository.LocationRepository; +import org.smartregister.repository.UniqueIdRepository; +import org.smartregister.util.JsonFormUtils; +import org.smartregister.view.activity.SecuredActivity; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import timber.log.Timber; + +public class PartnerRegistrationActivity extends SecuredActivity implements View.OnClickListener { + + private String clientBaseEntityId; + private String formSubmissionId; + private String referralFormSubmissionId; + + @Override + protected void onCreation() { + setContentView(R.layout.activity_partner_registration); + this.clientBaseEntityId = getIntent().getStringExtra(INTENT_BASE_ENTITY_ID); + this.formSubmissionId = getIntent().getStringExtra(INTENT_FORM_SUBMISSION_ID); + this.referralFormSubmissionId = getIntent().getStringExtra(REFERRAL_FORM_SUBMISSION_ID); + setupView(); + } + + + @Override + protected void onResumption() { + //overridden + } + + public void setupView() { + ImageView closeImageView = findViewById(R.id.close); + ConstraintLayout newClientRegistrationView = findViewById(R.id.new_client_registration); + ConstraintLayout existingClientRegistrationView = findViewById(R.id.existing_client_registration); + + newClientRegistrationView.setOnClickListener(this); + existingClientRegistrationView.setOnClickListener(this); + closeImageView.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.close) { + finish(); + } else if (id == R.id.new_client_registration) { + startPartnerRegistration(); + } else if (id == R.id.existing_client_registration) { + searchForPartner(); + } + } + + public UniqueIdRepository getUniqueIdRepository() { + return OpdLibrary.getInstance().getUniqueIdRepository(); + } + + private void startPartnerRegistration() { + + UniqueId uniqueId = getUniqueIdRepository().getNextUniqueId(); + final String entityId = uniqueId != null ? uniqueId.getOpenmrsId() : ""; + if (StringUtils.isBlank(entityId)) { + Toast.makeText(this, R.string.no_unique_id, Toast.LENGTH_SHORT).show(); + } else { + JSONObject jsonObject = getFormAsJson(getPartnerRegistrationForm(), entityId, null); + startFormActivity(jsonObject); + } + } + + public JSONObject getFormAsJson(String formName, String entityId, String currentLocationId) { + try { + JSONObject form; + + form = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + + if (form == null) { + return null; + } + + form.getJSONObject(METADATA).put(ENCOUNTER_LOCATION, currentLocationId); + + String newEntityId = entityId; + if (StringUtils.isNotBlank(entityId)) { + newEntityId = entityId.replace("-", ""); + } + + JSONObject stepOneUniqueId = getFieldJSONObject(fields(form, STEP1), Constants.JSON_FORM_KEY.UNIQUE_ID); + + if (stepOneUniqueId != null) { + stepOneUniqueId.remove(org.smartregister.family.util.JsonFormUtils.VALUE); + stepOneUniqueId.put(org.smartregister.family.util.JsonFormUtils.VALUE, newEntityId + "_Family"); + } + + JSONObject stepTwoUniqueId = getFieldJSONObject(fields(form, STEP2), Constants.JSON_FORM_KEY.UNIQUE_ID); + if (stepTwoUniqueId != null) { + stepTwoUniqueId.remove(org.smartregister.family.util.JsonFormUtils.VALUE); + stepTwoUniqueId.put(org.smartregister.family.util.JsonFormUtils.VALUE, newEntityId); + } + + org.smartregister.family.util.JsonFormUtils.addLocHierarchyQuestions(form); + return form; + + } catch (Exception e) { + Timber.e(e, "Error loading All Client registration form"); + } + return null; + } + + public void startFormActivity(JSONObject jsonObject) { + Intent intent = new Intent(this, Utils.metadata().familyMemberFormActivity); + intent.putExtra(OpdConstants.JSON_FORM_EXTRA.JSON, jsonObject.toString()); + + Form form = new Form(); + form.setName(getString(R.string.client_registration)); + form.setActionBarBackground(org.smartregister.chw.core.R.color.family_actionbar); + form.setNavigationBackground(org.smartregister.chw.core.R.color.family_navigation); + form.setHomeAsUpIndicator(org.smartregister.chw.core.R.mipmap.ic_cross_white); + form.setPreviousLabel(getResources().getString(org.smartregister.chw.core.R.string.back)); + intent.putExtra(JsonFormConstants.JSON_FORM_KEY.FORM, form); + + startActivityForResult(intent, NEW_PARTNER_REQUEST_CODE); + } + + private void searchForPartner() { + startActivityForResult(new Intent(this, AllMaleClientsActivity.class), EXISTING_PARTNER_REQUEST_CODE); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == EXISTING_PARTNER_REQUEST_CODE && resultCode == Activity.RESULT_OK) { + String partner_id = data.getStringExtra(INTENT_BASE_ENTITY_ID); + savePartnerDetails(partner_id, clientBaseEntityId); + generatePartnerReferral(partner_id); + finish(); + + } + if (requestCode == NEW_PARTNER_REQUEST_CODE && resultCode == Activity.RESULT_OK) { + String jsonString = data.getStringExtra(OpdConstants.JSON_FORM_EXTRA.JSON); + Timber.d("JSONResult : %s", jsonString); + + JSONObject form; + try { + form = new JSONObject(jsonString); + + String encounterType; + encounterType = form.getString(OpdJsonFormUtils.ENCOUNTER_TYPE); + if (encounterType.equals(CoreConstants.EventType.FAMILY_REGISTRATION)) { + RegisterParams registerParam = new RegisterParams(); + registerParam.setEditMode(false); + registerParam.setFormTag(OpdJsonFormUtils.formTag(OpdUtils.context().allSharedPreferences())); + try { + saveForm(jsonString, registerParam); + } catch (Exception e) { + Timber.e(e); + } + finish(); + + } + } catch (JSONException e) { + Timber.e(e); + } + + } + + } + + private void saveForm(String jsonString, RegisterParams registerParam) { + try { + List opdEventClientList = processRegistration(jsonString); + if (opdEventClientList == null || opdEventClientList.isEmpty()) { + return; + } + saveRegistration(opdEventClientList, jsonString, registerParam); + } catch (Exception e) { + Timber.e(e); + } + } + + public List processRegistration(String jsonString) { + return AllClientsUtils.getOpdEventClients(jsonString); + } + + public void saveRegistration(@NonNull List allClientEventList, @NonNull String jsonString, + @NonNull RegisterParams params) { + try { + List currentFormSubmissionIds = new ArrayList<>(); + + for (int i = 0; i < allClientEventList.size(); i++) { + try { + + OpdEventClient allClientEvent = allClientEventList.get(i); + Client baseClient = allClientEvent.getClient(); + Event baseEvent = allClientEvent.getEvent(); + addClient(params, baseClient); + addEvent(params, currentFormSubmissionIds, baseEvent); + updateOpenSRPId(jsonString, params, baseClient); + addImageLocation(jsonString, baseClient, baseEvent); + + if(baseEvent.getEventType().equals("Family Member Registration")) { + savePartnerDetails(baseEvent.getBaseEntityId(), clientBaseEntityId); + generatePartnerReferral(baseEvent.getBaseEntityId()); + } + } catch (Exception e) { + Timber.e(e, "ChwAllClientRegisterInteractor --> saveRegistration"); + } + } + + long lastSyncTimeStamp = getAllSharedPreferences().fetchLastUpdatedAtDate(0); + Date lastSyncDate = new Date(lastSyncTimeStamp); + getClientProcessorForJava().processClient(getSyncHelper().getEvents(currentFormSubmissionIds)); + getAllSharedPreferences().saveLastUpdatedAtDate(lastSyncDate.getTime()); + } catch (Exception e) { + Timber.e(e, "OpdRegisterInteractor --> saveRegistration"); + } + } + + private void addClient(@NonNull RegisterParams params, Client baseClient) throws JSONException { + JSONObject clientJson = new JSONObject(OpdJsonFormUtils.gson.toJson(baseClient)); + if (params.isEditMode()) { + try { + org.smartregister.family.util.JsonFormUtils.mergeAndSaveClient(getSyncHelper(), baseClient); + } catch (Exception e) { + Timber.e(e, "ChwAllClientRegisterInteractor --> mergeAndSaveClient"); + } + } else { + getSyncHelper().addClient(baseClient.getBaseEntityId(), clientJson); + } + } + + private void addImageLocation(String jsonString, Client baseClient, Event baseEvent) { + if (baseClient != null || baseEvent != null) { + String imageLocation = OpdJsonFormUtils.getFieldValue(jsonString, Constants.KEY.PHOTO); + if (StringUtils.isNotBlank(imageLocation)) { + org.smartregister.family.util.JsonFormUtils.saveImage(baseEvent.getProviderId(), baseClient.getBaseEntityId(), imageLocation); + } + } + } + + private void updateOpenSRPId(String jsonString, RegisterParams params, Client baseClient) { + if (params.isEditMode()) { + // UnAssign current OpenSRP ID + if (baseClient != null) { + String newOpenSrpId = baseClient.getIdentifier(Utils.metadata().uniqueIdentifierKey).replace("-", ""); + String currentOpenSrpId = org.smartregister.family.util.JsonFormUtils.getString(jsonString, org.smartregister.family.util.JsonFormUtils.CURRENT_OPENSRP_ID).replace("-", ""); + if (!newOpenSrpId.equals(currentOpenSrpId)) { + //OpenSRP ID was changed + getUniqueIdRepository().open(currentOpenSrpId); + } + } + + } else { + if (baseClient != null) { + String openSrpId = baseClient.getIdentifier(Utils.metadata().uniqueIdentifierKey); + if (StringUtils.isNotBlank(openSrpId) && !openSrpId.contains(Constants.IDENTIFIER.FAMILY_SUFFIX)) { + //Mark OpenSRP ID as used + getUniqueIdRepository().close(openSrpId); + } + } + } + } + + private void addEvent(RegisterParams params, List currentFormSubmissionIds, Event baseEvent) throws JSONException { + if (baseEvent != null) { + JSONObject eventJson = new JSONObject(OpdJsonFormUtils.gson.toJson(baseEvent)); + getSyncHelper().addEvent(baseEvent.getBaseEntityId(), eventJson, params.getStatus()); + currentFormSubmissionIds.add(eventJson.getString(EventClientRepository.event_column.formSubmissionId.toString())); + } + } + + protected void savePartnerDetails(String partnerBaseEntityId, String clientBaseEntityId) { + AllSharedPreferences sharedPreferences = getAllSharedPreferences(); + //Switched baseEntityId and formSubmissionId to update on the correct referral sent + Event baseEvent = (Event) new Event() + .withBaseEntityId(clientBaseEntityId) + .withEventDate(new Date()) + .withEventType(PARTNER_REGISTRATION_EVENT) + .withFormSubmissionId(generateRandomUUIDString()) + .withEntityType(CoreConstants.TABLE_NAME.ANC_MEMBER) + .withProviderId(sharedPreferences.fetchRegisteredANM()) + .withLocationId(sharedPreferences.fetchDefaultLocalityId(sharedPreferences.fetchRegisteredANM())) + .withTeamId(sharedPreferences.fetchDefaultTeamId(sharedPreferences.fetchRegisteredANM())) + .withTeam(sharedPreferences.fetchDefaultTeam(sharedPreferences.fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(PARTNER_BASE_ENTITY_ID) + .withValue(partnerBaseEntityId) + .withFieldCode(PARTNER_BASE_ENTITY_ID) + .withFieldType("formsubmissionField") + .withFieldDataType("text") + .withParentCode("") + .withHumanReadableValues(new ArrayList<>())); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(REFERRAL_FORM_SUBMISSION_ID) + .withValue(referralFormSubmissionId) + .withFieldCode(REFERRAL_FORM_SUBMISSION_ID) + .withFieldType("formsubmissionField") + .withFieldDataType("text") + .withParentCode("") + .withHumanReadableValues(new ArrayList<>())); + baseEvent.addObs((new Obs()) + .withFormSubmissionField(FEEDBACK_FORM_ID) + .withValue(formSubmissionId) + .withFieldCode(FEEDBACK_FORM_ID) + .withFieldType("formsubmissionField") + .withFieldDataType("text") + .withParentCode("") + .withHumanReadableValues(new ArrayList<>())); + // tag docs + org.smartregister.chw.util.JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), baseEvent); + try { + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(baseEvent))); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + protected void generatePartnerReferral(String partnerBaseEntityId) { + AllSharedPreferences sharedPreferences = getAllSharedPreferences(); + //Switched baseEntityId and formSubmissionId to update on the correct referral sent + Event baseEvent = (Event) new Event() + .withBaseEntityId(partnerBaseEntityId) + .withEventDate(new Date()) + .withEventType(org.smartregister.chw.referral.util.Constants.EventType.REGISTRATION) + .withFormSubmissionId(generateRandomUUIDString()) + .withEntityType(org.smartregister.chw.referral.util.Constants.Tables.REFERRAL) + .withProviderId(sharedPreferences.fetchRegisteredANM()) + .withLocationId(sharedPreferences.fetchDefaultLocalityId(sharedPreferences.fetchRegisteredANM())) + .withTeamId(sharedPreferences.fetchDefaultTeamId(sharedPreferences.fetchRegisteredANM())) + .withTeam(sharedPreferences.fetchDefaultTeam(sharedPreferences.fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.SERVICE_BEFORE_REFERRAL) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.SERVICE_BEFORE_REFERRAL) + .withValue("None")); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.PROBLEM) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.PROBLEM) + .withValue("anc_male_engagement")); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_STATUS) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_STATUS) + .withValue("PENDING")); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_SERVICE) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_SERVICE) + .withValue("ANC Male Engagement Referral")); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_DATE) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_DATE) + .withValue(new Date().getTime())); + + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss.SSS", Locale.getDefault()); + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_TIME) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_TIME) + .withValue(simpleDateFormat.format(new Date()))); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_APPOINTMENT_DATE) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_APPOINTMENT_DATE) + .withValue(new Date().getTime())); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_TYPE) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_TYPE) + .withValue(org.smartregister.chw.referral.util.Constants.ReferralType.COMMUNITY_TO_FACILITY_REFERRAL)); + + String facilityLocationId = sharedPreferences.fetchDefaultLocalityId(sharedPreferences.fetchRegisteredANM()); + LocationRepository locationRepository = new LocationRepository(); + Location facility = locationRepository.getLocationById(facilityLocationId); + + baseEvent.addObs( + (new Obs()) + .withFormSubmissionField(DBConstants.Key.REFERRAL_HF) + .withFieldType(JsonFormUtils.CONCEPT) + .withFieldCode(DBConstants.Key.REFERRAL_HF) + .withHumanReadableValues(Collections.singletonList(facility.getProperties().getName())) + .withValue(facilityLocationId)); + + // tag event + org.smartregister.chw.util.JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), baseEvent); + try { + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(baseEvent))); + } catch (Exception e) { + e.printStackTrace(); + } + + ReferralTask referralTask = new ReferralTask(baseEvent); + referralTask.setReferralDescription("partner_registration_referral"); + referralTask.setGroupId(facilityLocationId); + referralTask.setFocus(CoreConstants.TASKS_FOCUS.ANC_MALE_ENGAGEMENT); + ReferralUtil.createReferralTask(referralTask, ReferralLibrary.getInstance()); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PmtctFollowupDetailsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PmtctFollowupDetailsActivity.java new file mode 100644 index 0000000000..fcef85dfe4 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PmtctFollowupDetailsActivity.java @@ -0,0 +1,266 @@ +package org.smartregister.chw.activity; + +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; +import static org.smartregister.util.JsonFormUtils.STEP1; +import static org.smartregister.util.JsonFormUtils.VALUE; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Intent; +import android.graphics.PorterDuff; +import android.graphics.drawable.Drawable; +import android.os.Build; +import android.view.Menu; +import android.view.View; +import android.widget.Toast; + +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.widget.Toolbar; + +import com.google.android.material.appbar.AppBarLayout; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.chw.dao.PmtctDao; +import org.smartregister.chw.domain.PmtctReferralMemberObject; +import org.smartregister.chw.pmtct.util.NCUtils; +import org.smartregister.chw.referral.util.JsonFormConstants; +import org.smartregister.chw.util.Constants; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.domain.Location; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.repository.LocationRepository; +import org.smartregister.util.Utils; +import org.smartregister.view.activity.SecuredActivity; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Locale; + +import timber.log.Timber; + +public class PmtctFollowupDetailsActivity extends SecuredActivity implements View.OnClickListener { + public static final String PMTCT_MEMBER_OBJECT = "PMTCT_MEMBER_OBJECT"; + private static PmtctReferralMemberObject memberObject; + protected AppBarLayout appBarLayout; + private CustomFontTextView clientName; + private CustomFontTextView careGiverName; + private CustomFontTextView careGiverPhone; + private CustomFontTextView comments; + private CustomFontTextView referralDate; + private CustomFontTextView lastFacilityVisitDate; + private CustomFontTextView referralType; + private CustomFontTextView locationName; + private CustomFontTextView markAsDone; + private String baseEntityId; + + public static void startPmtctDetailsActivity(Activity activity, String baseEntityId) { + Intent intent = new Intent(activity, PmtctFollowupDetailsActivity.class); + intent.putExtra(PMTCT_MEMBER_OBJECT, baseEntityId); + activity.startActivity(intent); + } + + + + @Override + protected void onCreation() { + setContentView(R.layout.activity_pmtctc_details); + inflateToolbar(); + + baseEntityId = getIntent().getStringExtra(PMTCT_MEMBER_OBJECT); + memberObject = PmtctDao.getPmtctReferralMemberObject(baseEntityId); + setUpViews(); + } + + @Override + protected void onResumption() { + + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + return false; + } + + private void inflateToolbar() { + Toolbar toolbar = findViewById(R.id.back_pmtct_toolbar); + CustomFontTextView toolBarTextView = toolbar.findViewById(R.id.toolbar_title); + setSupportActionBar(toolbar); + + ActionBar supportActionBar = getSupportActionBar(); + supportActionBar.setDisplayHomeAsUpEnabled(true); + + Drawable upArrow = getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp); + + upArrow.setColorFilter(getResources().getColor(R.color.text_blue), PorterDuff.Mode.SRC_ATOP); + supportActionBar.setHomeAsUpIndicator(upArrow); + supportActionBar.setElevation(0f); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + toolbar.setNavigationOnClickListener(view -> finish()); + } + + toolBarTextView.setText(R.string.back_to_pmtct); + appBarLayout = findViewById(R.id.app_bar); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) + appBarLayout.setOutlineProvider(null); + } + + private void setUpViews() { + clientName = findViewById(R.id.client_name); + careGiverName = findViewById(R.id.care_giver_name); + careGiverPhone = findViewById(R.id.care_giver_phone); + comments = findViewById(R.id.comments); + referralDate = findViewById(R.id.referral_date); + lastFacilityVisitDate = findViewById(R.id.last_facility_visit_date); + referralType = findViewById(R.id.referral_type); + locationName = findViewById(R.id.location_name); + markAsDone = findViewById(R.id.mark_ask_done); + markAsDone.setOnClickListener(this); + obtainReferralDetails(); + } + + @SuppressLint("SetTextI18n") + private void obtainReferralDetails() { + clientName.setText(memberObject.getFirstName() + " " + memberObject.getMiddleName() + " " + memberObject.getLastName() + ", " + memberObject.getAge()); + SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault()); + Calendar referralDateCalendar = Calendar.getInstance(); + referralDateCalendar.setTimeInMillis(memberObject.getPmtctCommunityReferralDate().getTime()); + referralDate.setText(dateFormatter.format(referralDateCalendar.getTime())); + + if (memberObject.getLastFacilityVisitDate() != null) { + referralDateCalendar.setTimeInMillis(memberObject.getLastFacilityVisitDate().getTime()); + lastFacilityVisitDate.setText(dateFormatter.format(referralDateCalendar.getTime())); + } else { + findViewById(R.id.referral_facility_layout).setVisibility(View.GONE); + } + locationName.setText(memberObject.getAddress()); + + if (StringUtils.isNotEmpty(memberObject.getChildName())) { + careGiverName.setText(String.format(getString(R.string.child_name), memberObject.getChildName())); + referralType.setText(context().getStringResource(getReasonsForReferralResource(true))); + } else { + careGiverName.setVisibility(View.GONE); + referralType.setText(context().getStringResource(getReasonsForReferralResource(false))); + } + + if (StringUtils.isBlank(getFamilyMemberContacts()) && StringUtils.isEmpty(getFamilyMemberContacts())) { + careGiverPhone.setText(getString(R.string.phone_not_provided)); + } else { + careGiverPhone.setText(getFamilyMemberContacts()); + } + + if (StringUtils.isNotBlank(memberObject.getComments()) && StringUtils.isNotEmpty(memberObject.getComments())) { + comments.setText(memberObject.getComments()); + } + } + + private int getReasonsForReferralResource(boolean isChildReason) { + int resourceId; + if (isChildReason) { + switch (memberObject.getReasonsForIssuingCommunityFollowupReferral()) { + case "missed_appointment": + resourceId = R.string.missed_appointment_child; + break; + case "lost_to_followup": + resourceId = R.string.lost_to_followup_child; + break; + default: + resourceId = -1; + break; + } + } else { + switch (memberObject.getReasonsForIssuingCommunityFollowupReferral()) { + case "missed_appointment": + resourceId = R.string.missed_appointment; + break; + case "lost_to_followup": + resourceId = R.string.lost_to_followup; + break; + case "mother_champion_services": + resourceId = R.string.mother_champion_services; + break; + default: + resourceId = -1; + break; + } + } + return resourceId; + } + + private String getFamilyMemberContacts() { + String phoneNumber = ""; + String familyPhoneNumber = memberObject.getPhoneNumber(); + String familyHeadPhoneNumber = memberObject.getFamilyHeadPhoneNumber(); + String primaryCareGiverPhoneNumber = memberObject.getFamilyHeadPhoneNumber(); + + if (StringUtils.isNoneEmpty(familyPhoneNumber)) { + phoneNumber = familyPhoneNumber; + } else if (StringUtils.isEmpty(familyHeadPhoneNumber) && StringUtils.isNoneEmpty()) { + phoneNumber = familyHeadPhoneNumber; + } else if (StringUtils.isEmpty(primaryCareGiverPhoneNumber) && StringUtils.isNoneEmpty()) { + phoneNumber = primaryCareGiverPhoneNumber; + } + return phoneNumber; + } + + @Override + public void onClick(View view) { + if (view.getId() == R.id.mark_ask_done) { + JSONObject form = FormUtils.getFormUtils().getFormJson(Constants.JsonForm.getPmtctCommunityFollowupFeedback()); + AllSharedPreferences preferences = ChwApplication.getInstance().getContext().allSharedPreferences(); + + try { + JSONObject chwName = getFieldJSONObject(fields(form, STEP1), "chw_name"); + chwName.put(VALUE, preferences.getANMPreferredName(preferences.fetchRegisteredANM())); + } catch (JSONException e) { + Timber.e(e); + } + startActivityForResult(FormUtils.getStartFormActivity(form, getString(R.string.pmtct_followup_feedback_title), this), JsonFormUtils.REQUEST_CODE_GET_JSON); + } + } + + @SuppressLint("MissingSuperCall") + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == org.smartregister.chw.pmtct.util.Constants.REQUEST_CODE_GET_JSON && resultCode == RESULT_OK) { + try { + String jsonString = data.getStringExtra(org.smartregister.family.util.Constants.JSON_FORM_EXTRA.JSON); + JSONObject form = new JSONObject(jsonString); + String encounterType = form.getString(JsonFormUtils.ENCOUNTER_TYPE); + if (encounterType.equals(Constants.EncounterType.PMTCT_COMMUNITY_FOLLOWUP_FEEDBACK)) { + AllSharedPreferences allSharedPreferences = Utils.getAllSharedPreferences(); + Event baseEvent = org.smartregister.chw.pmtct.util.JsonFormUtils.processJsonForm(allSharedPreferences, tagReferralFormId(jsonString, baseEntityId), CoreConstants.TABLE_NAME.PMTCT_COMMUNITY_FEEDBACK); + org.smartregister.chw.pmtct.util.JsonFormUtils.tagEvent(allSharedPreferences, baseEvent); + baseEvent.setBaseEntityId(memberObject.getBaseEntityId()); + NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.pmtct.util.JsonFormUtils.gson.toJson(baseEvent))); + Toast.makeText(this, R.string.followup_feedback_recorded, Toast.LENGTH_SHORT).show(); + Intent intent = new Intent(this, MotherChampionRegisterActivity.class); + startActivity(intent); + } + } catch (Exception e) { + Timber.e(e, "MotherChampionRegisterActivity -- > onActivityResult"); + } + } + } + + private String tagReferralFormId(String jsonString, String formSubmissionId) throws JSONException { + JSONObject form = new JSONObject(jsonString); + JSONArray fields = org.smartregister.util.JsonFormUtils.fields(form); + JSONObject referralFormId = org.smartregister.util.JsonFormUtils.getFieldJSONObject(fields, Constants.PmtctFollowupFeedbackConstants.referralFormId); + assert referralFormId != null; + referralFormId.put(JsonFormUtils.VALUE, formSubmissionId); + return form.toString(); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncHomeVisitActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncHomeVisitActivity.java index c84e9d8798..4997ce1b4d 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncHomeVisitActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncHomeVisitActivity.java @@ -10,6 +10,7 @@ import org.json.JSONObject; import org.smartregister.chw.R; import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.model.BaseAncHomeVisitAction; import org.smartregister.chw.anc.presenter.BaseAncHomeVisitPresenter; import org.smartregister.chw.core.task.RunnableTask; import org.smartregister.chw.core.utils.CoreConstants; @@ -22,6 +23,7 @@ import org.smartregister.util.LangUtils; import java.util.Date; +import java.util.LinkedHashMap; public class PncHomeVisitActivity extends BasePncHomeVisitActivity { @@ -65,4 +67,15 @@ protected void attachBaseContext(Context base) { String lang = LangUtils.getLanguage(base.getApplicationContext()); super.attachBaseContext(LangUtils.setAppLocale(base, lang)); } + + @Override + public void initializeActions(LinkedHashMap map) { + actionList.clear(); + actionList.putAll(map); + + if (mAdapter != null) { + mAdapter.notifyDataSetChanged(); + } + displayProgressBar(false); + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncMemberProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncMemberProfileActivity.java index fbfc1880f4..0777bc7cd4 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncMemberProfileActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncMemberProfileActivity.java @@ -1,5 +1,16 @@ package org.smartregister.chw.activity; +import static org.smartregister.chw.core.utils.Utils.getCommonPersonObjectClient; +import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; +import static org.smartregister.chw.util.Constants.EventType; +import static org.smartregister.chw.util.Constants.JSON_FORM; +import static org.smartregister.chw.util.Constants.ProfileActivityResults; +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.chw.util.Utils.getClientGender; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; +import static org.smartregister.util.Utils.getAllSharedPreferences; + import android.app.Activity; import android.content.Intent; import android.util.Pair; @@ -9,9 +20,13 @@ import android.view.View; import android.widget.LinearLayout; +import com.vijay.jsonwizard.utils.FormUtils; + import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.Days; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.R; @@ -24,17 +39,22 @@ import org.smartregister.chw.core.activity.CorePncMemberProfileActivity; import org.smartregister.chw.core.activity.CorePncRegisterActivity; import org.smartregister.chw.core.adapter.NotificationListAdapter; +import org.smartregister.chw.core.dao.ChwNotificationDao; import org.smartregister.chw.core.interactor.CorePncMemberProfileInteractor; import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.model.CoreAllClientsMemberModel; import org.smartregister.chw.core.rule.PncVisitAlertRule; import org.smartregister.chw.core.utils.ChwNotificationUtil; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.core.utils.CoreJsonFormUtils; +import org.smartregister.chw.core.utils.UpdateDetailsUtil; import org.smartregister.chw.custom_view.AncFloatingMenu; import org.smartregister.chw.fp.util.FamilyPlanningConstants; +import org.smartregister.chw.hivst.dao.HivstDao; import org.smartregister.chw.interactor.ChildProfileInteractor; import org.smartregister.chw.interactor.FamilyProfileInteractor; import org.smartregister.chw.interactor.PncMemberProfileInteractor; +import org.smartregister.chw.kvp.dao.KvpDao; import org.smartregister.chw.model.ChildRegisterModel; import org.smartregister.chw.model.FamilyProfileModel; import org.smartregister.chw.model.ReferralTypeModel; @@ -47,8 +67,10 @@ import org.smartregister.commonregistry.CommonRepository; import org.smartregister.family.contract.FamilyProfileContract; import org.smartregister.family.domain.FamilyEventClient; +import org.smartregister.family.util.DBConstants; import org.smartregister.family.util.JsonFormUtils; import org.smartregister.family.util.Utils; +import org.smartregister.repository.AllSharedPreferences; import java.text.MessageFormat; import java.util.ArrayList; @@ -65,14 +87,8 @@ import io.reactivex.schedulers.Schedulers; import timber.log.Timber; -import static org.smartregister.chw.core.utils.Utils.passToolbarTitle; -import static org.smartregister.chw.util.Constants.EventType; -import static org.smartregister.chw.util.Constants.JSON_FORM; -import static org.smartregister.chw.util.Constants.ProfileActivityResults; -import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; -import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; - public class PncMemberProfileActivity extends CorePncMemberProfileActivity implements PncMemberProfileContract.View { + public static final String CLOSE_PNC_VISITS = "Close PNC Visits"; private Flavor flavor = new PncMemberProfileActivityFlv(); private List referralTypeModels = new ArrayList<>(); @@ -114,6 +130,11 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { FamilyEventClient familyEventClient = new FamilyProfileModel(memberObject.getFamilyName()).processUpdateMemberRegistration(jsonString, memberObject.getBaseEntityId()); new FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, (FamilyProfileContract.InteractorCallBack) pncMemberProfilePresenter()); + } else if (form.getString(JsonFormUtils.ENCOUNTER_TYPE).equals(Utils.metadata().familyRegister.updateEventType)) { + CommonPersonObjectClient client = getCommonPersonObjectClient(memberObject.getBaseEntityId()); + FamilyEventClient familyEventClient = new CoreAllClientsMemberModel().processJsonForm(jsonString, UpdateDetailsUtil.getFamilyBaseEntityId(client)); + familyEventClient.getEvent().setEntityType(CoreConstants.TABLE_NAME.INDEPENDENT_CLIENT); + new org.smartregister.family.interactor.FamilyProfileInteractor().saveRegistration(familyEventClient, jsonString, true, (FamilyProfileContract.InteractorCallBack) pncMemberProfilePresenter()); } if (EventType.UPDATE_CHILD_REGISTRATION.equals(form.getString(JsonFormUtils.ENCOUNTER_TYPE))) { @@ -145,35 +166,45 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { @Override public void setupViews() { super.setupViews(); +// textview_record_visit.setVisibility(GONE); + PncVisitAlertRule summaryVisit = getVisitDetails(); String statusVisit = summaryVisit.getButtonStatus(); if (statusVisit.equals("OVERDUE")) { - textview_record_visit.setVisibility(View.VISIBLE); - textview_record_visit.setBackgroundResource(R.drawable.rounded_red_btn); + updateUiForVisitsOverdue(); } else if (statusVisit.equals("DUE")) { - textview_record_visit.setVisibility(View.VISIBLE); - textview_record_visit.setBackgroundResource(R.drawable.rounded_blue_btn); + updateUiForVisitsDue(); } else if (ChildProfileInteractor.VisitType.VISIT_DONE.name().equals(statusVisit)) { Visit lastVisit = getVisit(Constants.EVENT_TYPE.PNC_HOME_VISIT); if (lastVisit != null) { if ((Days.daysBetween(new DateTime(lastVisit.getCreatedAt()), new DateTime()).getDays() < 1) && (Days.daysBetween(new DateTime(lastVisit.getDate()), new DateTime()).getDays() <= 1)) { setEditViews(true, true, lastVisit.getDate().getTime()); - } else { - textview_record_visit.setVisibility(View.GONE); - layoutRecordView.setVisibility(View.GONE); - } + } else updateUiForNoVisits(); - } else { - textview_record_visit.setVisibility(View.VISIBLE); - textview_record_visit.setBackgroundResource(R.drawable.rounded_blue_btn); - } - } else { - textview_record_visit.setVisibility(View.GONE); - layoutRecordView.setVisibility(View.GONE); - } + } else updateUiForVisitsDue(); + + } else updateUiForNoVisits(); } + protected void updateUiForNoVisits() { + textview_record_visit.setVisibility(View.GONE); + layoutRecordView.setVisibility(View.GONE); + } + + protected void updateUiForVisitsDue() { + layoutRecordView.setVisibility(View.VISIBLE); + textview_record_visit.setVisibility(View.VISIBLE); + textview_record_visit.setBackgroundResource(R.drawable.rounded_blue_btn); + } + + protected void updateUiForVisitsOverdue() { + layoutRecordView.setVisibility(View.VISIBLE); + textview_record_visit.setVisibility(View.VISIBLE); + textview_record_visit.setBackgroundResource(R.drawable.rounded_red_btn); + } + + private void refreshOnHomeVisitResult() { Observable observable = Observable.create(e -> { Visit lastVisit = getVisit(CoreConstants.EventType.PNC_HOME_VISIT); @@ -240,6 +271,16 @@ protected void onCreation() { notificationListAdapter.setOnClickListener(this); } +// @Override +// public void setUpComingServicesStatus(String service, AlertStatus status, Date date) { +// findViewById(R.id.rlUpcomingServices).setVisibility(GONE); +// } +// +// @Override +// public void setFamilyStatus(AlertStatus status) { +// findViewById(R.id.view_family_row).setVisibility(GONE); +// } + @Override public void registerPresenter() { presenter = new PncMemberProfilePresenter(this, new PncMemberProfileInteractor(this), memberObject); @@ -290,9 +331,52 @@ public void openUpcomingService() { public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); flavor.onCreateOptionsMenu(menu, memberObject.getBaseEntityId()); + if (ChwApplication.getApplicationFlavor().hasHIVST()) { + int age = memberObject.getAge(); + menu.findItem(R.id.action_hivst_registration).setVisible(!HivstDao.isRegisteredForHivst(memberObject.getBaseEntityId()) && age >= 15); + } + if(ChwApplication.getApplicationFlavor().hasKvp()){ + menu.findItem(R.id.action_kvp_prep_registration).setVisible(!KvpDao.isRegisteredForKvpPrEP(baseEntityID)); + } return true; } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == org.smartregister.chw.core.R.id.action_pnc_member_registration) { + if (UpdateDetailsUtil.isIndependentClient(baseEntityID)) { + startFormForEdit(org.smartregister.chw.core.R.string.registration_info, + CoreConstants.JSON_FORM.getAllClientUpdateRegistrationInfoForm()); + } else { + startFormForEdit(org.smartregister.chw.core.R.string.edit_member_form_title, + CoreConstants.JSON_FORM.getFamilyMemberRegister()); + } + return true; + } + if (itemId == R.id.action_hivst_registration) { + CommonPersonObjectClient commonPersonObjectClient = getCommonPersonObjectClient(memberObject.getBaseEntityId()); + String gender = Utils.getValue(commonPersonObjectClient.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + HivstRegisterActivity.startHivstRegistrationActivity(this, baseEntityID, gender); + } + if(itemId == R.id.action_kvp_prep_registration){ + String gender = getClientGender(baseEntityID); + int age = memberObject.getAge(); + KvpPrEPRegisterActivity.startRegistration(PncMemberProfileActivity.this, baseEntityID, gender, age); + return true; + } + return super.onOptionsItemSelected(item); + } + + public void startFormForEdit(Integer title_resource, String formName) { + try { + JSONObject form = CoreJsonFormUtils.getAncPncForm(title_resource, formName, memberObject, this); + startActivityForResult(CoreJsonFormUtils.getAncPncStartFormIntent(form, this), JsonFormUtils.REQUEST_CODE_GET_JSON); + } catch (Exception e) { + Timber.e(e); + } + } + @Override public void onClick(View view) { super.onClick(view); @@ -372,21 +456,12 @@ public List getReferralTypeModels() { } private void addPncReferralTypes() { - referralTypeModels.add(new ReferralTypeModel(getString(R.string.pnc_danger_signs), + referralTypeModels.add(new ReferralTypeModel(getString(R.string.pnc_referral), BuildConfig.USE_UNIFIED_REFERRAL_APPROACH ? JSON_FORM.getPncUnifiedReferralForm() : JSON_FORM.getPncReferralForm(), CoreConstants.TASKS_FOCUS.PNC_DANGER_SIGNS)); if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { - referralTypeModels.add(new ReferralTypeModel(getString(R.string.suspected_malaria), - JSON_FORM.getMalariaReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_MALARIA)); - - referralTypeModels.add(new ReferralTypeModel(getString(R.string.hiv_referral), - JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_HIV)); - - referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), - JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); - referralTypeModels.add(new ReferralTypeModel(getString(R.string.gbv_referral), - JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); + CoreConstants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); } } @@ -401,6 +476,38 @@ protected void startFpRegister() { FpRegisterActivity.startFpRegistrationActivity(this, memberObject.getBaseEntityId(), memberObject.getDob(), CoreConstants.JSON_FORM.getFpRegistrationForm("Female"), FamilyPlanningConstants.ActivityPayload.REGISTRATION_PAYLOAD_TYPE); } + @Override + protected void startHivRegister() { + CommonPersonObjectClient client = getCommonPersonObjectClient(memberObject.getBaseEntityId()); + String gender = org.smartregister.chw.util.Utils.getValue(client.getColumnmaps(), DBConstants.KEY.GENDER, false); + String dob = org.smartregister.chw.util.Utils.getValue(client.getColumnmaps(), DBConstants.KEY.DOB, false); + int age = org.smartregister.chw.util.Utils.getAgeFromDate(dob); + + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(PncMemberProfileActivity.this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + updateAgeAndGender(fields, age, gender); + + HivRegisterActivity.startHIVFormActivity(PncMemberProfileActivity.this, memberObject.getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + protected void startTbRegister() { + try { + TbRegisterActivity.startTbFormActivity(this, memberObject.getBaseEntityId(), JSON_FORM.getTbRegistration(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, JSON_FORM.getTbRegistration()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + @Override protected void startFpChangeMethod() { FpRegisterActivity.startFpRegistrationActivity(this, memberObject.getBaseEntityId(), memberObject.getDob(), CoreConstants.JSON_FORM.getFpChangeMethodForm("female"), FamilyPlanningConstants.ActivityPayload.CHANGE_METHOD_PAYLOAD_TYPE); @@ -434,6 +541,33 @@ public void onReceivedNotifications(List> notifications) { handleReceivedNotifications(this, notifications, notificationListAdapter); } + public static void closePncMemberVisits(String baseEntityId) { + AllSharedPreferences sharedPreferences = getAllSharedPreferences(); + Event baseEvent = (Event) new Event() + .withBaseEntityId(baseEntityId) + .withEventDate(new Date()) + .withEventType(CLOSE_PNC_VISITS) + .withFormSubmissionId(org.smartregister.util.JsonFormUtils.generateRandomUUIDString()) + .withEntityType(CoreConstants.TABLE_NAME.PNC_MEMBER) + .withProviderId(sharedPreferences.fetchRegisteredANM()) + .withLocationId(ChwNotificationDao.getSyncLocationId(baseEntityId)) + .withTeamId(sharedPreferences.fetchDefaultTeamId(sharedPreferences.fetchRegisteredANM())) + .withTeam(sharedPreferences.fetchDefaultTeam(sharedPreferences.fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + try { + org.smartregister.chw.util.JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), baseEvent); + } catch (Exception e) { + Timber.e(e); + } + try { + org.smartregister.chw.anc.util.NCUtils.processEvent(baseEvent.getBaseEntityId(), new JSONObject(org.smartregister.chw.anc.util.JsonFormUtils.gson.toJson(baseEvent))); + } catch (Exception e) { + Timber.e(e); + } + } + public interface Flavor { Boolean onCreateOptionsMenu(@Nullable Menu menu, @Nullable String baseEntityId); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncRegisterActivity.java index 750eee95a8..6ee047c540 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncRegisterActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/PncRegisterActivity.java @@ -1,24 +1,32 @@ package org.smartregister.chw.activity; +import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; +import android.view.MenuItem; + +import androidx.annotation.NonNull; + +import com.google.android.material.bottomnavigation.BottomNavigationView; import org.apache.commons.lang3.EnumUtils; import org.json.JSONArray; import org.json.JSONObject; +import org.smartregister.chw.R; import org.smartregister.chw.anc.util.Constants; import org.smartregister.chw.anc.util.JsonFormUtils; import org.smartregister.chw.core.activity.CoreFamilyRegisterActivity; import org.smartregister.chw.core.activity.CorePncRegisterActivity; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.fragment.PncRegisterFragment; +import org.smartregister.helper.BottomNavigationHelper; import org.smartregister.job.SyncServiceJob; import org.smartregister.view.fragment.BaseRegisterFragment; import timber.log.Timber; -public class PncRegisterActivity extends CorePncRegisterActivity { +public class PncRegisterActivity extends CorePncRegisterActivity implements BottomNavigationView.OnNavigationItemSelectedListener { public static void startPncRegistrationActivity(Activity activity, String memberBaseEntityID, String phoneNumber, String formName, String uniqueId, String familyBaseID, String family_name, String last_menstrual_period) { @@ -46,8 +54,14 @@ public void onRegistrationSaved(String encounterType, boolean isEdit, boolean ha @Override protected void registerBottomNavigation() { - super.registerBottomNavigation(); - FamilyRegisterActivity.registerBottomNavigation(bottomNavigationHelper, bottomNavigationView, this); + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(R.id.bottom_navigation); + bottomNavigationView.getMenu().clear(); + + bottomNavigationView.inflateMenu(R.menu.anc_bottom_nav_menu); + bottomNavigationView.getMenu().removeItem(R.id.action_received_referrals); + + bottomNavigationView.setOnNavigationItemSelectedListener(this); } @Override @@ -60,6 +74,7 @@ protected BaseRegisterFragment getRegisterFragment() { return new PncRegisterFragment(); } + @SuppressLint("MissingSuperCall") protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResultExtended(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { @@ -83,4 +98,9 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } } } + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { + return false; + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ReferralRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ReferralRegisterActivity.java index 4cbcd72f6e..620041fda6 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/ReferralRegisterActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/ReferralRegisterActivity.java @@ -3,10 +3,9 @@ import android.app.Activity; import android.content.Intent; import android.os.Bundle; +import android.view.MenuItem; -import androidx.fragment.app.Fragment; - -import com.google.android.material.bottomnavigation.LabelVisibilityMode; +import com.google.android.material.bottomnavigation.BottomNavigationView; import org.apache.commons.lang3.tuple.Triple; import org.jetbrains.annotations.NotNull; @@ -15,16 +14,18 @@ import org.json.JSONObject; import org.smartregister.chw.R; import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.fragment.CompletedReferralRegisterFragment; import org.smartregister.chw.fragment.ReferralRegisterFragment; import org.smartregister.chw.malaria.util.MalariaJsonFormUtils; import org.smartregister.chw.referral.activity.BaseReferralRegisterActivity; import org.smartregister.chw.util.Constants; import org.smartregister.helper.BottomNavigationHelper; -import org.smartregister.listener.BottomNavigationListener; import java.util.Collections; import java.util.List; +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; import timber.log.Timber; import static org.smartregister.chw.core.utils.CoreConstants.ENTITY_ID; @@ -34,7 +35,7 @@ import static org.smartregister.util.JsonFormUtils.VALUE; import static org.smartregister.util.JsonFormUtils.getFieldJSONObject; -public class ReferralRegisterActivity extends BaseReferralRegisterActivity { +public class ReferralRegisterActivity extends BaseReferralRegisterActivity implements BottomNavigationView.OnNavigationItemSelectedListener { public static void startReferralRegistrationActivity(Activity activity, String baseEntityID) { Intent intent = new Intent(activity, ReferralRegisterActivity.class); @@ -47,7 +48,7 @@ public static void startReferralRegistrationActivity(Activity activity, String b @NotNull @Override protected Fragment[] getOtherFragments() { - return new Fragment[]{}; + return new CompletedReferralRegisterFragment[]{new CompletedReferralRegisterFragment()}; } @NotNull @@ -71,21 +72,10 @@ protected void onCreate(Bundle savedInstanceState) { protected void registerBottomNavigation() { bottomNavigationHelper = new BottomNavigationHelper(); bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + bottomNavigationView.getMenu().clear(); - if (bottomNavigationView != null) { - bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); - bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); - bottomNavigationView.getMenu().removeItem(org.smartregister.chw.referral.R.id.action_register); - bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); - bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); - - bottomNavigationView.inflateMenu(getMenuResource()); - bottomNavigationHelper.disableShiftMode(bottomNavigationView); - - BottomNavigationListener referralBottomNavigationListener = getBottomNavigation(this); - bottomNavigationView.setOnNavigationItemSelectedListener(referralBottomNavigationListener); - - } + bottomNavigationView.inflateMenu(R.menu.referrals_bottom_nav_menu); + bottomNavigationView.setOnNavigationItemSelectedListener(this); } @Override @@ -138,5 +128,17 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } } + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { + if (menuItem.getItemId() == R.id.action_home) { + switchToFragment(0); + return true; + } else if (menuItem.getItemId() == R.id.action_completed_referrals) { + switchToFragment(1); + return true; + } else + return false; + } } \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/RequestPhoneNumberCollectionPermission.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/RequestPhoneNumberCollectionPermission.java new file mode 100644 index 0000000000..0b45a2abde --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/RequestPhoneNumberCollectionPermission.java @@ -0,0 +1,72 @@ +package org.smartregister.chw.activity; + +import android.Manifest; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Build; +import android.os.Bundle; +import android.view.View; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.FragmentActivity; + +import org.smartregister.chw.R; + +public class RequestPhoneNumberCollectionPermission extends FragmentActivity { + private static final int READ_PHONE_NUMBERS_PERMISSION_CODE = 100; + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == READ_PHONE_NUMBERS_PERMISSION_CODE) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + Toast.makeText(RequestPhoneNumberCollectionPermission.this, "Read Phone Number Permission Granted", Toast.LENGTH_SHORT).show(); + startLoginActivity(); + } else { + Toast.makeText(RequestPhoneNumberCollectionPermission.this, "Read Phone Number Permission Not Granted", Toast.LENGTH_SHORT).show(); + } + } + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && ContextCompat.checkSelfPermission(RequestPhoneNumberCollectionPermission.this, + Manifest.permission.READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED) { + startLoginActivity(); + }else if (ContextCompat.checkSelfPermission(RequestPhoneNumberCollectionPermission.this, + Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) { + startLoginActivity(); + } + setContentView(R.layout.activity_request_call_phone_permission); + } + + public void onClickNoThanks(View view) { + finish(); + } + + public void onClickGrant(View view) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + checkPermission(Manifest.permission.READ_PHONE_NUMBERS, READ_PHONE_NUMBERS_PERMISSION_CODE); + } else { + checkPermission(Manifest.permission.READ_PHONE_STATE, READ_PHONE_NUMBERS_PERMISSION_CODE); + } + } + + public void checkPermission(String permission, int requestCode) { + if (ContextCompat.checkSelfPermission(RequestPhoneNumberCollectionPermission.this, permission) == PackageManager.PERMISSION_DENIED) { + ActivityCompat.requestPermissions(RequestPhoneNumberCollectionPermission.this, new String[]{permission}, requestCode); + } else { + Toast.makeText(RequestPhoneNumberCollectionPermission.this, "Permission already granted", Toast.LENGTH_SHORT).show(); + } + } + + public void startLoginActivity() { + Intent intent = new Intent(RequestPhoneNumberCollectionPermission.this, LoginActivity.class); + startActivity(intent); + finish(); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/RestockingVisitHistoryActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/RestockingVisitHistoryActivity.java new file mode 100644 index 0000000000..cd387b1fbb --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/RestockingVisitHistoryActivity.java @@ -0,0 +1,25 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; + +import org.json.JSONObject; +import org.smartregister.chw.cdp.activity.BaseRestockingHistoryActivity; +import org.smartregister.chw.cdp.domain.OutletObject; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.core.utils.FormUtils; +import org.smartregister.family.util.JsonFormUtils; + +public class RestockingVisitHistoryActivity extends BaseRestockingHistoryActivity { + + public static void startMe(Activity activity, OutletObject outletObject) { + Intent intent = new Intent(activity, RestockingVisitHistoryActivity.class); + intent.putExtra(Constants.ACTIVITY_PAYLOAD.OUTLET_OBJECT, outletObject); + activity.startActivity(intent); + } + + @Override + public void startFormActivity(JSONObject jsonForm) { + startActivityForResult(FormUtils.getStartFormActivity(jsonForm, null, this), JsonFormUtils.REQUEST_CODE_GET_JSON); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbCommunityFollowupDetailsActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbCommunityFollowupDetailsActivity.java new file mode 100644 index 0000000000..768e3af8a2 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbCommunityFollowupDetailsActivity.java @@ -0,0 +1,23 @@ +package org.smartregister.chw.activity; + + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.smartregister.chw.tb.activity.BaseTbCommunityFollowupDetailsActivity; +import org.smartregister.chw.util.Constants; + +import timber.log.Timber; + +public class TbCommunityFollowupDetailsActivity extends BaseTbCommunityFollowupDetailsActivity { + + @Override + public void openFollowupForm() { + try { + TbRegisterActivity.startTbFormActivity(this, getMemberObject().getBaseEntityId(), Constants.JSON_FORM.getHivCommunityFollowFeedback(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, Constants.JSON_FORM.getHivCommunityFollowFeedback()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } +} + \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbProfileActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbProfileActivity.java new file mode 100644 index 0000000000..9e6b8f2d4a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbProfileActivity.java @@ -0,0 +1,307 @@ +package org.smartregister.chw.activity; + +import static org.smartregister.chw.util.NotificationsUtil.handleNotificationRowClick; +import static org.smartregister.chw.util.NotificationsUtil.handleReceivedNotifications; +import static org.smartregister.chw.util.Utils.updateAgeAndGender; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.util.Pair; +import android.view.Gravity; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.LinearLayout; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.R; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.activity.CoreTbProfileActivity; +import org.smartregister.chw.core.activity.CoreTbUpcomingServicesActivity; +import org.smartregister.chw.core.adapter.NotificationListAdapter; +import org.smartregister.chw.core.contract.FamilyProfileExtendedContract; +import org.smartregister.chw.core.interactor.CoreTbProfileInteractor; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.core.listener.OnRetrieveNotifications; +import org.smartregister.chw.core.task.RunnableTask; +import org.smartregister.chw.core.utils.ChwNotificationUtil; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.custom_view.TbFloatingMenu; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.presenter.TbProfilePresenter; +import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; +import org.smartregister.chw.tb.activity.BaseTbRegistrationFormsActivity; +import org.smartregister.chw.tb.domain.TbMemberObject; +import org.smartregister.chw.tb.util.Constants; +import org.smartregister.chw.tb.util.TbUtil; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import io.reactivex.annotations.Nullable; +import timber.log.Timber; + +public class TbProfileActivity extends CoreTbProfileActivity + implements FamilyProfileExtendedContract.PresenterCallBack, OnRetrieveNotifications { + + private List referralTypeModels = new ArrayList<>(); + private NotificationListAdapter notificationListAdapter = new NotificationListAdapter(); + private Flavor flavor = new TbProfileActivityFlv(); + + public static void startTbProfileActivity(Activity activity, TbMemberObject memberObject) { + Intent intent = new Intent(activity, TbProfileActivity.class); + intent.putExtra(Constants.ActivityPayload.MEMBER_OBJECT, memberObject); + activity.startActivity(intent); + } + + public void startTbFollowupActivity(Activity activity, String baseEntityID) throws JSONException { + Intent intent = new Intent(activity, BaseTbRegistrationFormsActivity.class); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.JSON_FORM, (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, org.smartregister.chw.util.Constants.JSON_FORM.getTbFollowupVisit()).toString()); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.USE_DEFAULT_NEAT_FORM_LAYOUT, false); + + activity.startActivityForResult(intent, org.smartregister.chw.anc.util.Constants.REQUEST_CODE_HOME_VISIT); + } + + @Override + protected void onCreation() { + super.onCreation(); + addTbReferralTypes(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + notificationAndReferralRecyclerView.setAdapter(notificationListAdapter); + notificationListAdapter.setOnClickListener(this); + } + + @Override + protected void onResume() { + super.onResume(); + notificationListAdapter.canOpen = true; + ChwNotificationUtil.retrieveNotifications(ChwApplication.getApplicationFlavor().hasReferrals(), + getTbMemberObject().getBaseEntityId(), this); + } + + @Override + protected void removeMember() { + IndividualProfileRemoveActivity.startIndividualProfileActivity(TbProfileActivity.this, + getClientDetailsByBaseEntityID(getTbMemberObject().getBaseEntityId()), + getTbMemberObject().getFamilyBaseEntityId(), getTbMemberObject().getFamilyHead(), + getTbMemberObject().getPrimaryCareGiver(), FpRegisterActivity.class.getCanonicalName()); + } + + @Override + protected void startTbCaseClosure() { + try { + TbRegisterActivity.startTbFormActivity(this, getTbMemberObject().getBaseEntityId(), CoreConstants.JSON_FORM.getTbCaseClosure(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, CoreConstants.JSON_FORM.getTbCaseClosure()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + + @Override + protected void initializePresenter() { + showProgressBar(true); + setTbProfilePresenter(new TbProfilePresenter(this, new CoreTbProfileInteractor(this), getTbMemberObject())); + fetchProfileData(); + } + + private void checkPhoneNumberProvided() { + boolean phoneNumberAvailable = (StringUtils.isNotBlank(getTbMemberObject().getPhoneNumber()) + || StringUtils.isNotBlank(getTbMemberObject().getPrimaryCareGiverPhoneNumber())); + + ((TbFloatingMenu) getTbFloatingMenu()).redraw(phoneNumberAvailable); + } + + @Override + public void onClick(View view) { + super.onClick(view); + int id = view.getId(); + if (id == R.id.record_tb_followup_visit) { + openFollowUpVisitForm(false); + } + handleNotificationRowClick(this, view, notificationListAdapter, getTbMemberObject().getBaseEntityId()); + + } + + @Override + public Context getContext() { + return null; + } + + @Override + public void verifyHasPhone() { + // Implement + } + + @Override + public void notifyHasPhone(boolean b) { + // Implement + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + // recompute schedule + Runnable runnable = () -> ChwScheduleTaskExecutor.getInstance().execute(getTbMemberObject().getBaseEntityId(), org.smartregister.chw.tb.util.Constants.EventType.FOLLOW_UP_VISIT, new Date()); + org.smartregister.chw.util.Utils.startAsyncTask(new RunnableTask(runnable), null); + + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == CoreConstants.ProfileActivityResults.CHANGE_COMPLETED && resultCode == Activity.RESULT_OK) { + Intent intent = new Intent(this, TbRegisterActivity.class); + intent.putExtras(getIntent().getExtras()); + startActivity(intent); + finish(); + + } + } + + @Override + public void openMedicalHistory() { + //TODO implement + } + + @Override + public void openTbRegistrationForm() { + try { + TbRegisterActivity.startTbFormActivity(this, getTbMemberObject().getBaseEntityId(), CoreConstants.JSON_FORM.getTbRegistration(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, CoreConstants.JSON_FORM.getTbRegistration()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + + @Override + public void openUpcomingServices() { + CoreTbUpcomingServicesActivity.startMe(this, TbUtil.toMember(getTbMemberObject())); + } + + @Override + public void openFamilyDueServices() { + Intent intent = new Intent(this, FamilyProfileActivity.class); + + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_BASE_ENTITY_ID, getTbMemberObject().getFamilyBaseEntityId()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_HEAD, getTbMemberObject().getFamilyHead()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.PRIMARY_CAREGIVER, getTbMemberObject().getPrimaryCareGiver()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_NAME, getTbMemberObject().getFamilyName()); + + intent.putExtra(CoreConstants.INTENT_KEY.SERVICE_DUE, true); + startActivity(intent); + } + + @Override + public void openFollowUpVisitForm(boolean isEdit) { + if (!isEdit) { + try { + startTbFollowupActivity(this, getTbMemberObject().getBaseEntityId()); + } catch (JSONException e) { + Timber.e(e); + } + } + } + + private void addTbReferralTypes() { + if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { + referralTypeModels.add(new ReferralTypeModel(getString(R.string.tb_referral), + CoreConstants.JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); + + referralTypeModels.add(new ReferralTypeModel(getString(R.string.gbv_referral), + CoreConstants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); + } + + } + + public List getReferralTypeModels() { + return referralTypeModels; + } + + @Override + public void initializeCallFAB() { + setTbFloatingMenu(new TbFloatingMenu(this, getTbMemberObject())); + + OnClickFloatingMenu onClickFloatingMenu = viewId -> { + switch (viewId) { + case R.id.tb_fab: + checkPhoneNumberProvided(); + ((TbFloatingMenu) getTbFloatingMenu()).animateFAB(); + break; + case R.id.call_layout: + ((TbFloatingMenu) getTbFloatingMenu()).launchCallWidget(); + ((TbFloatingMenu) getTbFloatingMenu()).animateFAB(); + break; + case R.id.refer_to_facility_layout: + ((TbProfilePresenter) getTbProfilePresenter()).referToFacility(); + break; + default: + Timber.d("Unknown fab action"); + break; + } + + }; + + ((TbFloatingMenu) getTbFloatingMenu()).setFloatMenuClickListener(onClickFloatingMenu); + getTbFloatingMenu().setGravity(Gravity.BOTTOM | Gravity.END); + LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.MATCH_PARENT); + addContentView(getTbFloatingMenu(), linearLayoutParams); + } + + @Override + public void onReceivedNotifications(List> notifications) { + handleReceivedNotifications(this, notifications, notificationListAdapter); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(org.smartregister.chw.core.R.menu.tb_profile_menu, menu); + flavor.updateHivMenuItems(getTbMemberObject().getBaseEntityId(), menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int itemId = item.getItemId(); + if (itemId == org.smartregister.chw.core.R.id.action_cbhs_registration) { + startHivRegister(); + return true; + } + return super.onOptionsItemSelected(item); + } + + protected void startHivRegister() { + try { + String formName = org.smartregister.chw.util.Constants.JsonForm.getCbhsRegistrationForm(); + JSONObject formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(this, formName); + JSONArray steps = formJsonObject.getJSONArray("steps"); + JSONObject step = steps.getJSONObject(0); + JSONArray fields = step.getJSONArray("fields"); + + + int age = org.smartregister.chw.util.Utils.getAgeFromDate(getTbMemberObject().getAge()); + try { + updateAgeAndGender(fields, age, getTbMemberObject().getGender()); + } catch (Exception e) { + Timber.e(e); + } + + HivRegisterActivity.startHIVFormActivity(this, getTbMemberObject().getBaseEntityId(), formName, formJsonObject.toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + + public interface Flavor { + void updateHivMenuItems(@Nullable String baseEntityId, @Nullable Menu menu); + } + +} + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbRegisterActivity.java new file mode 100644 index 0000000000..a9534eb8e6 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/TbRegisterActivity.java @@ -0,0 +1,71 @@ +package org.smartregister.chw.activity; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import com.google.android.material.bottomnavigation.LabelVisibilityMode; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.activity.CoreTbRegisterActivity; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.fragment.TbFollowupRegisterFragment; +import org.smartregister.chw.fragment.TbRegisterFragment; +import org.smartregister.chw.tb.fragment.BaseTbCommunityFollowupRegisterFragment; +import org.smartregister.chw.tb.fragment.BaseTbRegisterFragment; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.listener.BottomNavigationListener; + +public class TbRegisterActivity extends CoreTbRegisterActivity { + + public static void startTbFormActivity(Activity activity, String baseEntityID, String formName, String payloadType) { + Intent intent = new Intent(activity, TbRegisterActivity.class); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.BASE_ENTITY_ID, baseEntityID); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.ACTION, payloadType); + intent.putExtra(org.smartregister.chw.tb.util.Constants.ActivityPayload.TB_REGISTRATION_FORM_NAME, formName); + activity.startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } + + @NotNull + @Override + protected BaseTbRegisterFragment getRegisterFragment() { + return new TbRegisterFragment(); + } + + @NotNull + @Override + protected BaseTbCommunityFollowupRegisterFragment[] getOtherFragments() { + return new TbFollowupRegisterFragment[]{ + new TbFollowupRegisterFragment()}; + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + NavigationMenu.getInstance(this, null, null); + } + + @Override + protected void registerBottomNavigation() { + bottomNavigationHelper = new BottomNavigationHelper(); + bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); + + if (bottomNavigationView != null) { + bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_LABELED); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_clients); + bottomNavigationView.getMenu().removeItem(org.smartregister.chw.tb.R.id.action_register); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_search); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_library); + + bottomNavigationView.inflateMenu(getMenuResource()); + bottomNavigationHelper.disableShiftMode(bottomNavigationView); + + BottomNavigationListener tbBottomNavigationListener = getBottomNavigation(this); + bottomNavigationView.setOnNavigationItemSelectedListener(tbBottomNavigationListener); + + } + } + +} + \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/activity/UpdatesRegisterActivity.java b/opensrp-chw/src/main/java/org/smartregister/chw/activity/UpdatesRegisterActivity.java index 5edd855f8d..a0d1cf2f90 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/activity/UpdatesRegisterActivity.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/activity/UpdatesRegisterActivity.java @@ -60,6 +60,7 @@ protected void registerBottomNavigation() { bottomNavigationHelper = new BottomNavigationHelper(); bottomNavigationView = findViewById(org.smartregister.R.id.bottom_navigation); FamilyRegisterActivity.registerBottomNavigation(bottomNavigationHelper, bottomNavigationView, this); + bottomNavigationView.getMenu().removeItem(org.smartregister.R.id.action_register); } @Override diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/adapter/ChwSectionsPagerAdapter.java b/opensrp-chw/src/main/java/org/smartregister/chw/adapter/ChwSectionsPagerAdapter.java new file mode 100644 index 0000000000..71ffe4c3f9 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/adapter/ChwSectionsPagerAdapter.java @@ -0,0 +1,62 @@ +package org.smartregister.chw.adapter; + +import android.content.Context; + +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; +import androidx.fragment.app.FragmentPagerAdapter; + +import org.smartregister.chw.core.R; +import org.smartregister.chw.core.fragment.DailyTalliesFragment; +import org.smartregister.chw.core.fragment.DraftMonthlyFragment; +import org.smartregister.chw.core.fragment.SentMonthlyFragment; + +/** + * A {@link FragmentPagerAdapter} that returns a fragment corresponding to + * one of the sections/tabs/pages. + */ +public class ChwSectionsPagerAdapter extends FragmentPagerAdapter { + private Context context; + + public ChwSectionsPagerAdapter(FragmentManager fm, Context context) { + super(fm); + this.context = context; + } + + @Override + public Fragment getItem(int position) { + // getItem is called to instantiate the fragment for the given page. + // Return a PlaceholderFragment (defined as a static inner class below). + switch (position) { + case 0: + return DailyTalliesFragment.newInstance(); + case 1: + return DraftMonthlyFragment.newInstance(); + case 2: + return SentMonthlyFragment.newInstance(); + default: + break; + } + return null; + } + + @Override + public int getCount() { + return 3; + } + + @Override + public CharSequence getPageTitle(int position) { + switch (position) { + case 0: + return context.getString(R.string.hia2_daily_tallies); + case 1: + return context.getString(R.string.hia2_draft_monthly); + case 2: + return context.getString(R.string.hia2_sent_monthly); + default: + break; + } + return null; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/adapter/SbccRegisterAdapter.java b/opensrp-chw/src/main/java/org/smartregister/chw/adapter/SbccRegisterAdapter.java new file mode 100644 index 0000000000..491a99ce1e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/adapter/SbccRegisterAdapter.java @@ -0,0 +1,71 @@ +package org.smartregister.chw.adapter; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.model.SbccSessionModel; + +import java.util.List; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +public class SbccRegisterAdapter extends RecyclerView.Adapter { + private static Context context; + private final List sbccSessionModels; + + + public SbccRegisterAdapter(List sbccSessionModels, Context context) { + this.sbccSessionModels = sbccSessionModels; + SbccRegisterAdapter.context = context; + } + + @NonNull + @Override + public SbccViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { + View followupLayout = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sbcc_session_card_view, viewGroup, false); + return new SbccViewHolder(followupLayout); + } + + @Override + public void onBindViewHolder(@NonNull SbccViewHolder holder, int position) { + SbccSessionModel sbccSessionModel = sbccSessionModels.get(position); + holder.bindData(sbccSessionModel); + } + + + @Override + public int getItemCount() { + return sbccSessionModels.size(); + } + + protected static class SbccViewHolder extends RecyclerView.ViewHolder { + public TextView sbccSessionDate; + public TextView sbccSessionParticipants; + public TextView sbccSessionLocation; + + public SbccViewHolder(@NonNull View itemView) { + super(itemView); + } + + public void bindData(SbccSessionModel sbccSessionModel) { + sbccSessionDate = itemView.findViewById(R.id.sbcc_session_date); + sbccSessionParticipants = itemView.findViewById(R.id.sbcc_session_participants); + sbccSessionLocation = itemView.findViewById(R.id.sbcc_session_location); + + sbccSessionDate.setText(context.getString(R.string.sbcc_session_date, sbccSessionModel.getSessionDate())); + sbccSessionParticipants.setText(context.getString(R.string.sbcc_participants, sbccSessionModel.getSessionParticipants())); + if (sbccSessionModel.getSessionLocation().equalsIgnoreCase("facility")) { + sbccSessionLocation.setText(context.getString(R.string.sbcc_location, itemView.getContext().getString(R.string.sbcc_session_location_facility))); + } else if (sbccSessionModel.getSessionLocation().equalsIgnoreCase("community")) { + sbccSessionLocation.setText(context.getString(R.string.sbcc_location, itemView.getContext().getString(R.string.sbcc_session_location_community))); + } else { + sbccSessionLocation.setText(context.getString(R.string.sbcc_location, sbccSessionModel.getSessionLocation())); + } + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwApplication.java b/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwApplication.java index 73c203c49b..480a8beb58 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwApplication.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwApplication.java @@ -24,38 +24,54 @@ import org.smartregister.CoreLibrary; import org.smartregister.P2POptions; import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.activity.AgywRegisterActivity; import org.smartregister.chw.activity.AllClientsRegisterActivity; import org.smartregister.chw.activity.AncRegisterActivity; +import org.smartregister.chw.activity.CdpRegisterActivity; import org.smartregister.chw.activity.ChildRegisterActivity; import org.smartregister.chw.activity.FamilyProfileActivity; import org.smartregister.chw.activity.FamilyRegisterActivity; import org.smartregister.chw.activity.FpRegisterActivity; +import org.smartregister.chw.activity.HivIndexContactsContactsRegisterActivity; +import org.smartregister.chw.activity.HivRegisterActivity; +import org.smartregister.chw.activity.HivstRegisterActivity; +import org.smartregister.chw.activity.KvpPrEPRegisterActivity; +import org.smartregister.chw.activity.LTFURegisterActivity; import org.smartregister.chw.activity.LoginActivity; import org.smartregister.chw.activity.MalariaRegisterActivity; +import org.smartregister.chw.activity.MotherChampionRegisterActivity; import org.smartregister.chw.activity.PncRegisterActivity; import org.smartregister.chw.activity.ReferralRegisterActivity; +import org.smartregister.chw.activity.TbRegisterActivity; import org.smartregister.chw.activity.UpdatesRegisterActivity; +import org.smartregister.chw.agyw.AGYWLibrary; import org.smartregister.chw.anc.AncLibrary; import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.cdp.CdpLibrary; import org.smartregister.chw.configs.AllClientsRegisterRowOptions; import org.smartregister.chw.core.application.CoreChwApplication; import org.smartregister.chw.core.custom_views.NavigationMenu; import org.smartregister.chw.core.loggers.CrashlyticsTree; -import org.smartregister.chw.core.provider.CoreAllClientsRegisterQueryProvider; import org.smartregister.chw.core.service.CoreAuthorizationService; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.core.utils.FormUtils; import org.smartregister.chw.custom_view.NavigationMenuFlv; import org.smartregister.chw.fp.FpLibrary; +import org.smartregister.chw.hiv.HivLibrary; +import org.smartregister.chw.hivst.HivstLibrary; import org.smartregister.chw.job.ChwJobCreator; +import org.smartregister.chw.kvp.KvpLibrary; import org.smartregister.chw.malaria.MalariaLibrary; import org.smartregister.chw.model.NavigationModelFlv; +import org.smartregister.chw.pmtct.PmtctLibrary; import org.smartregister.chw.pnc.PncLibrary; +import org.smartregister.chw.provider.ChwAllClientsRegisterQueryProvider; import org.smartregister.chw.referral.ReferralLibrary; import org.smartregister.chw.repository.ChwRepository; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; import org.smartregister.chw.service.ChildAlertService; import org.smartregister.chw.sync.ChwClientProcessor; +import org.smartregister.chw.tb.TbLibrary; import org.smartregister.chw.util.ChwLocationBasedClassifier; import org.smartregister.chw.util.FailSafeRecalledID; import org.smartregister.chw.util.FileUtils; @@ -246,14 +262,46 @@ private void initializeLibraries() { ReferralLibrary.getInstance().setDatabaseVersion(BuildConfig.DATABASE_VERSION); } + if (hasHIV()) { + //Setup hiv library + HivLibrary.init(this); + HivLibrary.getInstance().setAppVersion(BuildConfig.VERSION_CODE); + HivLibrary.getInstance().setDatabaseVersion(BuildConfig.DATABASE_VERSION); + } + + if (hasTB()) { + //Setup tb library + TbLibrary.init(this); + TbLibrary.getInstance().setAppVersion(BuildConfig.VERSION_CODE); + TbLibrary.getInstance().setDatabaseVersion(BuildConfig.DATABASE_VERSION); + } + + if (hasPmtct()) { + //Setup pmtct library + PmtctLibrary.init(context, getRepository(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION); + } + + if(flavor.hasKvp()){ + KvpLibrary.init(context, getRepository(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION); + } + + HivstLibrary.init(context, getRepository(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION); + + if (flavor.hasAGYW()) { + //setup agyw lib + AGYWLibrary.init(context, getRepository(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION); + } + OpdLibrary.init(context, getRepository(), - new OpdConfiguration.Builder(CoreAllClientsRegisterQueryProvider.class) + new OpdConfiguration.Builder(ChwAllClientsRegisterQueryProvider.class) .setBottomNavigationEnabled(true) .setOpdRegisterRowOptions(AllClientsRegisterRowOptions.class) .build(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION ); + CdpLibrary.init(context, getRepository(), BuildConfig.VERSION_CODE, BuildConfig.DATABASE_VERSION); + SyncStatusBroadcastReceiver.init(this); LocationHelper.init(new ArrayList<>(Arrays.asList(BuildConfig.DEBUG ? BuildConfig.ALLOWED_LOCATION_LEVELS_DEBUG : BuildConfig.ALLOWED_LOCATION_LEVELS)), BuildConfig.DEBUG ? BuildConfig.DEFAULT_LOCATION_DEBUG : BuildConfig.DEFAULT_LOCATION); @@ -263,7 +311,7 @@ private void initializeLibraries() { // Set display date format for date pickers in native forms Form form = new Form(); - form.setDatePickerDisplayFormat("dd MMM yyyy"); + form.setDatePickerDisplayFormat("dd-MM-yyyy"); NativeFormLibrary.getInstance().setClientFormDao(CoreLibrary.getInstance().context().getClientFormRepository()); } @@ -318,15 +366,27 @@ public Map getRegisteredActivities() { registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.FAMILY_REGISTER_ACTIVITY, FamilyRegisterActivity.class); registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.CHILD_REGISTER_ACTIVITY, ChildRegisterActivity.class); registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.PNC_REGISTER_ACTIVITY, PncRegisterActivity.class); - registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.MALARIA_REGISTER_ACTIVITY, MalariaRegisterActivity.class); if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.REFERRALS_REGISTER_ACTIVITY, ReferralRegisterActivity.class); } if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH && BuildConfig.BUILD_FOR_BORESHA_AFYA_SOUTH) { registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.ALL_CLIENTS_REGISTERED_ACTIVITY, AllClientsRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.HIV_REGISTER_ACTIVITY, HivRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.HIV_INDEX_REGISTER_ACTIVITY, HivIndexContactsContactsRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.LTFU_REFERRALS_REGISTER_ACTIVITY, LTFURegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.HIV_SELF_TESTING_REGISTER_ACTIVITY, HivstRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.TB_REGISTER_ACTIVITY, TbRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.CDP_REGISTER_ACTIVITY, CdpRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.KVP_PrEP_REGISTER_ACTIVITY, KvpPrEPRegisterActivity.class); } + + + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.MALARIA_REGISTER_ACTIVITY, MalariaRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.FP_REGISTER_ACTIVITY, FpRegisterActivity.class); registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.FP_REGISTER_ACTIVITY, FpRegisterActivity.class); registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.UPDATES_REGISTER_ACTIVITY, UpdatesRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.MOTHER_CHAMPION_ACTIVITY, MotherChampionRegisterActivity.class); + registeredActivities.put(CoreConstants.REGISTERED_ACTIVITIES.AGYW_REGISTER_ACTIVITY, AgywRegisterActivity.class); return registeredActivities; } @@ -353,6 +413,19 @@ public boolean hasReferrals() { return flavor.hasReferrals(); } + public boolean hasHIV() { + return flavor.hasHIV(); + } + + public boolean hasTB() { + return flavor.hasTB(); + } + + + public boolean hasPmtct() { + return flavor.hasPmtct(); + } + @Subscribe(threadMode = ThreadMode.MAIN) public void onVisitEvent(Visit visit) { if (visit != null) { @@ -428,6 +501,12 @@ public interface Flavor { boolean hasJobAidsVitaminAGraph(); + boolean hasHIV(); + + boolean hasTB(); + + boolean hasPmtct(); + boolean hasJobAidsDewormingGraph(); boolean hasChildrenMNPSupplementationGraph(); @@ -480,6 +559,14 @@ public interface Flavor { boolean hasEventDateOnFamilyProfile(); + boolean hasCdp(); + + boolean hasHIVST(); + + boolean hasKvp(); + + boolean hasAGYW(); + String[] getFTSTables(); Map getFTSSearchMap(); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwSyncConfiguration.java b/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwSyncConfiguration.java index 66dc50d0b8..aef8526ae4 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwSyncConfiguration.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/application/ChwSyncConfiguration.java @@ -1,18 +1,20 @@ package org.smartregister.chw.application; -import com.google.common.collect.ImmutableList; - import org.smartregister.SyncConfiguration; import org.smartregister.SyncFilter; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.core.utils.Utils; +import java.util.Arrays; import java.util.List; /** * Created by samuelgithengi on 10/19/18. */ public class ChwSyncConfiguration extends SyncConfiguration { + private int connectTimeout = 900000; + private int readTimeout = 900000; + @Override public int getSyncMaxRetries() { return BuildConfig.MAX_SYNC_RETRIES; @@ -65,11 +67,21 @@ public boolean isSyncUsingPost() { @Override public List getSynchronizedLocationTags() { - return ImmutableList.of("MOH Jhpiego Facility Name", "Health Facility", "Facility"); + return Arrays.asList("MOH Jhpiego Facility Name", "Health Facility", "Facility"); } @Override public String getTopAllowedLocationLevel() { - return "District"; + return "Council"; + } + + @Override + public int getReadTimeout() { + return connectTimeout; + } + + @Override + public int getConnectTimeout() { + return readTimeout; } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/application/DefaultChwApplicationFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/application/DefaultChwApplicationFlv.java index c4c1374fbb..d9e69a5a4e 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/application/DefaultChwApplicationFlv.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/application/DefaultChwApplicationFlv.java @@ -70,12 +70,12 @@ public boolean hasRoutineVisit() { @Override public boolean hasServiceReport() { - return false; + return true; } @Override public boolean hasStockUsageReport() { - return false; + return true; } @Override @@ -85,7 +85,7 @@ public boolean hasPinLogin() { @Override public boolean hasReports() { - return false; + return true; } @Override @@ -139,7 +139,7 @@ public boolean hasSurname() { @Override public boolean showMyCommunityActivityReport() { - return false; + return true; } @Override @@ -162,11 +162,21 @@ public boolean useThinkMd() { return false; } + @Override + public boolean hasHIV() { + return false; + } + @Override public boolean hasFamilyLocationRow() { return false; } + @Override + public boolean hasTB() { + return false; + } + @Override public boolean usesPregnancyRiskProfileLayout() { return false; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/contract/AllClientsMemberContract.java b/opensrp-chw/src/main/java/org/smartregister/chw/contract/AllClientsMemberContract.java deleted file mode 100644 index 624291076b..0000000000 --- a/opensrp-chw/src/main/java/org/smartregister/chw/contract/AllClientsMemberContract.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.smartregister.chw.contract; - -import org.smartregister.family.contract.FamilyOtherMemberContract; -import org.smartregister.family.contract.FamilyProfileContract; -import org.smartregister.family.domain.FamilyEventClient; - -public interface AllClientsMemberContract { - - interface Model { - FamilyEventClient processJsonForm(String jsonString, String familyBaseEntityId); - } - - interface Presenter { - void updateLocationInfo(String jsonString, String familyBaseEntityId); - - View getView(); - - void refreshProfileView(); - } - - interface Interactor { - void updateLocationInfo(String jsonString, FamilyEventClient familyEventClient, - FamilyProfileContract.InteractorCallBack interactorCallback); - - void updateProfileInfo(String baseEntityId, FamilyOtherMemberContract.InteractorCallBack callback); - } - - interface View { - Presenter getAllClientsMemberPresenter(); - } -} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivIndexContactProfileContract.java b/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivIndexContactProfileContract.java new file mode 100644 index 0000000000..927553118e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivIndexContactProfileContract.java @@ -0,0 +1,9 @@ +package org.smartregister.chw.contract; + +import org.smartregister.chw.core.contract.CoreIndexContactProfileContract; + +public interface HivIndexContactProfileContract extends CoreIndexContactProfileContract { + interface Presenter { + void referToFacility(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivProfileContract.java b/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivProfileContract.java new file mode 100644 index 0000000000..ad9d39a174 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/contract/HivProfileContract.java @@ -0,0 +1,9 @@ +package org.smartregister.chw.contract; + +import org.smartregister.chw.core.contract.CoreHivProfileContract; + +public interface HivProfileContract extends CoreHivProfileContract { + interface Presenter { + void referToFacility(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/contract/TbProfileContract.java b/opensrp-chw/src/main/java/org/smartregister/chw/contract/TbProfileContract.java new file mode 100644 index 0000000000..76f4bc431a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/contract/TbProfileContract.java @@ -0,0 +1,9 @@ +package org.smartregister.chw.contract; + +import org.smartregister.chw.core.contract.CoreTbProfileContract; + +public interface TbProfileContract extends CoreTbProfileContract { + interface Presenter { + void referToFacility(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/DefaultNavigationMenuFlv.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/DefaultNavigationMenuFlv.java index 6699180c2b..16a9b970c8 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/DefaultNavigationMenuFlv.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/DefaultNavigationMenuFlv.java @@ -32,6 +32,11 @@ public boolean hasServiceReport() { return false; } + @Override + public boolean hasCommunityResponders() { + return false; + } + @Override public Intent getStockReportIntent(Activity activity) { @@ -48,11 +53,6 @@ public String childNavigationMenuCountString() { return null; } - @Override - public boolean hasCommunityResponders() { - return false; - } - @Override public Intent getHIA2ReportActivityIntent(Activity activity) { return null; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivFloatingMenu.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivFloatingMenu.java new file mode 100644 index 0000000000..eedc31347b --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivFloatingMenu.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.custom_view; + +import android.content.Context; + +import org.smartregister.chw.core.custom_views.CoreHivFloatingMenu; +import org.smartregister.chw.hiv.domain.HivMemberObject; + +public class HivFloatingMenu extends CoreHivFloatingMenu { + public HivFloatingMenu(Context context, HivMemberObject hivMemberObject) { + super(context, hivMemberObject); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivIndexContactFloatingMenu.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivIndexContactFloatingMenu.java new file mode 100644 index 0000000000..0f74170c80 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/HivIndexContactFloatingMenu.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.custom_view; + +import android.content.Context; + +import org.smartregister.chw.core.custom_views.CoreHivIndexContactFloatingMenu; +import org.smartregister.chw.hiv.domain.HivIndexContactObject; + +public class HivIndexContactFloatingMenu extends CoreHivIndexContactFloatingMenu { + public HivIndexContactFloatingMenu(Context context, HivIndexContactObject hivIndexContactObject) { + super(context, hivIndexContactObject); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/MotherChampionFloatingMenu.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/MotherChampionFloatingMenu.java new file mode 100644 index 0000000000..52eefb6eaf --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/MotherChampionFloatingMenu.java @@ -0,0 +1,114 @@ +package org.smartregister.chw.custom_view; + +import static org.smartregister.chw.core.utils.Utils.redrawWithOption; + +import android.app.Activity; +import android.content.Context; +import android.view.View; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.widget.LinearLayout; +import android.widget.RelativeLayout; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; + +import org.smartregister.chw.core.fragment.FamilyCallDialogFragment; +import org.smartregister.chw.core.listener.OnClickFloatingMenu; +import org.smartregister.chw.pmtct.custom_views.BasePmtctFloatingMenu; +import org.smartregister.chw.pmtct.domain.MemberObject; + +public class MotherChampionFloatingMenu extends BasePmtctFloatingMenu { + public FloatingActionButton fab; + protected View referLayout; + protected View callLayout; + protected RelativeLayout activityMain; + protected boolean isFabMenuOpen = false; + protected LinearLayout menuBar; + protected OnClickFloatingMenu onClickFloatingMenu; + private Animation fabOpen; + private Animation fabClose; + private Animation rotateForward; + private Animation rotateBack; + private MemberObject MEMBER_OBJECT; + + public MotherChampionFloatingMenu(Context context, MemberObject MEMBER_OBJECT) { + super(context, MEMBER_OBJECT); + this.MEMBER_OBJECT = MEMBER_OBJECT; + } + + public void setFloatMenuClickListener(OnClickFloatingMenu onClickFloatingMenu) { + this.onClickFloatingMenu = onClickFloatingMenu; + } + + @Override + protected void initUi() { + inflate(getContext(), org.smartregister.chw.core.R.layout.view_anc_call_woma_floating_menu, this); + fabOpen = AnimationUtils.loadAnimation(getContext(), org.smartregister.chw.core.R.anim.fab_open); + fabClose = AnimationUtils.loadAnimation(getContext(), org.smartregister.chw.core.R.anim.fab_close); + rotateForward = AnimationUtils.loadAnimation(getContext(), org.smartregister.chw.core.R.anim.rotate_forward); + rotateBack = AnimationUtils.loadAnimation(getContext(), org.smartregister.chw.core.R.anim.rotate_back); + + activityMain = findViewById(org.smartregister.chw.core.R.id.activity_main); + menuBar = findViewById(org.smartregister.chw.core.R.id.menu_bar); + + fab = findViewById(org.smartregister.chw.core.R.id.anc_fab); + fab.setOnClickListener(this); + + callLayout = findViewById(org.smartregister.chw.core.R.id.call_layout); + callLayout.setOnClickListener(this); + callLayout.setClickable(false); + + referLayout = findViewById(org.smartregister.chw.core.R.id.refer_to_facility_layout); + referLayout.setOnClickListener(this); + referLayout.setClickable(false); + + menuBar.setVisibility(GONE); + } + + @Override + public void onClick(View view) { + onClickFloatingMenu.onClickMenu(view.getId()); + } + + public void animateFAB() { + if (menuBar.getVisibility() == GONE) { + menuBar.setVisibility(VISIBLE); + } + + if (isFabMenuOpen) { + activityMain.setBackgroundResource(org.smartregister.chw.core.R.color.transparent); + fab.startAnimation(rotateBack); + fab.setImageResource(org.smartregister.chw.core.R.drawable.ic_edit_white); + + callLayout.startAnimation(fabClose); + callLayout.setClickable(false); + + referLayout.startAnimation(fabClose); + referLayout.setClickable(false); + isFabMenuOpen = false; + } else { + activityMain.setBackgroundResource(org.smartregister.chw.core.R.color.grey_tranparent_50); + fab.startAnimation(rotateForward); + fab.setImageResource(org.smartregister.chw.core.R.drawable.ic_input_add); + + callLayout.startAnimation(fabOpen); + callLayout.setClickable(true); + + referLayout.startAnimation(fabOpen); + referLayout.setClickable(true); + isFabMenuOpen = true; + } + } + + public void launchCallWidget() { + FamilyCallDialogFragment.launchDialog((Activity) this.getContext(), MEMBER_OBJECT.getFamilyBaseEntityId()); + } + + public void redraw(boolean hasPhoneNumber) { + redrawWithOption(this, hasPhoneNumber); + } + + public View getCallLayout() { + return callLayout; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/PmtctFloatingMenu.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/PmtctFloatingMenu.java new file mode 100644 index 0000000000..b407f627bc --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/PmtctFloatingMenu.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.custom_view; + +import android.content.Context; + +import org.smartregister.chw.core.custom_views.CorePmtctFloatingMenu; +import org.smartregister.chw.pmtct.domain.MemberObject; + +public class PmtctFloatingMenu extends CorePmtctFloatingMenu { + public PmtctFloatingMenu(Context context, MemberObject MEMBER_OBJECT) { + super(context, MEMBER_OBJECT); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/TbFloatingMenu.java b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/TbFloatingMenu.java new file mode 100644 index 0000000000..c49bd32cd1 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/custom_view/TbFloatingMenu.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.custom_view; + +import android.content.Context; + +import org.smartregister.chw.core.custom_views.CoreTbFloatingMenu; +import org.smartregister.chw.tb.domain.TbMemberObject; + +public class TbFloatingMenu extends CoreTbFloatingMenu { + public TbFloatingMenu(Context context, TbMemberObject tbMemberObject) { + super(context, tbMemberObject); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/AncPartnerDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/AncPartnerDao.java new file mode 100644 index 0000000000..2fbd3de70e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/AncPartnerDao.java @@ -0,0 +1,91 @@ +package org.smartregister.chw.dao; + +import org.smartregister.dao.AbstractDao; + +import java.util.List; + +public class AncPartnerDao extends AbstractDao { + + public static boolean isPartnerRegistered(String referralFormSubmissionId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "partner_base_entity_id"); + + String sql = String.format( + "SELECT partner_base_entity_id FROM %s WHERE referral_form_id = '%s' " + + "AND partner_base_entity_id is not null " + + "AND is_closed = 0", + "ec_anc_partner_community_feedback", + referralFormSubmissionId + ); + + List res = readData(sql, dataMap); + + return res.size() == 1; + } + + + public static boolean isPartnerAlreadyRegistered(String ancReferralFormSubmissionId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "partner_base_entity_id"); + + String sql = "SELECT partner_base_entity_id FROM ec_anc_partners WHERE referral_form_submission_id = '" + ancReferralFormSubmissionId + "' " + + "AND partner_base_entity_id is not null " + + "AND is_closed = 0 LIMIT 1"; + + List res = readData(sql, dataMap); + + if (res != null) + return res.size() == 1; + return false; + } + + public static boolean hasPartnerAgreeForRegistration(String referralFormSubmissionId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "partner_agree_attending_hf"); + + String sql = String.format( + "SELECT partner_agree_attending_hf FROM %s WHERE referral_form_id = '%s' " + + "AND partner_agree_attending_hf is not null " + + "AND is_closed = 0", + "ec_anc_partner_community_feedback", + referralFormSubmissionId + ); + + List res = readData(sql, dataMap); + + if (res.size() > 0) { + return res.get(0).equalsIgnoreCase("yes"); + } + return false; + } + + public static boolean isPartnerFollowedUp(String referralFormSubmissionId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "client_found"); + + String sql = String.format( + "SELECT client_found FROM %s WHERE referral_form_id = '%s' " + + "AND client_found is not null " + + "AND is_closed = 0", + "ec_anc_partner_community_feedback", + referralFormSubmissionId + ); + + List res = readData(sql, dataMap); + + return res.size() > 0; + } + + public static String getFeedbackFormId(String referralFormSubmissionId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "base_entity_id"); + + String sql = String.format( + "SELECT base_entity_id FROM %s WHERE referral_form_id = '%s' " + + "AND base_entity_id is not null " + + "AND is_closed = 0", + "ec_anc_partner_community_feedback", + referralFormSubmissionId + ); + + List res = readData(sql, dataMap); + + return res.size() > 0 ? res.get(0) : ""; + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwAncDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwAncDao.java new file mode 100644 index 0000000000..0944d6577b --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwAncDao.java @@ -0,0 +1,26 @@ +package org.smartregister.chw.dao; + +import org.smartregister.chw.core.dao.AncDao; + +import java.util.List; + +public class ChwAncDao extends AncDao { + + public static boolean isClientHighRisk(String baseEntityId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "medical_surgical_history"); + + String sql = String.format( + "SELECT medical_surgical_history FROM %s WHERE base_entity_id = '%s' " + + "AND medical_surgical_history is not null ", + "ec_anc_hf_data", + baseEntityId + ); + + List res = readData(sql, dataMap); + if (res != null && res.size() != 0 && res.get(0) != null) { + return !res.get(0).equalsIgnoreCase("none"); + } else { + return false; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwCBHSDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwCBHSDao.java new file mode 100644 index 0000000000..2f5fea4c20 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwCBHSDao.java @@ -0,0 +1,93 @@ +package org.smartregister.chw.dao; + +import org.smartregister.dao.AbstractDao; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +import timber.log.Timber; + +public class ChwCBHSDao extends AbstractDao { + public static boolean tbStatusAfterTestingDone(String baseEntityID) { + String sql = "Select client_tb_status_after_testing from ec_cbhs_register where base_entity_id = '" + baseEntityID + "'"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "client_tb_status_after_testing"); + List res = readData(sql, dataMap); + + if (res != null && res.size() > 0 && res.get(0) != null) + return !res.get(0).equalsIgnoreCase("unknown"); + return false; + } + + public static Date getNextVisitDate(String baseEntityId) { + String sql = "Select next_appointment_date from ec_cbhs_followup where entity_id = '" + baseEntityId + "' AND next_appointment_date is not null ORDER BY last_interacted_with DESC LIMIT 1"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "next_appointment_date"); + List res = readData(sql, dataMap); + + if (res != null && res.size() > 0 && res.get(0) != null) { + try { + return new Date(new BigDecimal(res.get(0)).longValue()); + } catch (Exception e) { + //NEEDED FOR THE ISSUE IN SOME TABLETS FAILING TO CREATE A TIMESTAMP + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + try { + return sdf.parse(res.get(0)); + } catch (ParseException parseException) { + Timber.e(parseException); + } + } + } + return null; + } + + public static boolean isDeceased(String baseEntityId) { + String sql = " Select registration_or_followup_status\n" + + " FROM ec_cbhs_followup ecf\n" + + " INNER JOIN ec_family_member efm on ecf.entity_id = efm.base_entity_id\n" + + " WHERE efm.dod IS NULL AND ecf.entity_id = '" + baseEntityId + "'" + + " ORDER BY ecf.last_interacted_with DESC\n" + + " LIMIT 1"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "registration_or_followup_status"); + List res = readData(sql, dataMap); + + if (res != null && res.size() > 0 && res.get(0) != null) { + return res.get(0).equals("deceased"); + } + return false; + } + + public static boolean completedServiceOrNoLongerContinuingWithService(String baseEntityId) { + String sql = " Select registration_or_followup_status\n" + + " FROM ec_cbhs_followup ecf\n" + + " WHERE ecf.is_closed = 0 AND ecf.entity_id = '" + baseEntityId + "'" + + " ORDER BY ecf.last_interacted_with DESC\n" + + " LIMIT 1"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "registration_or_followup_status"); + List res = readData(sql, dataMap); + + if (res != null && res.size() > 0 && res.get(0) != null) { + return res.get(0).equals("deceased") || res.get(0).equals("client_has_absconded") || res.get(0).equals("completed_and_qualified_from_the_services") || res.get(0).equals("client_relocated_to_another_location"); + } + return false; + } + + public static boolean hasFollowupVisits(String baseEntityId) { + String sql = " Select ecf.entity_id\n" + + " FROM ec_cbhs_followup ecf\n" + + " WHERE ecf.entity_id = '" + baseEntityId + "'" + + " ORDER BY ecf.last_interacted_with DESC\n" + + " LIMIT 1"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "entity_id"); + List res = readData(sql, dataMap); + + return res != null && res.size() > 0; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwHivOutcomeDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwHivOutcomeDao.java new file mode 100644 index 0000000000..d7deec88a1 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwHivOutcomeDao.java @@ -0,0 +1,99 @@ +package org.smartregister.chw.dao; + +import org.smartregister.dao.AbstractDao; + +import java.util.List; + +public class ChwHivOutcomeDao extends AbstractDao { + + public static String servicesProvided(String baseEntityID, long timestamp) { + String sql = "SELECT action_taken, test_results\n" + + "FROM ec_hiv_outcome\n" + + "WHERE entity_id = '" + baseEntityID + "'\n" + + "AND date(visit_date) = date(substr(strftime('%Y-%m-%d', datetime(" + timestamp + " / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(" + timestamp + "/ 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || substr(strftime('%Y-%m-%d', datetime(" + timestamp + "/ 1000, 'unixepoch', 'localtime')), 9, 2))\n" + + "ORDER BY visit_date DESC\n" + + "LIMIT 1;"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "action_taken"); + List res = readData(sql, dataMap); + if (res != null && res.size() > 0 && res.get(0) != null) + return res.get(0); + return null; + } + + public static String hivStatus(String baseEntityID, long timestamp) { + String sql = "SELECT test_results\n" + + "FROM ec_hiv_outcome\n" + + "WHERE entity_id = '" + baseEntityID + "'\n" + + "AND date(visit_date) = date(substr(strftime('%Y-%m-%d', datetime(" + timestamp + " / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(" + timestamp + "/ 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || substr(strftime('%Y-%m-%d', datetime(" + timestamp + "/ 1000, 'unixepoch', 'localtime')), 9, 2))\n" + + "ORDER BY visit_date DESC\n" + + "LIMIT 1;"; + + DataMap dataMap = cursor -> getCursorValue(cursor, "test_results"); + List res = readData(sql, dataMap); + if (res != null && res.size() > 0 && res.get(0) != null) + return res.get(0); + return null; + } + + public static String hivEnrolledToCTC(String forEntity, long millis) { + String sql = "SELECT enrolled_to_clinic\n" + + "FROM ec_hiv_outcome\n" + + "WHERE entity_id = '" + forEntity + "'\n" + + "AND date(visit_date) = date(substr(strftime('%Y-%m-%d', datetime(" + millis + " / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 9, 2))\n" + + "ORDER BY visit_date DESC\n" + + "LIMIT 1;"; + DataMap dataMap = cursor -> getCursorValue(cursor, "enrolled_to_clinic"); + List res = readData(sql, dataMap); + if (res != null && res.size() > 0 && res.get(0) != null) + return res.get(0); + return null; + } + + public static String hivCommentsFromHF(String forEntity, long millis) { + String sql = "SELECT comment\n" + + "FROM ec_hiv_outcome\n" + + "WHERE entity_id = '" + forEntity + "'\n" + + "AND date(visit_date) = date(substr(strftime('%Y-%m-%d', datetime(" + millis + " / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 9, 2))\n" + + "ORDER BY visit_date DESC\n" + + "LIMIT 1;"; + DataMap dataMap = cursor -> getCursorValue(cursor, "comment"); + List res = readData(sql, dataMap); + if (res != null && res.size() > 0 && res.get(0) != null) + return res.get(0); + return null; + } + + public static String ctcNumber(String forEntity, long millis) { + String sql = "SELECT ctc_number\n" + + "FROM ec_hiv_outcome\n" + + "WHERE entity_id = '" + forEntity + "'\n" + + "AND date(visit_date) = date(substr(strftime('%Y-%m-%d', datetime(" + millis + " / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || substr(strftime('%Y-%m-%d', datetime(" + millis + "/ 1000, 'unixepoch', 'localtime')), 9, 2))\n" + + "ORDER BY visit_date DESC\n" + + "LIMIT 1;"; + DataMap dataMap = cursor -> getCursorValue(cursor, "ctc_number"); + List res = readData(sql, dataMap); + if (res != null && res.size() > 0 && res.get(0) != null) + return res.get(0); + return null; + } + + public static String reasonsForNotEnrolling(String forEntity, long millis) { + return null; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwKvpDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwKvpDao.java new file mode 100644 index 0000000000..6fb5b1c90a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwKvpDao.java @@ -0,0 +1,20 @@ +package org.smartregister.chw.dao; + +import org.smartregister.chw.kvp.dao.KvpDao; + +import java.util.List; + +public class ChwKvpDao extends KvpDao { + public static String getDominantKVPGroup(String baseEntityId) { + String sql = "SELECT client_group FROM ec_kvp_prep_register p " + + " WHERE p.base_entity_id = '" + baseEntityId + "' AND p.is_closed = 0 "; + + DataMap dataMap = cursor -> getCursorValue(cursor, "client_group"); + + List res = readData(sql, dataMap); + if (res != null && res.size() != 0 && res.get(0) != null) { + return res.get(0); + } + return ""; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwPNCDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwPNCDao.java index e8ee19e45d..bc02d3aaa4 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwPNCDao.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwPNCDao.java @@ -3,6 +3,7 @@ import net.sqlcipher.database.SQLiteDatabase; import org.jetbrains.annotations.Nullable; +import org.smartregister.chw.anc.domain.MemberObject; import org.smartregister.chw.anc.domain.VisitDetail; import org.smartregister.chw.domain.PNCHealthFacilityVisitSummary; import org.smartregister.dao.AbstractDao; @@ -69,6 +70,72 @@ public class ChwPNCDao extends AbstractDao { return details; } + public static List getPncMembersWithMoreThan42Days() { + String sql = "select m.base_entity_id,\n" + + " m.unique_id,\n" + + " m.relational_id,\n" + + " m.dob,\n" + + " m.first_name,\n" + + " m.middle_name,\n" + + " m.last_name,\n" + + " m.gender,\n" + + " m.phone_number,\n" + + " m.other_phone_number,\n" + + " f.first_name family_name,\n" + + " f.primary_caregiver,\n" + + " f.family_head,\n" + + " fh.first_name family_head_first_name,\n" + + " fh.middle_name family_head_middle_name,\n" + + " fh.last_name family_head_last_name,\n" + + " fh.phone_number family_head_phone_number,\n" + + " f.village_town,\n" + + " epo.delivery_date\n" + + "from ec_family_member m\n" + + " inner join ec_family f on m.relational_id = f.base_entity_id\n" + + " inner join ec_pregnancy_outcome epo on m.base_entity_id = epo.base_entity_id\n" + + " left join ec_family_member fh on fh.base_entity_id = f.family_head\n" + + "where cast(julianday(datetime('now')) - julianday(datetime(substr(epo.delivery_date, 7,4)\n" + + " || '-' || substr(epo.delivery_date, 4,2) || '-' || substr(epo.delivery_date, 1,2))) as integer) >= 43\n" + + " AND epo.is_closed = 0 "; + + DataMap dataMap = cursor -> { + MemberObject memberObject = new MemberObject(); + memberObject.setLastMenstrualPeriod(getCursorValue(cursor, "last_menstrual_period")); + memberObject.setChwMemberId(getCursorValue(cursor, "unique_id", "")); + memberObject.setBaseEntityId(getCursorValue(cursor, "base_entity_id", "")); + memberObject.setFamilyBaseEntityId(getCursorValue(cursor, "relational_id", "")); + memberObject.setFamilyHead(getCursorValue(cursor, "family_head", "")); + + String familyHeadName = getCursorValue(cursor, "family_head_first_name", "") + " " + + getCursorValue(cursor, "family_head_middle_name", ""); + + familyHeadName = (familyHeadName.trim() + " " + getCursorValue(cursor, "family_head_last_name", "")).trim(); + + memberObject.setFamilyHeadName(familyHeadName); + memberObject.setFamilyHeadPhoneNumber(getCursorValue(cursor, "family_head_phone_number", "")); + memberObject.setPrimaryCareGiver(getCursorValue(cursor, "primary_caregiver")); + memberObject.setFamilyName(getCursorValue(cursor, "family_name", "")); + memberObject.setLastContactVisit(getCursorValue(cursor, "last_contact_visit")); + memberObject.setLastInteractedWith(getCursorValue(cursor, "last_interacted_with")); + memberObject.setFirstName(getCursorValue(cursor, "first_name", "")); + memberObject.setMiddleName(getCursorValue(cursor, "middle_name", "")); + memberObject.setLastName(getCursorValue(cursor, "last_name", "")); + memberObject.setDob(getCursorValue(cursor, "dob")); + memberObject.setPhoneNumber(getCursorValue(cursor, "phone_number", "")); + memberObject.setConfirmedContacts(getCursorIntValue(cursor, "confirmed_visits", 0)); + memberObject.setDateCreated(getCursorValue(cursor, "date_created")); + memberObject.setAddress(getCursorValue(cursor, "village_town")); + memberObject.setHasAncCard(getCursorValue(cursor, "has_anc_card", "")); + + return memberObject; + }; + List res = readData(sql, dataMap); + if (res == null || res.size() == 0) + return null; + + return res; + } + public interface Flavor { diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwSbccDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwSbccDao.java new file mode 100644 index 0000000000..b4e3196779 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ChwSbccDao.java @@ -0,0 +1,31 @@ +package org.smartregister.chw.dao; + +import org.smartregister.chw.core.dao.SbccDao; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.model.SbccSessionModel; +import org.smartregister.chw.util.Constants; +import org.smartregister.family.util.DBConstants; + +import java.util.List; + +public class ChwSbccDao extends SbccDao { + + public static List getSbccSessions() { + String sql = "SELECT * FROM " + Constants.TableName.SBCC; + + DataMap dataMap = cursor -> { + SbccSessionModel sbccSessionModel = new SbccSessionModel(); + sbccSessionModel.setSessionId(cursor.getString(cursor.getColumnIndex(DBConstants.KEY.BASE_ENTITY_ID))); + sbccSessionModel.setSessionParticipants(cursor.getString(cursor.getColumnIndex(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.SBCC_PARTICIPANTS_NUMBER))); + sbccSessionModel.setSessionLocation(cursor.getString(cursor.getColumnIndex(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.SBCC_LOCATION_TYPE))); + sbccSessionModel.setSessionDate(cursor.getString(cursor.getColumnIndex(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.SBCC_DATE))); + + return sbccSessionModel; + }; + + List res = readData(sql, dataMap); + if (res == null || res.size() == 0) + return null; + return res; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/MotherChampionDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/MotherChampionDao.java new file mode 100644 index 0000000000..ef76b21e40 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/MotherChampionDao.java @@ -0,0 +1,70 @@ +package org.smartregister.chw.dao; + +import org.smartregister.chw.pmtct.domain.MemberObject; +import org.smartregister.dao.AbstractDao; + +import java.util.List; + +public class MotherChampionDao extends AbstractDao { + public static MemberObject getMember(String baseEntityID) { + String sql = "select m.base_entity_id , m.unique_id , m.relational_id as family_relational_id , m.dob , m.first_name , m.middle_name , m.last_name , m.gender , m.phone_number , m.other_phone_number , f.first_name family_name ,f.primary_caregiver , f.family_head , f.village_town ,fh.first_name family_head_first_name , fh.middle_name family_head_middle_name , fh.last_name family_head_last_name, fh.phone_number family_head_phone_number , ancr.is_closed anc_is_closed, pncr.is_closed pnc_is_closed, pcg.first_name pcg_first_name , pcg.last_name pcg_last_name , pcg.middle_name pcg_middle_name , pcg.phone_number pcg_phone_number , mr.* from ec_family_member m inner join ec_family f on m.relational_id = f.base_entity_id inner join ec_mother_champion mr on mr.base_entity_id = m.base_entity_id left join ec_family_member fh on fh.base_entity_id = f.family_head left join ec_family_member pcg on pcg.base_entity_id = f.primary_caregiver left join ec_anc_register ancr on ancr.base_entity_id = m.base_entity_id left join ec_pregnancy_outcome pncr on pncr.base_entity_id = m.base_entity_id where m.base_entity_id ='" + baseEntityID + "' "; + + + DataMap dataMap = cursor -> { + MemberObject memberObject = new MemberObject(); + + memberObject.setFirstName(getCursorValue(cursor, "first_name", "")); + memberObject.setMiddleName(getCursorValue(cursor, "middle_name", "")); + memberObject.setLastName(getCursorValue(cursor, "last_name", "")); + memberObject.setAddress(getCursorValue(cursor, "village_town")); + memberObject.setGender(getCursorValue(cursor, "gender")); + memberObject.setUniqueId(getCursorValue(cursor, "unique_id", "")); + memberObject.setAge(getCursorValue(cursor, "dob")); + memberObject.setFamilyBaseEntityId(getCursorValue(cursor, "family_relational_id", "")); + memberObject.setRelationalId(getCursorValue(cursor, "family_relational_id", "")); + memberObject.setPrimaryCareGiver(getCursorValue(cursor, "primary_caregiver")); + memberObject.setFamilyName(getCursorValue(cursor, "family_name", "")); + memberObject.setPhoneNumber(getCursorValue(cursor, "phone_number", "")); + memberObject.setBaseEntityId(getCursorValue(cursor, "base_entity_id", "")); + memberObject.setFamilyHead(getCursorValue(cursor, "family_head", "")); + memberObject.setFamilyHeadPhoneNumber(getCursorValue(cursor, "pcg_phone_number", "")); + memberObject.setFamilyHeadPhoneNumber(getCursorValue(cursor, "family_head_phone_number", "")); + memberObject.setAncMember(getCursorValue(cursor, "anc_is_closed", "")); + memberObject.setPncMember(getCursorValue(cursor, "pnc_is_closed", "")); + + String familyHeadName = getCursorValue(cursor, "family_head_first_name", "") + " " + + getCursorValue(cursor, "family_head_middle_name", ""); + + familyHeadName = + (familyHeadName.trim() + " " + getCursorValue(cursor, "family_head_last_name", "")).trim(); + memberObject.setFamilyHeadName(familyHeadName); + + String familyPcgName = getCursorValue(cursor, "pcg_first_name", "") + " " + + getCursorValue(cursor, "pcg_middle_name", ""); + + familyPcgName = + (familyPcgName.trim() + " " + getCursorValue(cursor, "pcg_last_name", "")).trim(); + memberObject.setPrimaryCareGiverName(familyPcgName); + + return memberObject; + }; + + List res = readData(sql, dataMap); + if (res == null || res.size() != 1) + return null; + + return res.get(0); + } + + public static int getVisitNumber(String baseEntityID) { + String sql = "SELECT visit_number FROM ec_mother_champion_followup WHERE entity_id='" + baseEntityID + "' ORDER BY visit_number DESC LIMIT 1"; + DataMap map = cursor -> getCursorIntValue(cursor, "visit_number"); + List res = readData(sql, map); + + if (res != null && res.size() > 0 && res.get(0) != null) { + return res.get(0) + 1; + } else + return 0; + + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/PersonDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/PersonDao.java index 326c9d5184..e56930abc4 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dao/PersonDao.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/PersonDao.java @@ -2,6 +2,7 @@ import org.smartregister.chw.core.domain.Person; import org.smartregister.chw.domain.PncBaby; +import org.smartregister.chw.pnc.util.Constants; import org.smartregister.dao.AbstractDao; import java.text.ParseException; @@ -52,7 +53,7 @@ public static List getMothersPNCBabies(String baseEntityID) { "inner join ec_family_member on ec_child.base_entity_id = ec_family_member.base_entity_id " + "where ec_child.mother_entity_id = '" + baseEntityID + "'" + " COLLATE NOCASE " + "and ec_child.date_removed is null and ec_family_member.date_removed is null " + - "and date(ec_child.dob, '+28 days') >= date() " + + "and date(ec_child.dob, '+42 days') >= date() " + "order by ec_family_member.first_name ASC, ec_family_member.last_name , ec_family_member.middle_name "; DataMap dataMap = c -> { @@ -68,7 +69,8 @@ public static List getMothersPNCBabies(String baseEntityID) { getCursorValue(c, "last_name"), getCursorValue(c, "middle_name"), dob, - getCursorValue(c,"low_birth_weight") + getCursorValue(c, "low_birth_weight"), + getCursorValue(c, Constants.KEY.GENDER) ); }; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/PmtctDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/PmtctDao.java new file mode 100644 index 0000000000..ebc6aad7d3 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/PmtctDao.java @@ -0,0 +1,95 @@ +package org.smartregister.chw.dao; + +import org.smartregister.chw.domain.PmtctReferralMemberObject; + +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Locale; + +public class PmtctDao extends org.smartregister.chw.pmtct.dao.PmtctDao { + public static PmtctReferralMemberObject getPmtctReferralMemberObject(String baseEntityId) { + String sql = "select m.base_entity_id,\n" + + " m.unique_id,\n" + + " m.relational_id,\n" + + " m.dob,\n" + + " m.first_name,\n" + + " m.middle_name,\n" + + " m.last_name,\n" + + " m.gender,\n" + + " m.phone_number,\n" + + " m.other_phone_number,\n" + + " f.first_name family_name,\n" + + " f.primary_caregiver,\n" + + " f.family_head,\n" + + " f.village_town,\n" + + " fh.first_name family_head_first_name,\n" + + " fh.middle_name family_head_middle_name,\n" + + " fh.last_name family_head_last_name,\n" + + " fh.phone_number family_head_phone_number,\n" + + " ancr.is_closed anc_is_closed,\n" + + " pncr.is_closed pnc_is_closed,\n" + + " pcg.first_name pcg_first_name,\n" + + " pcg.last_name pcg_last_name,\n" + + " pcg.middle_name pcg_middle_name,\n" + + " pcg.phone_number pcg_phone_number,\n" + + " mr.*\n" + + "from ec_family_member m\n" + + " inner join ec_family f on m.relational_id = f.base_entity_id\n" + + " inner join ec_pmtct_community_followup mr on mr.entity_id = m.base_entity_id\n" + + " left join ec_family_member fh on fh.base_entity_id = f.family_head\n" + + " left join ec_family_member pcg on pcg.base_entity_id = f.primary_caregiver\n" + + " left join ec_anc_register ancr on ancr.base_entity_id = m.base_entity_id\n" + + " left join ec_pregnancy_outcome pncr on pncr.base_entity_id = m.base_entity_id\n" + + " where mr.base_entity_id ='" + baseEntityId + "' "; + SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()); + + DataMap dataMap = cursor -> { + PmtctReferralMemberObject memberObject = new PmtctReferralMemberObject(); + + memberObject.setFirstName(getCursorValue(cursor, "first_name", "")); + memberObject.setMiddleName(getCursorValue(cursor, "middle_name", "")); + memberObject.setLastName(getCursorValue(cursor, "last_name", "")); + memberObject.setAddress(getCursorValue(cursor, "village_town")); + memberObject.setGender(getCursorValue(cursor, "gender")); + memberObject.setUniqueId(getCursorValue(cursor, "unique_id", "")); + memberObject.setAge(getCursorValue(cursor, "dob")); + memberObject.setFamilyBaseEntityId(getCursorValue(cursor, "relational_id", "")); + memberObject.setRelationalId(getCursorValue(cursor, "relational_id", "")); + memberObject.setPrimaryCareGiver(getCursorValue(cursor, "primary_caregiver")); + memberObject.setFamilyName(getCursorValue(cursor, "family_name", "")); + memberObject.setPhoneNumber(getCursorValue(cursor, "phone_number", "")); + memberObject.setBaseEntityId(getCursorValue(cursor, "entity_id", "")); + memberObject.setFamilyHead(getCursorValue(cursor, "family_head", "")); + memberObject.setFamilyHeadPhoneNumber(getCursorValue(cursor, "pcg_phone_number", "")); + memberObject.setFamilyHeadPhoneNumber(getCursorValue(cursor, "family_head_phone_number", "")); + + memberObject.setPmtctCommunityReferralDate(getCursorValueAsDate(cursor, "pmtct_community_referral_date", getNativeFormsDateFormat())); + memberObject.setLastFacilityVisitDate(getCursorValueAsDate(cursor, "last_client_visit_date", getNativeFormsDateFormat())); + memberObject.setReasonsForIssuingCommunityFollowupReferral(getCursorValue(cursor, "reasons_for_issuing_community_referral", "")); + memberObject.setComments(getCursorValue(cursor, "comment", "")); + memberObject.setChildName(getCursorValue(cursor, "child_name", "")); + + String familyHeadName = getCursorValue(cursor, "family_head_first_name", "") + " " + + getCursorValue(cursor, "family_head_middle_name", ""); + + familyHeadName = + (familyHeadName.trim() + " " + getCursorValue(cursor, "family_head_last_name", "")).trim(); + memberObject.setFamilyHeadName(familyHeadName); + + String familyPcgName = getCursorValue(cursor, "pcg_first_name", "") + " " + + getCursorValue(cursor, "pcg_middle_name", ""); + + familyPcgName = + (familyPcgName.trim() + " " + getCursorValue(cursor, "pcg_last_name", "")).trim(); + memberObject.setPrimaryCareGiverName(familyPcgName); + + return memberObject; + }; + + List res = readData(sql, dataMap); + if (res == null || res.size() != 1) + return null; + + return res.get(0); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReferralDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReferralDao.java new file mode 100644 index 0000000000..39652a3df5 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReferralDao.java @@ -0,0 +1,56 @@ +package org.smartregister.chw.dao; + +import org.smartregister.dao.AbstractDao; + +import java.math.BigDecimal; +import java.sql.Date; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.Locale; + +import timber.log.Timber; + +public class ReferralDao extends AbstractDao { + public static String getTaskIdByReasonReference(String formId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "_id"); + + String sql = String.format( + "SELECT _id FROM %s WHERE reason_reference = '%s' ", + "task", + formId + ); + + List res = readData(sql, dataMap); + return res.size() > 0 ? res.get(0) : ""; + + } + + public static Date getLastAppointmentDate(String baseEntityId) { + DataMap dataMap = cursor -> getCursorValue(cursor, "last_appointment_date"); + + String sql = "SELECT last_appointment_date from ec_referral " + + "WHERE base_entity_id = '" + baseEntityId + "' "; + List res = readData(sql, dataMap); + + if (res != null && res.size() > 0 && res.get(0) != null) { + Calendar cal = Calendar.getInstance(); + try { + cal.setTimeInMillis(new BigDecimal(res.get(0)).longValue()); + } catch (Exception e) { + //NEEDED FOR THE ISSUE IN SOME TABLETS FAILING TO CREATE A TIMESTAMP + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + try { + cal.setTime(sdf.parse(res.get(0))); + } catch (ParseException parseException) { + Timber.e(parseException); + return null; + } + } + return new Date(cal.getTimeInMillis()); + } + return null; + + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReportDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReportDao.java index b5155b7b80..0234539236 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReportDao.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ReportDao.java @@ -1,5 +1,7 @@ package org.smartregister.chw.dao; +import static org.smartregister.chw.core.utils.VisitVaccineUtil.getInMemoryAlerts; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -37,13 +39,32 @@ import timber.log.Timber; -import static org.smartregister.chw.core.utils.VisitVaccineUtil.getInMemoryAlerts; - /** * @author rkodev */ public class ReportDao extends AbstractDao { + public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()); + + public static int getReportPerIndicatorCode(String indicatorCode, Date reportDate) { + String reportDateString = simpleDateFormat.format(reportDate); + String sql = "SELECT indicator_value\n" + + "FROM indicator_daily_tally\n" + + "WHERE indicator_code = '" + indicatorCode + "'\n" + + " AND date((substr('" + reportDateString + "', 7, 4) || '-' || substr('" + reportDateString + "', 4, 2) || '-' || '01')) = date((substr(day, 1, 4) || '-' || substr(day, 6, 2) || '-' || '01'))\n" + + "ORDER BY day DESC LIMIT 1"; + + DataMap map = cursor -> getCursorIntValue(cursor, "indicator_value"); + + List res = readData(sql, map); + + + if (res != null && res.size() > 0 && res.get(0) != null) { + return res.get(0); + } else + return 0; + } + @NonNull public static Map extractRecordedLocations() { Map locations = new HashMap<>(); @@ -110,8 +131,8 @@ public static Map> fetchAllVaccines() { return result; } - protected static String cleanName(String name){ - return name.toLowerCase().replace("_", "").replace(" ",""); + protected static String cleanName(String name) { + return name.toLowerCase().replace("_", "").replace(" ", ""); } public static List fetchLiveEligibleChildrenReport(@Nullable List communityIds, Date dueDate) { @@ -143,8 +164,8 @@ public static List fetchLiveEligibleChildrenReport(@Nullable List if (age < 2 || (age >= 9 && age <= 11 && "Female".equalsIgnoreCase(gender))) { List rawVaccines = allVaccines.get(baseEntityId); List myVaccines = new ArrayList<>(); - if(rawVaccines != null){ - for(Vaccine vaccine: rawVaccines){ + if (rawVaccines != null) { + for (Vaccine vaccine : rawVaccines) { vaccine.setDate(new DateTime(vaccine.getDate()).minusDays(days).toDate()); myVaccines.add(vaccine); } @@ -152,8 +173,8 @@ public static List fetchLiveEligibleChildrenReport(@Nullable List List raw_alerts = computeChildAlerts(age, new DateTime(dob).minusDays(days), baseEntityId, myVaccines); Set myGivenVaccines = new HashSet<>(); - if(myVaccines != null){ - for(Vaccine vaccine : myVaccines) { + if (myVaccines != null) { + for (Vaccine vaccine : myVaccines) { myGivenVaccines.add(cleanName(vaccine.getName())); } } @@ -198,7 +219,7 @@ protected static List computeChildAlerts(int age, DateTime anchorDate, St } private static HashMap> getVaccineSchedules(String category) { - String fileName = category.equalsIgnoreCase("child")? "vaccines.json": "vaccines/child_over_5_vaccines.json"; + String fileName = category.equalsIgnoreCase("child") ? "vaccines.json" : "vaccines/child_over_5_vaccines.json"; List vaccineGroups = VaccineScheduleUtil.getVaccineGroups(CoreChwApplication.getInstance().getApplicationContext(), fileName); @@ -209,6 +230,220 @@ private static HashMap> getVaccineSched return VisitVaccineUtil.getSchedule(vaccineGroups, specialVaccines, category); } + public static List> getHfIssuingCdpStockLog(Date reportDate) + { + String sql = "SELECT outlet_name,visit_key,vd.details as details FROM ec_cdp_outlet as eco\n" + + " INNER JOIN visits ON visits.base_entity_id = eco.base_entity_id\n" + + "INNER JOIN visit_details as vd ON visits.visit_id = vd.visit_id\n" + + "WHERE (visit_key = 'restocked_male_condoms' \n" + + "OR visit_key = 'restocked_female_condoms' )\n" + + "AND visit_type = 'CDP Restock'\n" + + "AND date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) =\n" + + " date(substr(strftime('%Y-%m-%d', datetime(visit_date / 1000, 'unixepoch', 'localtime')), 1, 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d', datetime(visit_date / 1000, 'unixepoch', 'localtime')), 6, 2) ||\n" + + " '-' || '01')"; + + String queryDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(reportDate); + + sql = sql.contains("%s") ? sql.replaceAll("%s", queryDate) : sql; + + DataMap> map = cursor -> { + Map data = new HashMap<>(); + data.put("outlet_name", cursor.getString(cursor.getColumnIndex("outlet_name"))); + data.put("visit_key", cursor.getString(cursor.getColumnIndex("visit_key"))); + data.put("details", cursor.getString(cursor.getColumnIndex("details"))); + + return data; + }; + + List> res = readData(sql, map); + + + if (res != null && res.size() > 0) { + return res; + } else + return new ArrayList<>(); + } + + public static List> getCHWRegistrationFollowUpClients(Date reportDate) { + String sql = "SELECT ecr.cbhs_number as cbhs_number,\n" + + " ecr.reasons_for_registration as registration_reason,\n" + + " ecr.client_hiv_status_during_registration as hiv_status_during_registration,\n" + + " ecr.client_tb_status_during_registration as tb_status_during_registration,\n" + + " (date() - fm.dob) as age,\n" + + " fm.gender,\n" + + " ecr.client_hiv_status_after_testing as client_hiv_status_after_testing,\n" + + " ecr.client_tb_status_after_testing as client_tb_status_after_testing,\n" + + " ecf.hiv_services_provided,\n" + + " fm.base_entity_id,\n" + + " ecr.ctc_number,\n" + + " ecr.tb_number,\n" + + " ecr.rch_number,\n" + + " ecr.mat_number,\n" + + " ecf.supplies_provided,\n" + + " tasks.issued_referrals,\n" + + " tasks.successful_referrals,\n" + + " ecf.state_of_hiv_care_and_treatment,\n" + + " ecf.state_of_registration_in_tb_and_pwid_clinics,\n" + + " ecf.referrals_issued_to_other_services,\n" + + " ecf.referrals_to_other_services_completed,\n" + + " ecf.registration_or_followup_status\n" + + "FROM ec_cbhs_register ecr\n" + + " INNER JOIN ec_family_member fm on fm.base_entity_id = ecr.base_entity_id\n" + + " LEFT JOIN (SELECT entity_id,\n" + + " max(last_interacted_with) as last_interacted_with,\n" + + " hiv_services_provided,\n" + + " state_of_hiv_care_and_treatment,\n" + + " state_of_registration_in_tb_and_pwid_clinics,\n" + + " registration_or_followup_status,\n" + + " supplies_provided,\n" + + " referrals_issued_to_other_services,\n" + + " referrals_to_other_services_completed\n" + + " from ec_cbhs_followup\n" + + " WHERE date(substr(strftime('%Y-%m-%d',\n" + + " datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1,\n" + + " 4) || '-' ||\n" + + " substr(strftime('%Y-%m-%d',\n" + + " datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6,\n" + + " 2) || '-' || '01')\n" + + " =\n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01'))\n" + + " GROUP BY entity_id) ecf on fm.base_entity_id = ecf.entity_id\n" + + "\n" + + "\n" + + " LEFT JOIN (SELECT entity_id,\n" + + " max(last_interacted_with) as last_interaction, \n" + + " registration_or_followup_status as last_followup_status\n" + + " from ec_cbhs_followup\n" + + " WHERE date(substr(strftime('%Y-%m-%d',\n" + + " datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 1,\n" + + " 4) || '-' ||\n" + + " substr(strftime('%Y-%m-%d',\n" + + " datetime(last_interacted_with / 1000, 'unixepoch', 'localtime')), 6,\n" + + " 2) || '-' || '01')\n" + + " <\n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01'))\n" + + "\n" + + " group by entity_id) lecf on fm.base_entity_id = lecf.entity_id\n" + + "\n" + + " LEFT JOIN (select for,\n" + + " GROUP_CONCAT(case\n" + + " when code = 'Referral' and business_status != 'Cancelled' then focus\n" + + " else '' end,',') as 'issued_referrals',\n" + + " GROUP_CONCAT(case\n" + + " when code = 'Referral' and business_status != 'Cancelled' and\n" + + " business_status = 'Complete' then focus\n" + + " else '' end, ',') as 'successful_referrals'\n" + + " from Task\n" + + " WHERE date(substr(strftime('%Y-%m-%d',\n" + + " datetime(Task.authored_on / 1000, 'unixepoch', 'localtime')), 1,\n" + + " 4) ||\n" + + " '-' ||\n" + + " substr(strftime('%Y-%m-%d',\n" + + " datetime(Task.authored_on / 1000, 'unixepoch', 'localtime')), 6,\n" + + " 2) ||\n" + + " '-' || '01') =\n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01'))\n" + + " group by for) tasks on fm.base_entity_id = tasks.for\n" + + "\n" + + "WHERE (last_followup_status <> 'client_relocated_to_another_location' AND last_followup_status <> 'completed_and_qualified_from_the_services' AND last_followup_status <> 'client_has_absconded' AND last_followup_status <> 'deceased') OR last_followup_status IS NULL\n" + + "group by fm.base_entity_id\n"; + + String queryDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(reportDate); + + sql = sql.contains("%s") ? sql.replaceAll("%s", queryDate) : sql; + + DataMap> map = cursor -> { + Map data = new HashMap<>(); + data.put("cbhs_number", cursor.getString(cursor.getColumnIndex("cbhs_number"))); + data.put("registration_reason", cursor.getString(cursor.getColumnIndex("registration_reason"))); + data.put("hiv_status_during_registration", cursor.getString(cursor.getColumnIndex("hiv_status_during_registration"))); + data.put("tb_status_during_registration", cursor.getString(cursor.getColumnIndex("tb_status_during_registration"))); + data.put("age", cursor.getString(cursor.getColumnIndex("age"))); + data.put("gender", cursor.getString(cursor.getColumnIndex("gender"))); + + data.put("ctc_number", cursor.getString(cursor.getColumnIndex("ctc_number"))); + data.put("tb_number", cursor.getString(cursor.getColumnIndex("tb_number"))); + data.put("rch_number", cursor.getString(cursor.getColumnIndex("rch_number"))); + data.put("mat_number", cursor.getString(cursor.getColumnIndex("mat_number"))); + + data.put("referrals_issued_to_other_services", cursor.getString(cursor.getColumnIndex("referrals_issued_to_other_services"))); + data.put("referrals_to_other_services_completed", cursor.getString(cursor.getColumnIndex("referrals_to_other_services_completed"))); + + data.put("client_hiv_status_after_testing", cursor.getString(cursor.getColumnIndex("client_hiv_status_after_testing"))); + data.put("client_tb_status_after_testing", cursor.getString(cursor.getColumnIndex("client_tb_status_after_testing"))); + data.put("hiv_services_provided", cursor.getString(cursor.getColumnIndex("hiv_services_provided"))); + data.put("supplies_provided", cursor.getString(cursor.getColumnIndex("supplies_provided"))); + data.put("issued_referrals", cursor.getString(cursor.getColumnIndex("issued_referrals"))); + data.put("successful_referrals", cursor.getString(cursor.getColumnIndex("successful_referrals"))); + data.put("state_of_hiv_care_and_treatment", cursor.getString(cursor.getColumnIndex("state_of_hiv_care_and_treatment"))); + data.put("state_of_registration_in_tb_and_pwid_clinics", cursor.getString(cursor.getColumnIndex("state_of_registration_in_tb_and_pwid_clinics"))); + data.put("registration_or_followup_status", cursor.getString(cursor.getColumnIndex("registration_or_followup_status"))); + return data; + }; + + List> res = readData(sql, map); + + + if (res != null && res.size() > 0) { + return res; + } else + return new ArrayList<>(); + } + + public static List> getHfCdpStockLog(Date reportDate) + { + String sql = " SELECT female_condoms_offset,male_condoms_offset,issuing_organization,female_condom_brand,male_condom_brand \n" + + " FROM ec_cdp_stock_log \n" + + " WHERE (issuing_organization='MSD' OR issuing_organization='PSI' OR issuing_organization='T-MARC' OR issuing_organization='other') \n" + + " AND (stock_event_type ='increment' ) \n" + + " AND date(substr(strftime('%Y-%m-%d', datetime(date_updated / 1000, 'unixepoch', 'localtime')), 1, 4) || '-' || \n" + + " substr(strftime('%Y-%m-%d', datetime(date_updated / 1000, 'unixepoch', 'localtime')), 6, 2) || '-' || '01') = \n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) \n" + + " UNION ALL \n" + + " SELECT ec_cdp_order_feedback.quantity_response,'0' as male_condoms_offset,location.name,ec_cdp_order_feedback.condom_brand,'-' as male_condom_brand \n" + + " FROM task \n" + + " INNER JOIN location ON location.uuid = task.group_id \n" + + " INNER JOIN ec_cdp_order_feedback ON ec_cdp_order_feedback.request_reference = task.reason_reference \n" + + " WHERE (ec_cdp_order_feedback.condom_type = 'female_condom' AND task.status = 'COMPLETED') \n" + + " AND date(substr(strftime('%Y-%m-%d', datetime(response_at / 1000, 'unixepoch', 'localtime')), 1, 4) || '-' || \n" + + " substr(strftime('%Y-%m-%d', datetime(response_at / 1000, 'unixepoch', 'localtime')), 6, 2) || '-' || '01') = \n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) \n" + + " UNION ALL \n" + + " SELECT '0' as female_condoms_offset,quantity_response,location.name,'-' as female_condom_brand,ec_cdp_order_feedback.condom_brand \n" + + " FROM task \n" + + " INNER JOIN location ON location.uuid = task.group_id \n" + + " INNER JOIN ec_cdp_order_feedback ON ec_cdp_order_feedback.request_reference = task.reason_reference \n" + + " WHERE (ec_cdp_order_feedback.condom_type = 'male_condom' AND task.status = 'COMPLETED') \n" + + " AND date(substr(strftime('%Y-%m-%d', datetime(response_at / 1000, 'unixepoch', 'localtime')), 1, 4) || '-' || \n" + + " substr(strftime('%Y-%m-%d', datetime(response_at / 1000, 'unixepoch', 'localtime')), 6, 2) || '-' || '01') = \n" + + " date((substr('%s', 1, 4) || '-' || substr('%s', 6, 2) || '-' || '01')) "; + + String queryDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(reportDate); + + sql = sql.contains("%s") ? sql.replaceAll("%s", queryDate) : sql; + + DataMap> map = cursor -> { + Map data = new HashMap<>(); + data.put("female_condoms_offset", cursor.getString(cursor.getColumnIndex("female_condoms_offset"))); + data.put("male_condoms_offset", cursor.getString(cursor.getColumnIndex("male_condoms_offset"))); + data.put("issuing_organization", cursor.getString(cursor.getColumnIndex("issuing_organization"))); + data.put("male_condom_brand", cursor.getString(cursor.getColumnIndex("male_condom_brand"))); + data.put("female_condom_brand", cursor.getString(cursor.getColumnIndex("female_condom_brand"))); + + return data; + }; + + List> res = readData(sql, map); + + + if (res != null && res.size() > 0) { + return res; + } else + return new ArrayList<>(); + } + @NonNull public static List eligibleChildrenReport(ArrayList communityIds, Date dueDate) { @@ -415,7 +650,7 @@ private static String getChildrenExclusiveBreastFeeding() { "where rt.type = 'Exclusive_breastfeeding' and ifnull(re.value,'yes') = 'yes'\n" + "group by re.base_entity_id\n" + ") ex on ex.base_entity_id = e.baseEntityId and SUBSTR(e.eventDate,1,10) between date(ex.last_exclusive_date, '-1 day') and date(ex.last_exclusive_date, '1 day')\n" + - "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date()))\n" + + "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date()))\n" + "and date(ec.dob) between date('now', '-5 month') and date('now')"; } @@ -438,7 +673,7 @@ private static String getChildrenNotExclusiveBreastFeeding() { "where rt.type = 'Exclusive_breastfeeding' and ifnull(re.value,'yes') = 'yes'\n" + "group by re.base_entity_id\n" + ") ex on ex.base_entity_id = e.baseEntityId and SUBSTR(e.eventDate,1,10) between date(ex.last_exclusive_date, '-1 day') and date(ex.last_exclusive_date, '1 day')\n" + - "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date()))\n" + + "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date()))\n" + "and date(ec.dob) between date('now', '-5 month') and date('now') and ex.base_entity_id is null"; } @@ -447,7 +682,7 @@ private static String getChildrenVitaminAReceived() { "f.first_name family_name , ec.dob \n" + "from recurring_service_types rt \n" + "inner join recurring_service_records re on re.recurring_service_id = rt._id \n" + - "inner join ec_child ec on ec.base_entity_id = re.base_entity_id and (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date())) \n" + + "inner join ec_child ec on ec.base_entity_id = re.base_entity_id and (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date())) \n" + "inner join ec_family_member ef on ec.base_entity_id = ef.base_entity_id and ef.date_removed is null \n" + "inner join ec_family f on ec.relational_id = f.base_entity_id \n" + "where rt.type = 'Vitamin_A' and date(ec.dob) between date('now', '-23 month') and date('now', '-6 month') \n" + @@ -461,7 +696,7 @@ private static String getChildrenVitaminANotReceived() { "from ec_child ec \n" + "left join ec_family f on ec.relational_id = f.base_entity_id \n" + "inner join ec_family_member ef on ec.base_entity_id = ef.base_entity_id and ef.date_removed is null \n" + - "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date())) \n" + + "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date())) \n" + "and date(ec.dob) between date('now', '-23 month') and date('now', '-6 month') \n" + "and ec.base_entity_id not in ( \n" + "select re.base_entity_id from recurring_service_records re \n" + @@ -475,7 +710,7 @@ private static String getChildrenDewormed() { "f.first_name family_name , ec.dob \n" + "from recurring_service_types rt \n" + "inner join recurring_service_records re on re.recurring_service_id = rt._id \n" + - "inner join ec_child ec on ec.base_entity_id = re.base_entity_id and (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date())) \n" + + "inner join ec_child ec on ec.base_entity_id = re.base_entity_id and (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date())) \n" + "inner join ec_family_member ef on ec.base_entity_id = ef.base_entity_id and ef.date_removed is null \n" + "inner join ec_family f on ec.relational_id = f.base_entity_id \n" + "where rt.type = 'Deworming' and date(ec.dob) between date('now', '-23 month') and date('now', '-12 month') \n" + @@ -489,7 +724,7 @@ private static String getChildrenNotDewormed() { "from ec_child ec \n" + "left join ec_family f on ec.relational_id = f.base_entity_id \n" + "inner join ec_family_member ef on ec.base_entity_id = ef.base_entity_id and ef.date_removed is null \n" + - "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+28 days') <= date())) \n" + + "where (( ifnull(ec.entry_point,'') <> 'PNC' ) or (ifnull(ec.entry_point,'') = 'PNC' and date(ec.dob, '+42 days') <= date())) \n" + "and date(ec.dob) between date('now', '-23 month') and date('now', '-12 month') \n" + "and ec.base_entity_id not in ( \n" + "select re.base_entity_id from recurring_service_records re \n" + @@ -566,4 +801,5 @@ public static List myCommunityActivityReportDetails(String indica return res; } + } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ScheduleDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ScheduleDao.java index 99adf2cada..773af0dbb5 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dao/ScheduleDao.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/ScheduleDao.java @@ -69,4 +69,20 @@ public static void deleteChildrenVaccines(){ DataMap dataMap = c -> getCursorValue(c, "base_entity_id"); return AbstractDao.readData(sql, dataMap); } + + public static @Nullable List getActiveHivClients(String scheduleName, String scheduleGroup) { + String sql = "select base_entity_id from ec_hiv_register where is_closed = 0 and base_entity_id not in " + + "(select base_entity_id from schedule_service where schedule_name = '" + scheduleName + "' and schedule_group_name = '" + scheduleGroup + "')"; + + DataMap dataMap = c -> getCursorValue(c, "base_entity_id"); + return AbstractDao.readData(sql, dataMap); + } + + public static @Nullable List getActiveTbClients(String scheduleName, String scheduleGroup) { + String sql = "select base_entity_id from ec_tb_register where is_closed = 0 and tb_case_closure_date is null and base_entity_id not in " + + "(select base_entity_id from schedule_service where schedule_name = '" + scheduleName + "' and schedule_group_name = '" + scheduleGroup + "')"; + + DataMap dataMap = c -> getCursorValue(c, "base_entity_id"); + return AbstractDao.readData(sql, dataMap); + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dao/WashCheckDao.java b/opensrp-chw/src/main/java/org/smartregister/chw/dao/WashCheckDao.java index aa812c9942..bead70f487 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dao/WashCheckDao.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dao/WashCheckDao.java @@ -91,6 +91,4 @@ private static EventClient processEventClientCursor(String jsonEventStr) { return new EventClient(event, null); } - - } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/dataloader/FamilyMemberDataLoader.java b/opensrp-chw/src/main/java/org/smartregister/chw/dataloader/FamilyMemberDataLoader.java index ac780f0dda..c32713d784 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/dataloader/FamilyMemberDataLoader.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/dataloader/FamilyMemberDataLoader.java @@ -75,6 +75,7 @@ public String getValue(Context context, String baseEntityID, JSONObject jsonObje .replace("-", ""); case Constants.JsonAssets.FAM_NAME: + case Constants.JsonAssets.SURNAME: computeFamName(client, jsonObject, jsonArray, familyName); break; @@ -160,7 +161,7 @@ private void computeFamName(Client client, JSONObject jsonObject, JSONArray json if (!familyName.equals(lastName)) { surname.put(org.smartregister.family.util.JsonFormUtils.VALUE, lastName); } else { - surname.put(org.smartregister.family.util.JsonFormUtils.VALUE, ""); + surname.put(org.smartregister.family.util.JsonFormUtils.VALUE, familyName); } } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/PmtctReferralMemberObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/PmtctReferralMemberObject.java new file mode 100644 index 0000000000..1d7d6fbd02 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/PmtctReferralMemberObject.java @@ -0,0 +1,53 @@ +package org.smartregister.chw.domain; + +import org.smartregister.chw.pmtct.domain.MemberObject; + +import java.util.Date; + +public class PmtctReferralMemberObject extends MemberObject { + private Date pmtctCommunityReferralDate; + private Date lastFacilityVisitDate; + private String reasonsForIssuingCommunityFollowupReferral; + private String comments; + private String childName; + + public String getChildName() { + return childName; + } + + public void setChildName(String childName) { + this.childName = childName; + } + + public String getReasonsForIssuingCommunityFollowupReferral() { + return reasonsForIssuingCommunityFollowupReferral; + } + + public void setReasonsForIssuingCommunityFollowupReferral(String reasonsForIssuingCommunityFollowupReferral) { + this.reasonsForIssuingCommunityFollowupReferral = reasonsForIssuingCommunityFollowupReferral; + } + + public Date getPmtctCommunityReferralDate() { + return pmtctCommunityReferralDate; + } + + public void setPmtctCommunityReferralDate(Date pmtctCommunityReferralDate) { + this.pmtctCommunityReferralDate = pmtctCommunityReferralDate; + } + + public Date getLastFacilityVisitDate() { + return lastFacilityVisitDate; + } + + public void setLastFacilityVisitDate(Date lastFacilityVisitDate) { + this.lastFacilityVisitDate = lastFacilityVisitDate; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/PncBaby.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/PncBaby.java index b9e041b6e2..f3f15862ea 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/domain/PncBaby.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/PncBaby.java @@ -6,13 +6,19 @@ public class PncBaby extends Person { private String lbw; + private String gender; - public PncBaby(String baseEntityID, String firstName, String lastName, String middleName, Date dob, String lbw) { + public PncBaby(String baseEntityID, String firstName, String lastName, String middleName, Date dob, String gender, String lbw) { super(baseEntityID, firstName, lastName, middleName, dob); this.lbw = lbw; + this.gender = gender; } public String getLbw() { return lbw; } + + public String getGender() { + return gender; + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/ReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/ReportObject.java new file mode 100644 index 0000000000..9b8423460e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/ReportObject.java @@ -0,0 +1,36 @@ +package org.smartregister.chw.domain; + +import com.google.gson.Gson; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.Date; +import java.util.List; + +public abstract class ReportObject { + + private List indicatorCodes; + private final Date reportDate; + + public ReportObject(Date reportDate) { + this.reportDate = reportDate; + } + + public List getIndicatorCodes() { + return indicatorCodes; + } + + public Date getReportDate() { + return reportDate; + } + + public JSONObject getIndicatorData() throws JSONException { + return new JSONObject(); + } + + public String getIndicatorDataAsGson(JSONObject jsonObject) throws JSONException { + Gson gson = new Gson(); + return gson.toJson(jsonObject); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/SortableVisit.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/SortableVisit.java new file mode 100644 index 0000000000..540afefa2d --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/SortableVisit.java @@ -0,0 +1,11 @@ +package org.smartregister.chw.domain; + +import org.smartregister.chw.anc.domain.Visit; + +public class SortableVisit extends Visit implements Comparable { + @Override + public int compareTo(SortableVisit sortableVisit) { + long data = getDate().getTime() - sortableVisit.getDate().getTime(); + return (int) data; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/agyw_reports/AGYWReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/agyw_reports/AGYWReportObject.java new file mode 100644 index 0000000000..2cc4cdb395 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/agyw_reports/AGYWReportObject.java @@ -0,0 +1,50 @@ +package org.smartregister.chw.domain.agyw_reports; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.dao.ReportDao; +import org.smartregister.chw.domain.ReportObject; + +import java.util.Date; + +public class AGYWReportObject extends ReportObject { + + private final String[] noOfQuestions = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13"}; + private final String[] agesGroups = new String[]{"10-14","15-19","20-24"}; + private final Date reportDate; + private JSONObject jsonObject ; + + public AGYWReportObject(Date reportDate) { + super(reportDate); + this.reportDate = reportDate; + } + + @Override + public JSONObject getIndicatorData() throws JSONException { + + + + jsonObject = new JSONObject(); + for (String questions : noOfQuestions){ + for (String ageGroup : agesGroups) { + jsonObject.put("agyw"+"-"+questions+"-"+ageGroup, + ReportDao.getReportPerIndicatorCode("agyw"+"-"+questions+"-"+ageGroup, reportDate)); + } + } + // get total of all + getTotalPerEachIndicator(); + + return jsonObject; + } + + private void getTotalPerEachIndicator() throws JSONException { + int finalTotal = 0; + for (String question: noOfQuestions){ + for (String ageGroup : agesGroups) { + finalTotal += ReportDao.getReportPerIndicatorCode("agyw"+"-"+question+"-"+ageGroup, reportDate); + } + jsonObject.put("agyw"+"-"+question+"-JUMLA",finalTotal); //display the total for specified question + finalTotal=0; + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/cbhs_reports/CbhsMonthlyReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cbhs_reports/CbhsMonthlyReportObject.java new file mode 100644 index 0000000000..fb032eba0e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cbhs_reports/CbhsMonthlyReportObject.java @@ -0,0 +1,255 @@ +package org.smartregister.chw.domain.cbhs_reports; + +import android.content.Context; +import android.content.res.Configuration; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.dao.ReportDao; +import org.smartregister.chw.domain.ReportObject; + +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public class CbhsMonthlyReportObject extends ReportObject { + private final Context context; + private final Date reportDate; + + public CbhsMonthlyReportObject(Date reportDate, Context context) { + super(reportDate); + this.reportDate = reportDate; + + Configuration configuration = new Configuration(context.getResources().getConfiguration()); + configuration.setLocale(new Locale("sw")); + this.context = context.createConfigurationContext(configuration); + + } + + @Override + public JSONObject getIndicatorData() throws JSONException { + JSONArray dataArray = new JSONArray(); + List> chwRegistrationFollowupClientsList = ReportDao.getCHWRegistrationFollowUpClients(reportDate); + + int i = 0; + for (Map chwRegistrationFollowupClient : chwRegistrationFollowupClientsList) { + JSONObject reportJsonObject = new JSONObject(); + reportJsonObject.put("id", ++i); + + reportJsonObject.put("namba-za-mteja", getCbhsClientDetails(chwRegistrationFollowupClient, "cbhs_number")); + reportJsonObject.put("sababu-za-usajili", getCbhsClientDetails(chwRegistrationFollowupClient, "registration_reason")); + + if (chwRegistrationFollowupClient.get("client_hiv_status_after_testing") == null) + reportJsonObject.put("hali-ya-maamubikizi-ya-vvu", getCbhsClientDetails(chwRegistrationFollowupClient, "hiv_status_during_registration")); + else + reportJsonObject.put("hali-ya-maamubikizi-ya-vvu", getCbhsClientDetails(chwRegistrationFollowupClient, "client_hiv_status_after_testing")); + + if (chwRegistrationFollowupClient.get("client_tb_status_after_testing") == null) + reportJsonObject.put("hali-ya-maamubikizi-ya-tb", getCbhsClientDetails(chwRegistrationFollowupClient, "tb_status_during_registration")); + else + reportJsonObject.put("hali-ya-maamubikizi-ya-tb", getCbhsClientDetails(chwRegistrationFollowupClient, "client_tb_status_after_testing")); + + + String clinicRegistrationNumber = ""; + String clinicName = ""; + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "ctc_number").equals("-")) { + clinicRegistrationNumber += getCbhsClientDetails(chwRegistrationFollowupClient, "ctc_number") + "
"; + clinicName += "CTC
"; + } + + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "tb_number").equals("-")) { + clinicRegistrationNumber += getCbhsClientDetails(chwRegistrationFollowupClient, "tb_number") + "
"; + clinicName += "TB
"; + } + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "rch_number").equals("-")) { + clinicRegistrationNumber += getCbhsClientDetails(chwRegistrationFollowupClient, "rch_number") + "
"; + clinicName += "RCH
"; + } + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "mat_number").equals("-")) { + clinicRegistrationNumber += getCbhsClientDetails(chwRegistrationFollowupClient, "mat_number") + "
"; + clinicName += "MAT
"; + } + + if (StringUtils.isBlank(clinicRegistrationNumber)) + clinicRegistrationNumber = "-"; + + if (StringUtils.isBlank(clinicName)) + clinicName = "-"; + + reportJsonObject.put("namba-ya-usajili-wa kliniki", clinicRegistrationNumber); + reportJsonObject.put("aina-ya-kliniki", clinicName); + + + String referralIssued = ""; + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "issued_referrals").equals("-")) { + referralIssued += getCbhsClientDetails(chwRegistrationFollowupClient, "issued_referrals") + "
"; + } + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "referrals_issued_to_other_services").equals("-")) { + referralIssued += getCbhsClientDetails(chwRegistrationFollowupClient, "referrals_issued_to_other_services") + "
"; + } + + String referralsCompleted = ""; + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "successful_referrals").equals("-")) { + referralsCompleted += getCbhsClientDetails(chwRegistrationFollowupClient, "successful_referrals") + "
"; + } + if (!getCbhsClientDetails(chwRegistrationFollowupClient, "referrals_to_other_services_completed").equals("-")) { + referralsCompleted += getCbhsClientDetails(chwRegistrationFollowupClient, "referrals_to_other_services_completed") + "
"; + } + + + reportJsonObject.put("umri", getCbhsClientDetails(chwRegistrationFollowupClient, "age")); + reportJsonObject.put("jinsia", getCbhsClientDetails(chwRegistrationFollowupClient, "gender")); + reportJsonObject.put("huduma-zilizotolewa", getCbhsClientDetails(chwRegistrationFollowupClient, "hiv_services_provided")); + reportJsonObject.put("vifaa-vilivyotolewa", getCbhsClientDetails(chwRegistrationFollowupClient, "supplies_provided")); + reportJsonObject.put("rufaa-zilizotolewa", referralIssued); + reportJsonObject.put("rufaa-zilizofanikiwa", referralsCompleted); + + + String stateOfHivCareAndTreatment = getCbhsClientDetails(chwRegistrationFollowupClient, "state_of_hiv_care_and_treatment"); + + if (chwRegistrationFollowupClient.get("state_of_registration_in_tb_and_pwid_clinics") != null && !chwRegistrationFollowupClient.get("state_of_registration_in_tb_and_pwid_clinics").equals("not_applicable")) { + stateOfHivCareAndTreatment = stateOfHivCareAndTreatment + ", " + getCbhsClientDetails(chwRegistrationFollowupClient, "state_of_registration_in_tb_and_pwid_clinics"); + } + + + reportJsonObject.put("hali-ya-tiba-na-matunzo", stateOfHivCareAndTreatment); + reportJsonObject.put("hali-ya-usajili-na-ufuatiliaji", getCbhsClientDetails(chwRegistrationFollowupClient, "registration_or_followup_status")); + + dataArray.put(reportJsonObject); + } + + JSONObject resultJsonObject = new JSONObject(); + resultJsonObject.put("reportData", dataArray); + + return resultJsonObject; + } + + private String getCbhsClientDetails(Map chwRegistrationFollowupClient, String key) { + String details = chwRegistrationFollowupClient.get(key); + if (StringUtils.isNotBlank(details)) { + switch (key) { + case "issued_referrals": + case "successful_referrals": + return getTranslatedReferralFocus(details); + case "registration_reason": + return getStringValues(details, "reason_for_registration_"); + case "referrals_issued_to_other_services": + case "referrals_to_other_services_completed": + case "supplies_provided": + case "hiv_services_provided": + case "registration_or_followup_status": + case "state_of_hiv_care_and_treatment": + case "state_of_registration_in_tb_and_pwid_clinics": + case "gender": + case "hiv_status_during_registration": + case "tb_status_during_registration": + case "client_hiv_status_after_testing": + case "client_tb_status_after_testing": + return getStringValues(details, "cbhs_"); + default: + return details; + } + + } + return "-"; + } + + private String getStringValues(String receivedVal, String resourceKey) { + if (receivedVal.contains(",") || receivedVal.startsWith("[")) { + String[] values; + if (receivedVal.startsWith("[")) { + //remove the [ and ] and add the values separated in a comma to array + values = receivedVal.substring(1, receivedVal.length() - 1).split(","); + } else { + values = receivedVal.split(","); + } + StringBuilder sb = new StringBuilder(); + for (String value : values) { + int humanReadableValueId = context.getResources().getIdentifier(resourceKey.toLowerCase() + value.trim().toLowerCase(), "string", context.getPackageName()); + if (humanReadableValueId != 0) { + sb.append(context.getString(humanReadableValueId)).append(", "); + } else + sb.append(value).append(", "); + } + + String stringValues = sb.toString().trim(); + if (stringValues.charAt(stringValues.length() - 1) == ',') { + stringValues = stringValues.substring(0, stringValues.length() - 1); + } + + return stringValues; + } + + int humanReadableValueId = context.getResources().getIdentifier(resourceKey + receivedVal.trim().toLowerCase(), "string", context.getPackageName()); + if (humanReadableValueId != 0) { + return context.getString(humanReadableValueId); + } + return receivedVal; + } + + private String getTranslatedReferralFocus(String focusString) { + String focusList[]; + if (focusString.contains(",")) { + focusList = focusString.split(","); + } else { + focusList = new String[]{focusString}; + } + StringBuilder translatedFocus = new StringBuilder(); + for (String focus : focusList) { + switch (focus) { + case CoreConstants.TASKS_FOCUS.ANC_DANGER_SIGNS: + translatedFocus.append(context.getString(R.string.anc_danger_signs)).append(","); + break; + case CoreConstants.TASKS_FOCUS.PNC_DANGER_SIGNS: + translatedFocus.append(context.getString(R.string.pnc_danger_signs)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SUSPECTED_MALARIA: + translatedFocus.append(context.getString(R.string.client_malaria_follow_up)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SICK_CHILD: + translatedFocus.append(context.getString(R.string.sick_child)).append(","); + break; + case CoreConstants.TASKS_FOCUS.FP_SIDE_EFFECTS: + translatedFocus.append(context.getString(R.string.family_planning_referral)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SUSPECTED_TB: + translatedFocus.append(context.getString(R.string.tb_referral)).append(","); + break; + case CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST: + translatedFocus.append(context.getString(R.string.hts_referral)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SICK_HIV: + translatedFocus.append(context.getString(R.string.hiv_referral)).append(","); + break; + case CoreConstants.TASKS_FOCUS.PREGNANCY_CONFIRMATION: + translatedFocus.append(context.getString(R.string.pregnancy_confirmation)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SUSPECTED_GBV: + translatedFocus.append(context.getString(R.string.gbv_referral)).append(","); + break; + case CoreConstants.TASKS_FOCUS.SUSPECTED_CHILD_GBV: + translatedFocus.append(context.getString(R.string.child_gbv_referral)).append(","); + break; + default: + translatedFocus.append(focus).append(","); + } + } + + if (StringUtils.isBlank(translatedFocus.toString())) { + return "-"; + } + + String stringValues = translatedFocus.toString().trim(); + if (stringValues.charAt(translatedFocus.length() - 1) == ',') { + stringValues = stringValues.substring(0, stringValues.length() - 1); + } + return stringValues; + } + + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpIssuingReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpIssuingReportObject.java new file mode 100644 index 0000000000..e7c1b4dde6 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpIssuingReportObject.java @@ -0,0 +1,86 @@ +package org.smartregister.chw.domain.cdp_reports; + +import android.util.Log; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.dao.ReportDao; +import org.smartregister.chw.domain.ReportObject; +import java.util.Date; +import java.util.List; +import java.util.Map; + +public class CdpIssuingReportObject extends ReportObject { + private Date reportDate; + + public CdpIssuingReportObject(Date reportDate) { + super(reportDate); + this.reportDate = reportDate; + } + + + @Override + public JSONObject getIndicatorData() throws JSONException { + JSONArray dataArray = new JSONArray(); + List> getHfCdpStockLogList = ReportDao.getHfIssuingCdpStockLog(reportDate); + + int i = 0; + int flag_count_female=0; + int flag_count_male=0; + for (Map getHfCdpStockLog : getHfCdpStockLogList) { + JSONObject reportJsonObject = new JSONObject(); + reportJsonObject.put("id", ++i); + + Log.d("hukuuuu",""+getHfCdpStockLog); + if (getCdpClientDetails(getHfCdpStockLog, "visit_key").equals("restocked_male_condoms")){ + reportJsonObject.put("outlet-name", getCdpClientDetails(getHfCdpStockLog, "outlet_name")); + reportJsonObject.put("male-condoms-offset", getCdpClientDetails(getHfCdpStockLog, "details")); + reportJsonObject.put("female-condoms-offset", getCdpClientDetails(getHfCdpStockLog, "0")); + flag_count_male+=Integer.parseInt(getCdpClientDetails(getHfCdpStockLog, "details")); + } + + if(getCdpClientDetails(getHfCdpStockLog, "visit_key").equals("restocked_female_condoms")){ + reportJsonObject.put("outlet-name", getCdpClientDetails(getHfCdpStockLog, "outlet_name")); + reportJsonObject.put("male-condoms-offset", getCdpClientDetails(getHfCdpStockLog, "0")); + reportJsonObject.put("female-condoms-offset", getCdpClientDetails(getHfCdpStockLog, "details")); + flag_count_female+=Integer.parseInt(getCdpClientDetails(getHfCdpStockLog, "details")); + } + + dataArray.put(reportJsonObject); + } + + //finally go display total of all + if (flag_count_male > 0 || flag_count_female > 0 ){ + JSONObject reportJsonObject = new JSONObject(); + reportJsonObject.put("total-id",i+1); + reportJsonObject.put("total","TOTAL NUMBER OF CONDOMS ISSUED"); + reportJsonObject.put("total-male-condoms",flag_count_male); + reportJsonObject.put("total-female-condoms",flag_count_female); + dataArray.put(reportJsonObject); + } + + + JSONObject resultJsonObject = new JSONObject(); + resultJsonObject.put("reportData", dataArray); + + return resultJsonObject; + } + + private String getCdpClientDetails(Map chwRegistrationFollowupClient, String key) { + String details = chwRegistrationFollowupClient.get(key); //get all details + if (StringUtils.isNotBlank(details)) { + return details; + } + else { + if (key.equals("0")){ + return "0"; + }else { + return "-"; + } + } + + } + +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpReceivingReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpReceivingReportObject.java new file mode 100644 index 0000000000..73799bfe65 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/cdp_reports/CdpReceivingReportObject.java @@ -0,0 +1,70 @@ +package org.smartregister.chw.domain.cdp_reports; +import org.apache.commons.lang3.StringUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.dao.ReportDao; +import org.smartregister.chw.domain.ReportObject; +import java.util.Date; +import java.util.List; +import java.util.Map; + +public class CdpReceivingReportObject extends ReportObject { + private Date reportDate; + + public CdpReceivingReportObject(Date reportDate) { + super(reportDate); + this.reportDate = reportDate; + } + + + @Override + public JSONObject getIndicatorData() throws JSONException { + JSONArray dataArray = new JSONArray(); + List> getHfCdpStockLogList = ReportDao.getHfCdpStockLog(reportDate); + + int i = 0; + int flag_count_female=0; + int flag_count_male=0; + + for (Map getHfCdpStockLog : getHfCdpStockLogList) { + JSONObject reportJsonObject = new JSONObject(); + reportJsonObject.put("id", ++i); + + reportJsonObject.put("source", getCbhsClientDetails(getHfCdpStockLog, "issuing_organization")); + reportJsonObject.put("male-condom-brand", getCbhsClientDetails(getHfCdpStockLog, "male_condom_brand")); + reportJsonObject.put("female-condom-brand", getCbhsClientDetails(getHfCdpStockLog, "female_condom_brand")); + reportJsonObject.put("number-of-male-condom", getCbhsClientDetails(getHfCdpStockLog, "male_condoms_offset")); + reportJsonObject.put("number-of-female-condom", getCbhsClientDetails(getHfCdpStockLog, "female_condoms_offset")); + flag_count_male+=Integer.parseInt(getCbhsClientDetails(getHfCdpStockLog, "male_condoms_offset")); + flag_count_female+=Integer.parseInt(getCbhsClientDetails(getHfCdpStockLog, "female_condoms_offset")); + dataArray.put(reportJsonObject); + } + + if (flag_count_male > 0 || flag_count_female > 0){ + JSONObject reportJsonObject = new JSONObject(); + reportJsonObject.put("total-id",i+1); + reportJsonObject.put("total","TOTAL NUMBER OF CONDOMS RECEIVED"); + reportJsonObject.put("total-female-brand",""); + reportJsonObject.put("total-male-brand",""); + reportJsonObject.put("total-male-condoms",flag_count_male); + reportJsonObject.put("total-female-condoms",flag_count_female); + dataArray.put(reportJsonObject); + } + + JSONObject resultJsonObject = new JSONObject(); + resultJsonObject.put("reportData", dataArray); + + return resultJsonObject; + } + + private String getCbhsClientDetails(Map chwRegistrationFollowupClient, String key) { + String details = chwRegistrationFollowupClient.get(key); + if (StringUtils.isNotBlank(details)) { + return details; + } + return "-"; + } + + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/mother_champion_report/MotherChampionReportObject.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/mother_champion_report/MotherChampionReportObject.java new file mode 100644 index 0000000000..f4a4a6f71c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/mother_champion_report/MotherChampionReportObject.java @@ -0,0 +1,33 @@ +package org.smartregister.chw.domain.mother_champion_report; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.dao.ReportDao; +import org.smartregister.chw.domain.ReportObject; + +import java.util.Date; + +public class MotherChampionReportObject extends ReportObject { + private final String[] indicatorCodes = new String[]{"b-1", "b-2", "b-3", "b-4", "b-5", "b-7"}; + private final Date reportDate; + + public MotherChampionReportObject(Date reportDate) { + super(reportDate); + this.reportDate = reportDate; + + } + + @Override + public JSONObject getIndicatorData() throws JSONException { + + JSONObject jsonObject = new JSONObject(); + + for (String indicatorCode : indicatorCodes) { + jsonObject.put(indicatorCode, ReportDao.getReportPerIndicatorCode(indicatorCode, reportDate)); + } + + return jsonObject; + } + + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AgywRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AgywRegisterFragment.java new file mode 100644 index 0000000000..44746ec4ac --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AgywRegisterFragment.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.activity.AgywProfileActivity; +import org.smartregister.chw.core.fragment.CoreAgywRegisterFragment; + +public class AgywRegisterFragment extends CoreAgywRegisterFragment { + + @Override + protected void openProfile(String baseEntityId) { + AgywProfileActivity.startProfile(requireActivity(), baseEntityId); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllClientsRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllClientsRegisterFragment.java index f8a2ad59a4..0a5b7ba70a 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllClientsRegisterFragment.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllClientsRegisterFragment.java @@ -3,18 +3,20 @@ import android.os.Bundle; import android.view.View; -import androidx.annotation.NonNull; - import org.smartregister.chw.R; import org.smartregister.chw.core.fragment.CoreAllClientsRegisterFragment; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.dao.FamilyDao; import org.smartregister.chw.model.FamilyDetailsModel; +import org.smartregister.chw.provider.OpdRegisterProvider; import org.smartregister.chw.util.AllClientsUtils; import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; import org.smartregister.family.util.Constants; import org.smartregister.opd.utils.OpdDbConstants; +import androidx.annotation.NonNull; + public class AllClientsRegisterFragment extends CoreAllClientsRegisterFragment { public static final String REGISTER_TYPE = "register_type"; @@ -47,7 +49,7 @@ protected void goToClientDetailActivity(@NonNull CommonPersonObjectClient common AllClientsUtils.goToChildProfile(this.getActivity(), commonPersonObjectClient, bundle); break; case CoreConstants.REGISTER_TYPE.ANC: - AllClientsUtils.goToAncProfile(this.getActivity(), commonPersonObjectClient, bundle); + AllClientsUtils.goToAncProfile(this.getActivity(), commonPersonObjectClient); break; case CoreConstants.REGISTER_TYPE.PNC: AllClientsUtils.gotToPncProfile(this.getActivity(), commonPersonObjectClient, bundle); @@ -58,6 +60,19 @@ protected void goToClientDetailActivity(@NonNull CommonPersonObjectClient common case CoreConstants.REGISTER_TYPE.FAMILY_PLANNING: AllClientsUtils.goToFamilyPlanningProfile(this.getActivity(), commonPersonObjectClient); break; + case CoreConstants.REGISTER_TYPE.TB: + AllClientsUtils.goToTbProfile(this.getActivity(), commonPersonObjectClient); + break; + case CoreConstants.REGISTER_TYPE.HIV: + case CoreConstants.REGISTER_TYPE.CBHS: + AllClientsUtils.goToHivProfile(this.getActivity(), commonPersonObjectClient); + break; + case CoreConstants.REGISTER_TYPE.AGYW: + AllClientsUtils.goToAgywProfile(this.getActivity(), commonPersonObjectClient); + break; + case CoreConstants.REGISTER_TYPE.KVP_PrEP: + AllClientsUtils.goToKvpPrepProfile(this.getActivity(), commonPersonObjectClient); + break; default: AllClientsUtils.goToOtherMemberProfile(this.getActivity(), commonPersonObjectClient, bundle, familyDetailsModel.getFamilyHead(), familyDetailsModel.getPrimaryCareGiver()); @@ -70,4 +85,13 @@ protected void goToClientDetailActivity(@NonNull CommonPersonObjectClient common } } } + + + @Override + public void initializeAdapter() { + OpdRegisterProvider childRegisterProvider = new OpdRegisterProvider(getActivity(), registerActionHandler, paginationViewHandler); + clientAdapter = new RecyclerViewPaginatedAdapter(null, childRegisterProvider, context().commonrepository(this.tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllMaleClientsRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllMaleClientsRegisterFragment.java new file mode 100644 index 0000000000..33abab4044 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AllMaleClientsRegisterFragment.java @@ -0,0 +1,62 @@ +package org.smartregister.chw.fragment; + +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import org.smartregister.chw.R; +import org.smartregister.chw.configs.AllClientsRegisterRowOptions; +import org.smartregister.chw.core.fragment.CoreAllClientsRegisterFragment; +import org.smartregister.chw.provider.ChwAllMaleClientsQueryProvider; +import org.smartregister.chw.provider.ChwMaleClientRegisterProvider; + +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; +import org.smartregister.opd.configuration.OpdConfiguration; +import org.smartregister.opd.utils.ConfigurationInstancesHelper; + +import androidx.annotation.Nullable; +import androidx.appcompat.widget.Toolbar; + + + + +public class AllMaleClientsRegisterFragment extends CoreAllClientsRegisterFragment { + + @Nullable + @Override + public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + OpdConfiguration opdConfiguration = new OpdConfiguration.Builder(ChwAllMaleClientsQueryProvider.class) + .setBottomNavigationEnabled(true) + .setOpdRegisterRowOptions(AllClientsRegisterRowOptions.class) + .build(); + + setOpdRegisterQueryProvider(ConfigurationInstancesHelper.newInstance(opdConfiguration.getOpdRegisterQueryProvider())); + return rootView; + } + + @Override + public void setupViews(View view) { + super.setupViews(view); + View dueOnlyLayout = view.findViewById(R.id.due_only_layout); + Toolbar toolbar = view.findViewById(org.smartregister.R.id.register_toolbar); + toolbar.setVisibility(View.INVISIBLE); + ViewGroup.LayoutParams layoutParams = toolbar.getLayoutParams(); + layoutParams.height = 20; + toolbar.setLayoutParams(layoutParams); + + dueOnlyLayout.setVisibility(View.GONE); + } + + + @Override + public void initializeAdapter() { + ChwMaleClientRegisterProvider maleClientRegisterProvider = new ChwMaleClientRegisterProvider(getActivity(), registerActionHandler, paginationViewHandler); + CommonRepository commonRepository = context().commonrepository(this.tablename); + clientAdapter = new RecyclerViewPaginatedAdapter(null, maleClientRegisterProvider, commonRepository); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AncPartnerFollowupRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AncPartnerFollowupRegisterFragment.java new file mode 100644 index 0000000000..b24a28664e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/AncPartnerFollowupRegisterFragment.java @@ -0,0 +1,93 @@ +package org.smartregister.chw.fragment; + +import android.app.Activity; +import android.database.Cursor; + +import org.apache.commons.lang3.StringUtils; +import org.smartregister.chw.R; +import org.smartregister.chw.activity.AncHomeVisitActivity; +import org.smartregister.chw.activity.AncPartnerFollowupReferralProfileActivity; +import org.smartregister.chw.anc.util.DBConstants; +import org.smartregister.chw.core.fragment.CoreAncRegisterFragment; +import org.smartregister.chw.core.provider.ChwAncRegisterProvider; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.model.AncPartnerFollowupRegisterFragmentModel; +import org.smartregister.chw.presenter.ChwAncPartnerFollowupRegisterFragmentPresenter; +import org.smartregister.chw.provider.AncFollowupRegisterProvider; +import org.smartregister.chw.util.Constants; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.configurableviews.model.View; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; + +import java.util.Set; + +import timber.log.Timber; + +public class AncPartnerFollowupRegisterFragment extends CoreAncRegisterFragment { + @Override + public void initializeAdapter(Set visibleColumns) { + ChwAncRegisterProvider provider = new AncFollowupRegisterProvider(getActivity(), commonRepository(), visibleColumns, registerActionHandler, paginationViewHandler); + clientAdapter = new RecyclerViewPaginatedAdapter(null, provider, context().commonrepository(this.tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + presenter = new ChwAncPartnerFollowupRegisterFragmentPresenter(this, new AncPartnerFollowupRegisterFragmentModel(), null); + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + AncPartnerFollowupReferralProfileActivity.startMe(getActivity(), client.getCaseId(),client.getColumnmaps().get(Constants.PartnerRegistrationConstants.FormSubmissionId)); + } + + @Override + protected void openHomeVisit(CommonPersonObjectClient client) { + Activity activity = getActivity(); + if (activity == null) + return; + + AncHomeVisitActivity.startMe(activity, client.getCaseId(), false); + } + + @Override + public void countExecute() { + Cursor cursor = null; + try { + + String query = "select count(*) from " + presenter().getMainTable() + + " inner join " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + " on " + presenter().getMainTable() + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + + " inner join " + CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + " on " + presenter().getMainTable() + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + ".entity_id" + + " where " + presenter().getMainCondition(); + + if (StringUtils.isNotBlank(filters)) + query = query + getFilterString(); + + cursor = commonRepository().rawCustomQueryForAdapter(query); + cursor.moveToFirst(); + clientAdapter.setTotalcount(cursor.getInt(0)); + Timber.v("total count here %d", clientAdapter.getTotalcount()); + + clientAdapter.setCurrentlimit(20); + clientAdapter.setCurrentoffset(0); + + + } catch (Exception e) { + Timber.e(e); + } finally { + if (cursor != null) { + cursor.close(); + } + } + } + + @Override + public void setupViews(android.view.View view) { + super.setupViews(view); + titleLabelView.setText(R.string.action_received_anc_partner_followup_referrals); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpReceiveFromOrganizationsRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpReceiveFromOrganizationsRegisterFragment.java new file mode 100644 index 0000000000..e30c00617c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpReceiveFromOrganizationsRegisterFragment.java @@ -0,0 +1,15 @@ +package org.smartregister.chw.fragment; + +import android.content.Intent; + +import org.json.JSONObject; +import org.smartregister.chw.core.fragment.CoreCdpReceiveMsdRegisterFragment; +import org.smartregister.family.util.JsonFormUtils; + +public class CdpReceiveFromOrganizationsRegisterFragment extends CoreCdpReceiveMsdRegisterFragment { + @Override + public void startFormActivity(JSONObject form) { + Intent intent = org.smartregister.chw.core.utils.Utils.formActivityIntent(requireActivity(), form.toString()); + requireActivity().startActivityForResult(intent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpRegisterFragment.java new file mode 100644 index 0000000000..61eacadf7a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CdpRegisterFragment.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.activity.CdpProfileActivity; +import org.smartregister.chw.core.fragment.CoreCdpRegisterFragment; + +public class CdpRegisterFragment extends CoreCdpRegisterFragment { + + @Override + protected void openProfile(String baseEntityId) { + CdpProfileActivity.startProfile(getActivity(), baseEntityId); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CompletedReferralRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CompletedReferralRegisterFragment.java new file mode 100644 index 0000000000..39974e2140 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/CompletedReferralRegisterFragment.java @@ -0,0 +1,309 @@ +package org.smartregister.chw.fragment; + +import android.database.Cursor; +import android.os.Bundle; +import android.view.View; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; +import org.smartregister.chw.R; +import org.smartregister.chw.activity.ChwReferralDetailsViewActivity; +import org.smartregister.chw.activity.MalariaFollowUpVisitActivity; +import org.smartregister.chw.anc.util.DBConstants; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.core.utils.QueryBuilder; +import org.smartregister.chw.model.ReferralRegisterFragmentModel; +import org.smartregister.chw.presenter.CompletedReferralRegisterFragmentPresenter; +import org.smartregister.chw.referral.contract.BaseReferralRegisterFragmentContract; +import org.smartregister.chw.referral.domain.MemberObject; +import org.smartregister.chw.referral.fragment.BaseReferralRegisterFragment; +import org.smartregister.chw.referral.provider.ReferralRegisterProvider; +import org.smartregister.chw.util.Constants; +import org.smartregister.chw.util.Utils; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.view.activity.BaseRegisterActivity; +import org.smartregister.view.contract.BaseRegisterFragmentContract; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import androidx.appcompat.widget.Toolbar; +import androidx.loader.content.CursorLoader; +import androidx.loader.content.Loader; +import timber.log.Timber; + +public class CompletedReferralRegisterFragment extends BaseReferralRegisterFragment { + + private static final String DUE_FILTER_TAG = "PRESSED"; + private View view; + private View dueOnlyLayout; + private boolean dueFilterActive = false; + + @Override + public void initializeAdapter(@Nullable Set visibleColumns) { + ReferralRegisterProvider referralRegisterProvider = new ReferralRegisterProvider(getActivity(), paginationViewHandler, registerActionHandler, visibleColumns); + clientAdapter = new RecyclerViewPaginatedAdapter(null, referralRegisterProvider, context().commonrepository(this.tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } + + @Override + public void setupViews(View view) { + super.setupViews(view); + this.view = view; + + Toolbar toolbar = view.findViewById(org.smartregister.R.id.register_toolbar); + toolbar.setContentInsetsAbsolute(0, 0); + toolbar.setContentInsetsRelative(0, 0); + toolbar.setContentInsetStartWithNavigation(0); + + NavigationMenu.getInstance(getActivity(), null, toolbar); + + View navbarContainer = view.findViewById(R.id.register_nav_bar_container); + navbarContainer.setFocusable(false); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); + View searchBarLayout = view.findViewById(R.id.search_bar_layout); + searchBarLayout.setLayoutParams(params); + searchBarLayout.setBackgroundResource(R.color.chw_primary); + searchBarLayout.setPadding(searchBarLayout.getPaddingLeft(), searchBarLayout.getPaddingTop(), searchBarLayout.getPaddingRight(), (int) Utils.convertDpToPixel(10, getActivity())); + + CustomFontTextView titleView = view.findViewById(R.id.txt_title_label); + if (titleView != null) { + titleView.setPadding(0, titleView.getTop(), titleView.getPaddingRight(), titleView.getPaddingBottom()); + } + + View topLeftLayout = view.findViewById(R.id.top_left_layout); + topLeftLayout.setVisibility(View.GONE); + + View topRightLayout = view.findViewById(R.id.top_right_layout); + topRightLayout.setVisibility(View.VISIBLE); + + View sortFilterBarLayout = view.findViewById(R.id.register_sort_filter_bar_layout); + sortFilterBarLayout.setVisibility(View.GONE); + + View filterSortLayout = view.findViewById(R.id.filter_sort_layout); + filterSortLayout.setVisibility(View.GONE); + + dueOnlyLayout = view.findViewById(R.id.due_only_layout); + dueOnlyLayout.setVisibility(View.GONE); + + if (getSearchView() != null) { + getSearchView().setBackgroundResource(org.smartregister.family.R.color.white); + getSearchView().setCompoundDrawablesWithIntrinsicBounds(org.smartregister.family.R.drawable.ic_action_search, 0, 0, 0); + getSearchView().setTextColor(getResources().getColor(R.color.text_black)); + } + } + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = ((BaseRegisterActivity) getActivity()).getViewIdentifiers().get(0); + presenter = (BaseRegisterFragmentContract.Presenter) new CompletedReferralRegisterFragmentPresenter((BaseReferralRegisterFragmentContract.View) this, (BaseReferralRegisterFragmentContract.Model) new ReferralRegisterFragmentModel(), viewConfigurationIdentifier); + } + + @Override + public void setAdvancedSearchFormData(HashMap hashMap) { + //TODO + //Log.d(TAG, "setAdvancedSearchFormData unimplemented"); + } + + @Override + protected void onViewClicked(View view) { + super.onViewClicked(view); + + if (view.getId() == R.id.due_only_layout) { + toggleFilterSelection(view); + } + } + + protected void toggleFilterSelection(View dueOnlyLayout) { + if (dueOnlyLayout != null) { + if (dueOnlyLayout.getTag() == null) { + dueFilterActive = true; + dueFilter(dueOnlyLayout); + } else if (dueOnlyLayout.getTag().toString().equals(DUE_FILTER_TAG)) { + dueFilterActive = false; + normalFilter(dueOnlyLayout); + } + } + } + + protected String searchText() { + return (getSearchView() == null) ? "" : getSearchView().getText().toString(); + } + + private void switchViews(View dueOnlyLayout, boolean isPress) { + TextView dueOnlyTextView = dueOnlyLayout.findViewById(R.id.due_only_text_view); + if (isPress) { + dueOnlyTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_due_filter_on, 0); + } else { + dueOnlyTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_due_filter_off, 0); + + } + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + ChwReferralDetailsViewActivity.startChwReferralDetailsViewActivity(getActivity(), new MemberObject(client), client); + } + + @Override + protected void openFollowUpVisit(CommonPersonObjectClient client) { + MalariaFollowUpVisitActivity.startMalariaRegistrationActivity(getActivity(), client.getCaseId(), null); + } + + @Override + protected void onResumption() { + if (dueFilterActive && dueOnlyLayout != null) { + dueFilter(dueOnlyLayout); + } else { + super.onResumption(); + } + } + + @Override + public void onResume() { + super.onResume(); + + Toolbar toolbar = view.findViewById(org.smartregister.R.id.register_toolbar); + toolbar.setContentInsetsAbsolute(0, 0); + toolbar.setContentInsetsRelative(0, 0); + toolbar.setContentInsetStartWithNavigation(0); + NavigationMenu.getInstance(getActivity(), null, toolbar); + } + + @Override + protected void refreshSyncProgressSpinner() { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(View.GONE); + } + if (syncButton != null) { + syncButton.setVisibility(View.GONE); + } + } + + private String defaultFilterAndSortQuery() { + SmartRegisterQueryBuilder sqb = new SmartRegisterQueryBuilder(mainSelect); + + String query = ""; + StringBuilder customFilter = new StringBuilder(); + if (StringUtils.isNotBlank(filters)) { + customFilter.append(MessageFormat.format(" and ( {0}.{1} like ''%{2}%'' ", Constants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.FIRST_NAME, filters)); + customFilter.append(MessageFormat.format(" or {0}.{1} like ''%{2}%'' ", Constants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.LAST_NAME, filters)); + customFilter.append(MessageFormat.format(" or {0}.{1} like ''%{2}%'' ", Constants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.MIDDLE_NAME, filters)); + customFilter.append(MessageFormat.format(" or {0}.{1} like ''%{2}%'' ) ", Constants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.UNIQUE_ID, filters)); + + } + if (dueFilterActive) { + customFilter.append(MessageFormat.format(" and ( {0}) ", presenter().getDueFilterCondition())); + } + try { + if (isValidFilterForFts(commonRepository())) { + + String myquery = QueryBuilder.getQuery(joinTables, mainCondition, tablename, customFilter.toString(), clientAdapter, Sortqueries); + List ids = commonRepository().findSearchIds(myquery); + query = sqb.toStringFts(ids, tablename, CommonRepository.ID_COLUMN, + Sortqueries); + query = sqb.Endquery(query); + } else { + sqb.addCondition(customFilter.toString()); + query = sqb.orderbyCondition(Sortqueries); + query = sqb.Endquery(sqb.addlimitandOffset(query, clientAdapter.getCurrentlimit(), clientAdapter.getCurrentoffset())); + + } + } catch (Exception e) { + Timber.e(e); + } + + return query; + } + + + @Override + public void countExecute() { + Cursor c = null; + try { + + String query = "select count(*) from " + presenter().getMainTable() + " inner join " + Constants.TABLE_NAME.FAMILY_MEMBER + + " on " + presenter().getMainTable() + ".entity_id = " + + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + + " inner join task on task.for = ec_family_member.base_entity_id"+ + " where " + presenter().getMainCondition(); + + if (StringUtils.isNotBlank(filters)) { + query = query + " and ( " + filters + " ) "; + } + + if (dueFilterActive) { + query = query + " and ( " + presenter().getDueFilterCondition() + " ) "; + } + + c = commonRepository().rawCustomQueryForAdapter(query); + c.moveToFirst(); + clientAdapter.setTotalcount(c.getInt(0)); + Timber.v("total count here %s", clientAdapter.getTotalcount()); + + clientAdapter.setCurrentlimit(20); + clientAdapter.setCurrentoffset(0); + + } catch (Exception e) { + Timber.e(e); + } finally { + if (c != null) { + c.close(); + } + } + } + + @Override + public Loader onCreateLoader(int id, final Bundle args) { + if (id == LOADER_ID) { + return new CursorLoader(getActivity()) { + @Override + public Cursor loadInBackground() { + // Count query + final String COUNT = "count_execute"; + if (args != null && args.getBoolean(COUNT)) { + countExecute(); + } + String query = defaultFilterAndSortQuery(); + return commonRepository().rawCustomQueryForAdapter(query); + } + }; + } + return super.onCreateLoader(id, args); + } + + protected void dueFilter(View dueOnlyLayout) { + filterDue(searchText(), "", presenter().getDueFilterCondition()); + dueOnlyLayout.setTag(DUE_FILTER_TAG); + switchViews(dueOnlyLayout, true); + } + + protected void normalFilter(View dueOnlyLayout) { + filterDue(searchText(), "", presenter().getMainCondition()); + dueOnlyLayout.setTag(null); + switchViews(dueOnlyLayout, false); + } + + protected void filterDue(String filterString, String joinTableString, String mainConditionString) { + filters = filterString; + joinTable = joinTableString; + mainCondition = mainConditionString; + filterandSortExecute(countBundle()); + } + +} + + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivIndexContactsRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivIndexContactsRegisterFragment.java new file mode 100644 index 0000000000..5500c16494 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivIndexContactsRegisterFragment.java @@ -0,0 +1,65 @@ +package org.smartregister.chw.fragment; + +import android.view.View; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.jetbrains.annotations.Nullable; +import org.json.JSONException; +import org.smartregister.chw.R; +import org.smartregister.chw.activity.HivIndexContactProfileActivity; +import org.smartregister.chw.activity.HivIndexContactsContactsRegisterActivity; +import org.smartregister.chw.core.fragment.CoreHivIndexContactsRegisterFragment; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.dao.HivIndexDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.model.HivIndexContactsRegisterFragmentModel; +import org.smartregister.chw.presenter.HivIndexContactsContactsRegisterFragmentPresenter; +import org.smartregister.commonregistry.CommonPersonObjectClient; + +import java.util.Objects; + +import timber.log.Timber; + +public class HivIndexContactsRegisterFragment extends CoreHivIndexContactsRegisterFragment { + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((HivIndexContactsContactsRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (NullPointerException e) { + Timber.e(e); + } + presenter = new HivIndexContactsContactsRegisterFragmentPresenter(this, new HivIndexContactsRegisterFragmentModel(), viewConfigurationIdentifier); + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + if (getActivity() != null) { + HivIndexContactProfileActivity.startHivIndexContactProfileActivity(getActivity(), Objects.requireNonNull(HivIndexDao.getMember(client.getCaseId()))); + } + } + + @Override + protected void onViewClicked(View view) { + if (getActivity() == null) { + return; + } + if (view.getTag() instanceof CommonPersonObjectClient && view.getTag(R.id.VIEW_ID) == CLICK_VIEW_NORMAL) { + openProfile((CommonPersonObjectClient) view.getTag()); + } else if (view.getTag() instanceof CommonPersonObjectClient && view.getTag(R.id.VIEW_ID) == FOLLOW_UP_VISIT) { + try { + HivIndexContactProfileActivity.startHivIndexContactFollowupActivity(getActivity(), HivIndexDao.getMember(((CommonPersonObjectClient) view.getTag()).getCaseId()).getBaseEntityId()); + } catch (JSONException e) { + Timber.e(e); + } + } + } + +} + + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivRegisterFragment.java new file mode 100644 index 0000000000..47645d19c8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivRegisterFragment.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.fragment; + +import org.jetbrains.annotations.Nullable; +import org.json.JSONException; +import org.smartregister.chw.R; +import org.smartregister.chw.activity.HivProfileActivity; +import org.smartregister.chw.activity.HivRegisterActivity; +import org.smartregister.chw.core.fragment.CoreHivRegisterFragment; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.model.HivRegisterFragmentModel; +import org.smartregister.chw.presenter.HivRegisterFragmentPresenter; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.util.Objects; + +import timber.log.Timber; + +public class HivRegisterFragment extends CoreHivRegisterFragment { + @Override + public void setupViews(android.view.View view) { + super.setupViews(view); + ((CustomFontTextView) view.findViewById(R.id.txt_title_label)).setText(getString(R.string.hiv_clients)); + } + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((HivRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (NullPointerException e) { + Timber.e(e); + } + presenter = new HivRegisterFragmentPresenter(this, new HivRegisterFragmentModel(), viewConfigurationIdentifier); + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + if (getActivity() != null) + HivProfileActivity.startHivProfileActivity(getActivity(), Objects.requireNonNull(HivDao.getMember(client.getCaseId()))); + } + + + @Override + protected void openFollowUpVisit(@Nullable HivMemberObject hivMemberObject) { + if (getActivity() != null) { + try { + HivProfileActivity.startHivFollowupActivity(getActivity(), hivMemberObject.getBaseEntityId()); + } catch (JSONException e) { + Timber.e(e); + } + } + + } +} + + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstMobilizationFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstMobilizationFragment.java new file mode 100644 index 0000000000..b93f9e4341 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstMobilizationFragment.java @@ -0,0 +1,36 @@ +package org.smartregister.chw.fragment; + +import android.view.View; + +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.hivst.fragment.BaseHivstMobilizationRegisterFragment; +import org.smartregister.chw.util.JsonFormUtils; + +import timber.log.Timber; + +public class HivstMobilizationFragment extends BaseHivstMobilizationRegisterFragment { + + @Override + public void setupViews(View view) { + super.setupViews(view); + try { + NavigationMenu.getInstance(getActivity(), null, toolbar); + } catch (NullPointerException e) { + Timber.e(e); + } + } + + @Override + protected void onResumption() { + super.onResumption(); + NavigationMenu.getInstance(getActivity(), null, toolbar); + } + + + @Override + protected void startForm(JSONObject form) { + requireActivity().startActivityForResult(org.smartregister.chw.core.utils.FormUtils.getStartFormActivity(form, requireActivity().getString(R.string.hivst_mobilization), requireActivity()), JsonFormUtils.REQUEST_CODE_GET_JSON); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstRegisterFragment.java new file mode 100644 index 0000000000..b38d7b8a18 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstRegisterFragment.java @@ -0,0 +1,12 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.activity.HivstProfileActivity; +import org.smartregister.chw.core.fragment.CoreHivstRegisterFragment; + +public class HivstRegisterFragment extends CoreHivstRegisterFragment { + + @Override + protected void openProfile(String baseEntityId) { + HivstProfileActivity.startProfile(requireActivity(), baseEntityId); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstResultsViewFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstResultsViewFragment.java new file mode 100644 index 0000000000..3bfd9fd91e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/HivstResultsViewFragment.java @@ -0,0 +1,44 @@ +package org.smartregister.chw.fragment; + +import android.os.Bundle; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.activity.HivstResultViewActivity; +import org.smartregister.chw.hivst.fragment.BaseHivstResultViewFragment; +import org.smartregister.chw.hivst.util.Constants; +import org.smartregister.chw.hivst.util.DBConstants; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.util.Utils; + +public class HivstResultsViewFragment extends BaseHivstResultViewFragment { + + public static HivstResultsViewFragment newInstance(String baseEntityId) { + HivstResultsViewFragment hivstResultsViewFragment = new HivstResultsViewFragment(); + Bundle b = new Bundle(); + b.putString(Constants.ACTIVITY_PAYLOAD.BASE_ENTITY_ID, baseEntityId); + hivstResultsViewFragment.setArguments(b); + return hivstResultsViewFragment; + } + + + @Override + public void openResultsForm(CommonPersonObjectClient client) { + String baseEntityId = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.BASE_ENTITY_ID, false); + String entityId = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.ENTITY_ID, false); + String kitFor = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.KIT_FOR, false); + String clientTestingApproach = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.CLIENT_TESTING_APPROACH, false); + try { + JSONObject jsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(requireContext(), Constants.FORMS.HIVST_RECORD_RESULTS); + JSONObject global = jsonObject.getJSONObject("global"); + global.putOpt("kit_for", kitFor); + global.putOpt("client_testing_approach", clientTestingApproach); + HivstResultViewActivity.startResultsForm(getContext(), jsonObject.toString(), baseEntityId, entityId); + } catch (JSONException e) { + e.printStackTrace(); + } + + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/IndividualProfileRemoveFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/IndividualProfileRemoveFragment.java index 91f89b1e97..859bf42669 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/IndividualProfileRemoveFragment.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/IndividualProfileRemoveFragment.java @@ -69,13 +69,20 @@ public void onMemberRemoved(String removalType) { if (getActivity() != null) { if (getActivity() instanceof IndividualProfileRemoveActivity) { getActivity().finish(); + + Intent intent = new Intent(getActivity(), AllClientsRegisterActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); if (familyBaseEntityId != null) { //Independent clients don't belong to family CommonPersonObject personObject = getCommonRepository(Utils.metadata().familyRegister.tableName).findByBaseEntityId(familyBaseEntityId); - CommonPersonObjectClient pClient = new CommonPersonObjectClient(personObject.getCaseId(), - personObject.getDetails(), ""); - pClient.setColumnmaps(personObject.getColumnmaps()); - - goToPatientDetailActivity(pClient); + if (personObject != null) { + CommonPersonObjectClient pClient = new CommonPersonObjectClient(personObject.getCaseId(), + personObject.getDetails(), ""); + pClient.setColumnmaps(personObject.getColumnmaps()); + + goToPatientDetailActivity(pClient); + } else { + startActivity(intent); + } } } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/KvpPrEPRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/KvpPrEPRegisterFragment.java new file mode 100644 index 0000000000..f0e1a32559 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/KvpPrEPRegisterFragment.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.R; +import org.smartregister.chw.activity.KvpPrEPProfileActivity; +import org.smartregister.chw.core.fragment.CoreKvpRegisterFragment; + +public class KvpPrEPRegisterFragment extends CoreKvpRegisterFragment { + + @Override + protected void openProfile(String baseEntityId) { + KvpPrEPProfileActivity.startProfileActivity(requireActivity(), baseEntityId); + } + + @Override + protected int getTitleString() { + return R.string.menu_kvp; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/LTFUReferralsRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/LTFUReferralsRegisterFragment.java new file mode 100644 index 0000000000..43c7705edf --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/LTFUReferralsRegisterFragment.java @@ -0,0 +1,86 @@ +package org.smartregister.chw.fragment; + +import android.os.Handler; + +import org.smartregister.chw.R; +import org.smartregister.chw.activity.LTFUReferralsDetailsViewActivity; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.fragment.BaseReferralRegisterFragment; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.Utils; +import org.smartregister.chw.presenter.LTFUReferralFragmentPresenter; +import org.smartregister.chw.provider.LTFURegisterProvider; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.configurableviews.model.View; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; +import org.smartregister.domain.Task; +import org.smartregister.family.util.DBConstants; + +import java.util.Set; + +public class LTFUReferralsRegisterFragment extends BaseReferralRegisterFragment { + public Handler handler = new Handler(); + private LTFUReferralFragmentPresenter referralFragmentPresenter; + private CommonPersonObjectClient commonPersonObjectClient; + + @Override + public void initializeAdapter(Set visibleColumns, String tableName) { + LTFURegisterProvider registerProvider = new LTFURegisterProvider(getActivity(), registerActionHandler, paginationViewHandler); + clientAdapter = new RecyclerViewPaginatedAdapter(null, registerProvider, context().commonrepository(tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } + + @Override + public void setClient(CommonPersonObjectClient commonPersonObjectClient) { + setCommonPersonObjectClient(commonPersonObjectClient); + } + + @Override + protected int getToolBarTitle() { + return R.string.menu_ltfu; + } + + @Override + protected String getMainCondition() { + return "task.business_status = '" + CoreConstants.BUSINESS_STATUS.REFERRED + "' and ec_family_member_search.date_removed is null"; + } + + @Override + public CommonPersonObjectClient getCommonPersonObjectClient() { + return commonPersonObjectClient; + } + + @Override + public void setCommonPersonObjectClient(CommonPersonObjectClient commonPersonObjectClient) { + this.commonPersonObjectClient = commonPersonObjectClient; + } + + @Override + protected void initializePresenter() { + referralFragmentPresenter = new LTFUReferralFragmentPresenter(this); + presenter = referralFragmentPresenter; + + } + + @Override + protected void onViewClicked(android.view.View view) { + CommonPersonObjectClient client = (CommonPersonObjectClient) view.getTag(); + referralFragmentPresenter.setBaseEntityId(Utils.getValue(client.getColumnmaps(), DBConstants.KEY.BASE_ENTITY_ID, false)); + referralFragmentPresenter.fetchClient(); + + Task task = getTask(Utils.getValue(client.getColumnmaps(), "_id", false)); + referralFragmentPresenter.setTasksFocus(task.getFocus()); + goToReferralsDetails(client); + + } + + private Task getTask(String taskId) { + return ChwApplication.getInstance().getTaskRepository().getTaskByIdentifier(taskId); + } + + private void goToReferralsDetails(CommonPersonObjectClient client) { + handler.postDelayed(() -> LTFUReferralsDetailsViewActivity.startLTFUReferralsDetailsViewActivity(getActivity(), client, getTask(Utils.getValue(client.getColumnmaps(), "_id", false)), CoreConstants.REGISTERED_ACTIVITIES.LTFU_REFERRALS_REGISTER_ACTIVITY), 100); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MalariaRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MalariaRegisterFragment.java index 46b080d5de..c8b12482b0 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MalariaRegisterFragment.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MalariaRegisterFragment.java @@ -6,6 +6,7 @@ import org.smartregister.chw.activity.MalariaProfileActivity; import org.smartregister.chw.core.fragment.CoreMalariaRegisterFragment; import org.smartregister.chw.core.model.CoreMalariaRegisterFragmentModel; +import org.smartregister.chw.model.MalariaRegisterFragmentModel; import org.smartregister.chw.presenter.MalariaRegisterFragmentPresenter; import org.smartregister.view.activity.BaseRegisterActivity; @@ -17,7 +18,7 @@ protected void initializePresenter() { return; } String viewConfigurationIdentifier = ((BaseRegisterActivity) getActivity()).getViewIdentifiers().get(0); - presenter = new MalariaRegisterFragmentPresenter(this, new CoreMalariaRegisterFragmentModel(), viewConfigurationIdentifier); + presenter = new MalariaRegisterFragmentPresenter(this, new MalariaRegisterFragmentModel(), viewConfigurationIdentifier); } @Override diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MotherChampionRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MotherChampionRegisterFragment.java new file mode 100644 index 0000000000..4438439d3a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/MotherChampionRegisterFragment.java @@ -0,0 +1,76 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.R; +import org.smartregister.chw.activity.MotherChampionProfileActivity; +import org.smartregister.chw.activity.MotherChampionRegisterActivity; +import org.smartregister.chw.core.fragment.CorePmtctRegisterFragment; +import org.smartregister.chw.model.MotherChampionRegisterFragmentModel; +import org.smartregister.chw.presenter.MotherChampionRegisterFragmentPresenter; +import org.smartregister.chw.provider.MotherChampionRegisterProvider; +import org.smartregister.configurableviews.model.View; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; + +import java.util.Set; + +import timber.log.Timber; + +public class MotherChampionRegisterFragment extends CorePmtctRegisterFragment { + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((MotherChampionRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (Exception e) { + Timber.e(e); + } + + presenter = new MotherChampionRegisterFragmentPresenter(this, new MotherChampionRegisterFragmentModel(), viewConfigurationIdentifier); + + } + + @Override + protected void openProfile(String baseEntityId) { + MotherChampionProfileActivity.startProfile(getActivity(), baseEntityId); + } + + @Override + public void setupViews(android.view.View view) { + super.setupViews(view); + titleLabelView.setText(R.string.mother_champion_community_services); + } + + @Override + public void initializeAdapter(Set visibleColumns) { + MotherChampionRegisterProvider motherChampionRegisterProvider = new MotherChampionRegisterProvider(getActivity(), paginationViewHandler, registerActionHandler, visibleColumns); + clientAdapter = new RecyclerViewPaginatedAdapter(null, motherChampionRegisterProvider, context().commonrepository(this.tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } + + @Override + protected void openFollowUpVisit(String baseEntityId) { + // PmtctFollowUpVisitActivity.startPmtctFollowUpActivity(getActivity(),baseEntityId); + } + + @Override + protected void refreshSyncProgressSpinner() { + if (isSyncing()) { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(android.view.View.VISIBLE); + } + if (syncButton != null) { + syncButton.setVisibility(android.view.View.GONE); + } + } else { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(android.view.View.GONE); + } + if (syncButton != null) { + syncButton.setVisibility(android.view.View.GONE); + } + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/OrdersRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/OrdersRegisterFragment.java new file mode 100644 index 0000000000..d954b947cb --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/OrdersRegisterFragment.java @@ -0,0 +1,67 @@ +package org.smartregister.chw.fragment; + +import static com.vijay.jsonwizard.constants.JsonFormConstants.VALUE; + +import android.content.Intent; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.smartregister.chw.activity.OrderDetailsActivity; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.core.fragment.CoreOrdersRegisterFragment; +import org.smartregister.chw.presenter.OrdersRegisterFragmentPresenter; +import org.smartregister.chw.referral.util.JsonFormConstants; +import org.smartregister.chw.util.JsonFormUtils; +import org.smartregister.commonregistry.CommonPersonObjectClient; + +import static org.smartregister.chw.core.utils.FormUtils.getStartFormActivity; +import static org.smartregister.chw.util.Constants.JsonFormConstants.STEP1; +import static org.smartregister.util.Utils.getAllSharedPreferences; + +import timber.log.Timber; + +public class OrdersRegisterFragment extends CoreOrdersRegisterFragment { + + /** + * Starts the CDP condom order form + */ + @Override + public void startOrderForm() { + try { + // Get the order form as a JSONObject + JSONObject form = model().getOrderFormAsJson(Constants.FORMS.CDP_CONDOM_ORDER); + + // Get the user's name from shared preferences + String userName = getAllSharedPreferences().getPreference("anmIdentifier"); + String providerFullName = getAllSharedPreferences().getPreference(userName); + + // Get the fields of the form + JSONArray fields = form.getJSONObject(STEP1).getJSONArray(JsonFormConstants.FIELDS); + + // Get the "requester" field and set its value to the provider's full name + JSONObject requesterField = org.smartregister.util.JsonFormUtils.getFieldJSONObject(fields, "requester"); + requesterField.put(VALUE, providerFullName); + + // Create an intent to start the form activity + Intent startFormIntent = getStartFormActivity(form, null, requireActivity()); + + // Start the form activity for result + requireActivity().startActivityForResult(startFormIntent, JsonFormUtils.REQUEST_CODE_GET_JSON); + } catch (Exception e) { + // Print the stack trace of the exception + Timber.e(e); + } + } + + @Override + public void showDetails(CommonPersonObjectClient cp) { + OrderDetailsActivity.startMe(requireActivity(), cp); + } + + @Override + protected void initializePresenter() { + presenter = new OrdersRegisterFragmentPresenter(this, model()); + } + + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PmtctFollowupRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PmtctFollowupRegisterFragment.java new file mode 100644 index 0000000000..87d678fa3a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PmtctFollowupRegisterFragment.java @@ -0,0 +1,76 @@ +package org.smartregister.chw.fragment; + +import org.smartregister.chw.R; +import org.smartregister.chw.activity.MotherChampionRegisterActivity; +import org.smartregister.chw.activity.PmtctFollowupDetailsActivity; +import org.smartregister.chw.core.fragment.CorePmtctRegisterFragment; +import org.smartregister.chw.model.PmtctFollowupRegisterFragmentModel; +import org.smartregister.chw.presenter.PmtctFollowupRegisterFragmentPresenter; +import org.smartregister.chw.provider.MotherChampionRegisterProvider; +import org.smartregister.configurableviews.model.View; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; + +import java.util.Set; + +import timber.log.Timber; + +public class PmtctFollowupRegisterFragment extends CorePmtctRegisterFragment { + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((MotherChampionRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (Exception e) { + Timber.e(e); + } + + presenter = new PmtctFollowupRegisterFragmentPresenter(this, new PmtctFollowupRegisterFragmentModel(), viewConfigurationIdentifier); + + } + + @Override + protected void openProfile(String baseEntityId) { + PmtctFollowupDetailsActivity.startPmtctDetailsActivity(getActivity(), baseEntityId); + } + + @Override + public void setupViews(android.view.View view) { + super.setupViews(view); + titleLabelView.setText(R.string.missap_and_ltf_followups); + } + + @Override + public void initializeAdapter(Set visibleColumns) { + MotherChampionRegisterProvider motherChampionRegisterProvider = new MotherChampionRegisterProvider(getActivity(), paginationViewHandler, registerActionHandler, visibleColumns); + clientAdapter = new RecyclerViewPaginatedAdapter(null, motherChampionRegisterProvider, context().commonrepository(this.tablename)); + clientAdapter.setCurrentlimit(20); + clientsView.setAdapter(clientAdapter); + } + + @Override + protected void openFollowUpVisit(String baseEntityId) { + // PmtctFollowUpVisitActivity.startPmtctFollowUpActivity(getActivity(),baseEntityId); + } + + @Override + protected void refreshSyncProgressSpinner() { + if (isSyncing()) { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(android.view.View.VISIBLE); + } + if (syncButton != null) { + syncButton.setVisibility(android.view.View.GONE); + } + } else { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(android.view.View.GONE); + } + if (syncButton != null) { + syncButton.setVisibility(android.view.View.GONE); + } + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PncRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PncRegisterFragment.java index b2128c2648..01ce3f2379 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PncRegisterFragment.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/PncRegisterFragment.java @@ -1,13 +1,23 @@ package org.smartregister.chw.fragment; +import android.database.Cursor; + +import org.apache.commons.lang3.StringUtils; import org.smartregister.chw.activity.PncHomeVisitActivity; import org.smartregister.chw.activity.PncMemberProfileActivity; import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.util.DBConstants; import org.smartregister.chw.core.fragment.CorePncRegisterFragment; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.QueryGenerator; import org.smartregister.chw.model.ChwPncRegisterFragmentModel; import org.smartregister.chw.presenter.PncRegisterFragmentPresenter; import org.smartregister.commonregistry.CommonPersonObjectClient; +import java.text.MessageFormat; + +import timber.log.Timber; + public class PncRegisterFragment extends CorePncRegisterFragment { @Override @@ -29,4 +39,52 @@ protected void initializePresenter() { presenter = new PncRegisterFragmentPresenter(this, new ChwPncRegisterFragmentModel(), null); } + + @Override + public void countExecute() { + Cursor cursor = null; + try { + String mainTable = presenter().getMainTable(); + + QueryGenerator generator = new QueryGenerator() + .withMainTable(mainTable) + .withColumn("count(*)") + .withJoinClause("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + " ON " + + mainTable + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID) + + .withWhereClause(getCountMainCondition()); + + if (dueFilterActive) + generator.withWhereClause(getDueCondition()); + + if (StringUtils.isNotBlank(filters)) + generator.withWhereClause(getSearchFilter(filters)); + + cursor = commonRepository().rawCustomQueryForAdapter(generator.generateQuery()); + cursor.moveToFirst(); + clientAdapter.setTotalcount(cursor.getInt(0)); + Timber.v("total count here %d", clientAdapter.getTotalcount()); + + clientAdapter.setCurrentlimit(20); + clientAdapter.setCurrentoffset(0); + } catch (Exception e) { + Timber.e(e); + } finally { + if (cursor != null) { + cursor.close(); + } + } + } + + private String getSearchFilter(String search) { + return MessageFormat.format(" {0}.{1} like ''%{2}%'' ", CoreConstants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.FIRST_NAME, search) + + MessageFormat.format(" or {0}.{1} like ''%{2}%'' ", CoreConstants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.LAST_NAME, search) + + MessageFormat.format(" or {0}.{1} like ''%{2}%'' ", CoreConstants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.MIDDLE_NAME, search) + + MessageFormat.format(" or {0}.{1} like ''%{2}%'' ", CoreConstants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.UNIQUE_ID, search); + } + + private String getCountMainCondition() { + return " " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DATE_REMOVED + " is null "; + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/ReferralRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/ReferralRegisterFragment.java index acedeb0c88..47cc2bd819 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/ReferralRegisterFragment.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/ReferralRegisterFragment.java @@ -6,20 +6,17 @@ import android.widget.LinearLayout; import android.widget.TextView; -import androidx.appcompat.widget.Toolbar; -import androidx.loader.content.CursorLoader; -import androidx.loader.content.Loader; - import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.smartregister.chw.R; +import org.smartregister.chw.activity.ChwReferralDetailsViewActivity; import org.smartregister.chw.activity.MalariaFollowUpVisitActivity; import org.smartregister.chw.anc.util.DBConstants; import org.smartregister.chw.core.custom_views.NavigationMenu; import org.smartregister.chw.core.utils.QueryBuilder; import org.smartregister.chw.model.ReferralRegisterFragmentModel; import org.smartregister.chw.presenter.ReferralRegisterFragmentPresenter; -import org.smartregister.chw.referral.activity.ReferralDetailsViewActivity; +import org.smartregister.chw.referral.contract.BaseReferralRegisterFragmentContract; import org.smartregister.chw.referral.domain.MemberObject; import org.smartregister.chw.referral.fragment.BaseReferralRegisterFragment; import org.smartregister.chw.referral.provider.ReferralRegisterProvider; @@ -30,6 +27,7 @@ import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; import org.smartregister.view.activity.BaseRegisterActivity; +import org.smartregister.view.contract.BaseRegisterFragmentContract; import org.smartregister.view.customcontrols.CustomFontTextView; import java.text.MessageFormat; @@ -37,6 +35,9 @@ import java.util.List; import java.util.Set; +import androidx.appcompat.widget.Toolbar; +import androidx.loader.content.CursorLoader; +import androidx.loader.content.Loader; import timber.log.Timber; public class ReferralRegisterFragment extends BaseReferralRegisterFragment { @@ -109,7 +110,7 @@ protected void initializePresenter() { return; } String viewConfigurationIdentifier = ((BaseRegisterActivity) getActivity()).getViewIdentifiers().get(0); - presenter = new ReferralRegisterFragmentPresenter(this, new ReferralRegisterFragmentModel(), viewConfigurationIdentifier); + presenter = (BaseRegisterFragmentContract.Presenter) new ReferralRegisterFragmentPresenter((BaseReferralRegisterFragmentContract.View) this, (BaseReferralRegisterFragmentContract.Model) new ReferralRegisterFragmentModel(), viewConfigurationIdentifier); } @Override @@ -155,7 +156,7 @@ private void switchViews(View dueOnlyLayout, boolean isPress) { @Override protected void openProfile(CommonPersonObjectClient client) { - ReferralDetailsViewActivity.startReferralDetailsViewActivity(getActivity(), new MemberObject(client)); + ChwReferralDetailsViewActivity.startChwReferralDetailsViewActivity(getActivity(), new MemberObject(client), client); } @Override @@ -236,8 +237,9 @@ public void countExecute() { try { String query = "select count(*) from " + presenter().getMainTable() + " inner join " + Constants.TABLE_NAME.FAMILY_MEMBER + - " on " + presenter().getMainTable() + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + + " on " + presenter().getMainTable() + ".entity_id = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + + " inner join task on task.for = ec_family_member.base_entity_id"+ " where " + presenter().getMainCondition(); if (StringUtils.isNotBlank(filters)) { diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/SbccRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/SbccRegisterFragment.java new file mode 100644 index 0000000000..349ee30afb --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/SbccRegisterFragment.java @@ -0,0 +1,210 @@ +package org.smartregister.chw.fragment; + +import static com.vijay.jsonwizard.utils.FormUtils.fields; +import static com.vijay.jsonwizard.utils.FormUtils.getFieldJSONObject; + +import android.database.Cursor; +import android.os.Bundle; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.adapter.SbccRegisterAdapter; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.dao.ChwSbccDao; +import org.smartregister.chw.model.SbccRegisterFragmentModel; +import org.smartregister.chw.model.SbccSessionModel; +import org.smartregister.chw.pmtct.fragment.BasePmtctRegisterFragment; +import org.smartregister.chw.presenter.SbccRegisterFragmentPresenter; +import org.smartregister.chw.provider.SbccRegisterProvider; +import org.smartregister.configurableviews.model.View; +import org.smartregister.cursoradapter.RecyclerViewPaginatedAdapter; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.view.activity.BaseRegisterActivity; +import org.smartregister.view.customcontrols.CustomFontTextView; + +import java.util.List; +import java.util.Set; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.widget.Toolbar; +import timber.log.Timber; + +import static org.smartregister.util.JsonFormUtils.ENTITY_ID; +import static org.smartregister.util.JsonFormUtils.STEP1; +import static org.smartregister.util.JsonFormUtils.VALUE; +import static org.smartregister.util.JsonFormUtils.generateRandomUUIDString; + +public class SbccRegisterFragment extends BasePmtctRegisterFragment { + + private android.view.View view; + + @Override + public void initializeAdapter(Set visibleColumns) { + SbccRegisterProvider sbccRegisterProvider = new SbccRegisterProvider(getActivity(), paginationViewHandler, registerActionHandler, visibleColumns); + List sbccSessionModels = ChwSbccDao.getSbccSessions(); + clientAdapter = new RecyclerViewPaginatedAdapter(null, sbccRegisterProvider, null); + clientAdapter.setTotalcount(0); + clientAdapter.setCurrentlimit(20); + if (sbccSessionModels != null && !sbccSessionModels.isEmpty()) { + clientsView.setAdapter(new SbccRegisterAdapter(sbccSessionModels, requireActivity())); + } + } + + @Override + public void setupViews(android.view.View view) { + initializePresenter(); + super.setupViews(view); + this.view = view; + + Toolbar toolbar = view.findViewById(org.smartregister.R.id.register_toolbar); + toolbar.setContentInsetsAbsolute(0, 0); + toolbar.setContentInsetsRelative(0, 0); + toolbar.setContentInsetStartWithNavigation(0); + + try { + NavigationMenu.getInstance(getActivity(), null, toolbar); + } catch (NullPointerException e) { + Timber.e(e); + } + android.view.View navbarContainer = view.findViewById(org.smartregister.chw.core.R.id.register_nav_bar_container); + navbarContainer.setFocusable(false); + + CustomFontTextView titleView = view.findViewById(org.smartregister.chw.core.R.id.txt_title_label); + if (titleView != null) { + titleView.setText(getString(R.string.sbcc)); + titleView.setPadding(0, titleView.getTop(), titleView.getPaddingRight(), titleView.getPaddingBottom()); + } + + android.view.View searchBarLayout = view.findViewById(org.smartregister.chw.core.R.id.search_bar_layout); + searchBarLayout.setVisibility(android.view.View.GONE); + + android.view.View topLeftLayout = view.findViewById(org.smartregister.chw.core.R.id.top_left_layout); + topLeftLayout.setVisibility(android.view.View.GONE); + + android.view.View topRightLayout = view.findViewById(org.smartregister.chw.core.R.id.top_right_layout); + topRightLayout.setVisibility(android.view.View.VISIBLE); + + android.view.View sortFilterBarLayout = view.findViewById(org.smartregister.chw.core.R.id.register_sort_filter_bar_layout); + sortFilterBarLayout.setVisibility(android.view.View.GONE); + + android.view.View filterSortLayout = view.findViewById(org.smartregister.chw.core.R.id.filter_sort_layout); + filterSortLayout.setVisibility(android.view.View.GONE); + + android.view.View dueOnlyLayout = view.findViewById(org.smartregister.chw.core.R.id.due_only_layout); + dueOnlyLayout.setVisibility(android.view.View.GONE); + dueOnlyLayout.setOnClickListener(registerActionHandler); + if (getSearchView() != null) { + getSearchView().setVisibility(android.view.View.GONE); + } + } + + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((BaseRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (NullPointerException e) { + Timber.e(e); + } + presenter = new SbccRegisterFragmentPresenter(this, new SbccRegisterFragmentModel(), viewConfigurationIdentifier); + } + + @Override + public void onViewCreated(@NonNull android.view.View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + if (clientsView.getAdapter() != null) { + clientsView.getAdapter().notifyDataSetChanged(); + } + } + + + @Override + public void onResume() { + super.onResume(); + + Toolbar toolbar = view.findViewById(org.smartregister.R.id.register_toolbar); + toolbar.setContentInsetsAbsolute(0, 0); + toolbar.setContentInsetsRelative(0, 0); + toolbar.setContentInsetStartWithNavigation(0); + NavigationMenu.getInstance(getActivity(), null, toolbar); + if (clientsView.getAdapter() != null) { + clientsView.getAdapter().notifyDataSetChanged(); + } + } + + @Override + public void countExecute() { + Cursor c = null; + try { + + String query = "select count(*) from " + presenter().getMainTable() + " where " + presenter().getMainCondition(); + + if (StringUtils.isNotBlank(filters)) { + query = query + " and ( " + filters + " ) "; + } + + + c = commonRepository().rawCustomQueryForAdapter(query); + c.moveToFirst(); + clientAdapter.setTotalcount(c.getInt(0)); + Timber.v("total count here %s", clientAdapter.getTotalcount()); + + clientAdapter.setCurrentlimit(20); + clientAdapter.setCurrentoffset(0); + + } catch (Exception e) { + Timber.e(e); + } finally { + if (c != null) { + c.close(); + } + } + } + + + @Override + protected void openProfile(String baseEntityId) { + //implement when needed + } + + + @Override + protected void refreshSyncProgressSpinner() { + if (syncProgressBar != null) { + syncProgressBar.setVisibility(android.view.View.GONE); + } + if (syncButton != null) { + syncButton.setVisibility(android.view.View.VISIBLE); + syncButton.setPadding(0, 0, 10, 0); + syncButton.setImageDrawable(context().getDrawable(R.drawable.ic_add_white_24)); + syncButton.setOnClickListener(view -> { + JSONObject form; + try { + form = (new FormUtils()).getFormJsonFromRepositoryOrAssets(requireActivity(), org.smartregister.chw.util.Constants.JsonForm.getMotherChampionSbccForm()); + if (form != null) { + String randomId = generateRandomUUIDString(); + form.put(ENTITY_ID, randomId); + + JSONObject chwName = getFieldJSONObject(fields(form, STEP1), "chw_name"); + AllSharedPreferences preferences = ChwApplication.getInstance().getContext().allSharedPreferences(); + chwName.put(VALUE, preferences.getANMPreferredName(preferences.fetchRegisteredANM())); + requireActivity().startActivityForResult(org.smartregister.chw.core.utils.FormUtils.getStartFormActivity(form, requireActivity().getString(R.string.sbcc), requireActivity()), JsonFormUtils.REQUEST_CODE_GET_JSON); + } + } catch (JSONException e) { + Timber.e(e); + } + }); + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbFollowupRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbFollowupRegisterFragment.java new file mode 100644 index 0000000000..1e38b9700c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbFollowupRegisterFragment.java @@ -0,0 +1,72 @@ +package org.smartregister.chw.fragment; + +import android.content.Intent; +import android.os.Bundle; + +import androidx.annotation.Nullable; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.smartregister.chw.activity.TbCommunityFollowupDetailsActivity; +import org.smartregister.chw.activity.TbRegisterActivity; +import org.smartregister.chw.core.fragment.CoreTbCommunityFollowupRegisterFragment; +import org.smartregister.chw.hiv.util.DBConstants; +import org.smartregister.chw.model.TbCommunityFollowupFragmentModel; +import org.smartregister.chw.presenter.TbCommunityFollowupFragmentPresenter; +import org.smartregister.chw.tb.dao.TbDao; +import org.smartregister.chw.tb.domain.TbMemberObject; +import org.smartregister.chw.tb.util.Constants; +import org.smartregister.commonregistry.CommonPersonObjectClient; + +import timber.log.Timber; + +import static android.view.View.GONE; + +public class TbFollowupRegisterFragment extends CoreTbCommunityFollowupRegisterFragment { + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((TbRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (NullPointerException e) { + Timber.e(e); + } + presenter = new TbCommunityFollowupFragmentPresenter(this, new TbCommunityFollowupFragmentModel(), viewConfigurationIdentifier); + } + + @Override + public void setupViews(android.view.View view) { + super.setupViews(view); + view.findViewById(org.smartregister.chw.core.R.id.due_only_layout).setVisibility(GONE); + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + if (getActivity() != null) { + Intent intent = new Intent(getActivity(), TbCommunityFollowupDetailsActivity.class); + Bundle bundle = new Bundle(); + bundle.putSerializable(Constants.TbMemberObject.MEMBER_OBJECT, TbDao.getCommunityFollowupMember(client.getColumnmaps().get(DBConstants.Key.BASE_ENTITY_ID))); + intent.putExtras(bundle); + + getActivity().startActivity(intent); + } + } + + @Override + protected void openFollowUpVisit(@Nullable TbMemberObject tbMemberObject) { + if (getActivity() != null) { + try { + TbRegisterActivity.startTbFormActivity(getActivity(), tbMemberObject.getBaseEntityId(), org.smartregister.chw.util.Constants.JSON_FORM.getTbFollowupVisit(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(getActivity(), org.smartregister.chw.util.Constants.JSON_FORM.getTbFollowupVisit()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + } + +} + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbRegisterFragment.java b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbRegisterFragment.java new file mode 100644 index 0000000000..8fad5c98d8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/fragment/TbRegisterFragment.java @@ -0,0 +1,55 @@ +package org.smartregister.chw.fragment; + +import androidx.annotation.Nullable; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.smartregister.chw.activity.TbProfileActivity; +import org.smartregister.chw.activity.TbRegisterActivity; +import org.smartregister.chw.core.fragment.CoreTbRegisterFragment; +import org.smartregister.chw.model.TbRegisterFragmentModel; +import org.smartregister.chw.presenter.TbRegisterFragmentPresenter; +import org.smartregister.chw.tb.dao.TbDao; +import org.smartregister.chw.tb.domain.TbMemberObject; +import org.smartregister.commonregistry.CommonPersonObjectClient; + +import java.util.Objects; + +import timber.log.Timber; + +public class TbRegisterFragment extends CoreTbRegisterFragment { + + @Override + protected void initializePresenter() { + if (getActivity() == null) { + return; + } + String viewConfigurationIdentifier = null; + try { + viewConfigurationIdentifier = ((TbRegisterActivity) getActivity()).getViewIdentifiers().get(0); + } catch (NullPointerException e) { + Timber.e(e); + } + presenter = new TbRegisterFragmentPresenter(this, new TbRegisterFragmentModel(), viewConfigurationIdentifier); + } + + @Override + protected void openProfile(CommonPersonObjectClient client) { + if (getActivity() != null) + TbProfileActivity.startTbProfileActivity(getActivity(), Objects.requireNonNull(TbDao.getMember(client.getCaseId()))); + } + + @Override + protected void openFollowUpVisit(@Nullable TbMemberObject tbMemberObject) { + if (getActivity() != null) { + try { + TbRegisterActivity.startTbFormActivity(getActivity(), tbMemberObject.getBaseEntityId(), org.smartregister.chw.util.Constants.JSON_FORM.getTbFollowupVisit(), (new FormUtils()).getFormJsonFromRepositoryOrAssets(getActivity(), org.smartregister.chw.util.Constants.JSON_FORM.getTbFollowupVisit()).toString()); + } catch (JSONException e) { + Timber.e(e); + } + } + } +} + + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AgywMedicalHistoryInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AgywMedicalHistoryInteractor.java new file mode 100644 index 0000000000..efd3efa646 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AgywMedicalHistoryInteractor.java @@ -0,0 +1,71 @@ +package org.smartregister.chw.interactor; + +import static org.smartregister.chw.anc.util.VisitUtils.getVisitDetailsOnly; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitGroups; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitsOnly; + +import android.content.Context; + +import com.google.gson.Gson; + +import org.smartregister.chw.anc.contract.BaseAncMedicalHistoryContract; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.VisitUtils; +import org.smartregister.chw.core.CoreBaseAncMedicalHistoryInteractor; +import org.smartregister.chw.domain.SortableVisit; +import org.smartregister.chw.util.Constants; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class AgywMedicalHistoryInteractor extends CoreBaseAncMedicalHistoryInteractor { + public static List getVisits(String memberID, String... eventTypes) { + + List visits = new ArrayList<>(); + if (eventTypes != null && eventTypes.length > 0) { + for (String eventType : eventTypes) { + List visit = getVisitsOnly(memberID, eventType); + visits.addAll(visit); + } + } + + int x = 0; + while (visits.size() > x) { + Visit visit = visits.get(x); + List detailList = getVisitDetailsOnly(visit.getVisitId()); + visits.get(x).setVisitDetails(getVisitGroups(detailList)); + x++; + } + + List sortableVisits = new ArrayList<>(); + for (Visit visit : visits) { + Gson gson = new Gson(); + SortableVisit sortableVisit = gson.fromJson(gson.toJson(visit), SortableVisit.class); + sortableVisits.add(sortableVisit); + } + + Collections.sort(sortableVisits); + + return sortableVisits; + } + + @Override + public void getMemberHistory(final String memberID, final Context context, final BaseAncMedicalHistoryContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + + String[] eventTypes = new String[]{Constants.Events.AGYW_BIO_MEDICAL_SERVICES, Constants.Events.AGYW_BEHAVIORAL_SERVICES, Constants.Events.AGYW_STRUCTURAL_SERVICES}; + List visits = getVisits(memberID, eventTypes); + final List all_visits = new ArrayList<>(visits); + + for (Visit visit : visits) { + List child_visits = VisitUtils.getChildVisits(visit.getVisitId()); + all_visits.addAll(child_visits); + } + appExecutors.mainThread().execute(() -> callBack.onDataFetched(all_visits)); + }; + + appExecutors.diskIO().execute(runnable); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AllClientsMemberInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AllClientsMemberInteractor.java deleted file mode 100644 index 46aa67de09..0000000000 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AllClientsMemberInteractor.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.smartregister.chw.interactor; - -import org.smartregister.chw.contract.AllClientsMemberContract; -import org.smartregister.chw.core.utils.CoreConstants; -import org.smartregister.family.contract.FamilyOtherMemberContract; -import org.smartregister.family.contract.FamilyProfileContract; -import org.smartregister.family.domain.FamilyEventClient; -import org.smartregister.family.interactor.FamilyOtherMemberProfileInteractor; - -public class AllClientsMemberInteractor extends FamilyOtherMemberProfileInteractor implements AllClientsMemberContract.Interactor { - - private FamilyProfileInteractor familyProfileInteractor; - - public AllClientsMemberInteractor() { - familyProfileInteractor = new FamilyProfileInteractor(); - } - - @Override - public void updateLocationInfo(String jsonString, FamilyEventClient familyEventClient, FamilyProfileContract.InteractorCallBack interactorCallback) { - familyEventClient.getEvent().setEntityType(CoreConstants.TABLE_NAME.INDEPENDENT_CLIENT); - familyProfileInteractor.saveRegistration(familyEventClient, jsonString, true, interactorCallback); - } - - @Override - public void updateProfileInfo(String baseEntityId, FamilyOtherMemberContract.InteractorCallBack callback) { - refreshProfileView(baseEntityId, callback); - } -} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AncHfMedicalHistoryInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AncHfMedicalHistoryInteractor.java new file mode 100644 index 0000000000..3058784105 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/AncHfMedicalHistoryInteractor.java @@ -0,0 +1,62 @@ +package org.smartregister.chw.interactor; + +import android.content.Context; + +import org.smartregister.chw.anc.contract.BaseAncMedicalHistoryContract; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.VisitUtils; +import org.smartregister.chw.core.CoreBaseAncMedicalHistoryInteractor; +import org.smartregister.chw.util.Constants; + +import java.util.ArrayList; +import java.util.List; + +import static org.smartregister.chw.anc.util.VisitUtils.getVisitDetailsOnly; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitGroups; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitsOnly; + +public class AncHfMedicalHistoryInteractor extends CoreBaseAncMedicalHistoryInteractor { + @Override + public void getMemberHistory(final String memberID, final Context context, final BaseAncMedicalHistoryContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + + String[] eventTypes = new String[2]; + eventTypes[0] = Constants.Events.ANC_FIRST_FACILITY_VISIT; + eventTypes[1] = Constants.Events.ANC_RECURRING_FACILITY_VISIT; + List visits = getVisits(memberID, eventTypes); + final List all_visits = new ArrayList<>(visits); + + for (Visit visit : visits) { + List child_visits = VisitUtils.getChildVisits(visit.getVisitId()); + all_visits.addAll(child_visits); + } + appExecutors.mainThread().execute(() -> callBack.onDataFetched(all_visits)); + }; + + appExecutors.diskIO().execute(runnable); + } + + public static List getVisits(String memberID, String... eventTypes) { + + List visits = new ArrayList<>(); + if(eventTypes != null && eventTypes.length > 0) { + for (String eventType : eventTypes) { + List visit= getVisitsOnly(memberID, eventType); + visits.addAll(visit); + } + } else{ + getVisitsOnly(memberID, Constants.Events.ANC_FIRST_FACILITY_VISIT); + } + + int x = 0; + while (visits.size() > x) { + Visit visit = visits.get(x); + List detailList = getVisitDetailsOnly(visit.getVisitId()); + visits.get(x).setVisitDetails(getVisitGroups(detailList)); + x++; + } + + return visits; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsMedicalHistoryInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsMedicalHistoryInteractor.java new file mode 100644 index 0000000000..a9105e6559 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsMedicalHistoryInteractor.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.interactor; + +import static org.smartregister.chw.anc.util.VisitUtils.getVisitDetailsOnly; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitGroups; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitsOnly; + +import android.content.Context; + +import org.smartregister.chw.anc.contract.BaseAncMedicalHistoryContract; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.VisitUtils; +import org.smartregister.chw.core.CoreBaseAncMedicalHistoryInteractor; +import org.smartregister.chw.util.Constants; + +import java.util.ArrayList; +import java.util.List; + +public class CbhsMedicalHistoryInteractor extends CoreBaseAncMedicalHistoryInteractor { + public static List getVisits(String memberID, String... eventTypes) { + + List visits = new ArrayList<>(); + if (eventTypes != null && eventTypes.length > 0) { + for (String eventType : eventTypes) { + List visit = getVisitsOnly(memberID, eventType); + visits.addAll(visit); + } + } else { + getVisitsOnly(memberID, Constants.Events.CBHS_FOLLOWUP); + } + + int x = 0; + while (visits.size() > x) { + Visit visit = visits.get(x); + List detailList = getVisitDetailsOnly(visit.getVisitId()); + visits.get(x).setVisitDetails(getVisitGroups(detailList)); + x++; + } + + return visits; + } + + @Override + public void getMemberHistory(final String memberID, final Context context, final BaseAncMedicalHistoryContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + + String[] eventTypes = new String[2]; + eventTypes[0] = Constants.Events.CBHS_FOLLOWUP; + List visits = getVisits(memberID, eventTypes); + final List all_visits = new ArrayList<>(visits); + + for (Visit visit : visits) { + List child_visits = VisitUtils.getChildVisits(visit.getVisitId()); + all_visits.addAll(child_visits); + } + appExecutors.mainThread().execute(() -> callBack.onDataFetched(all_visits)); + }; + + appExecutors.diskIO().execute(runnable); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsProfileInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsProfileInteractor.java new file mode 100644 index 0000000000..46e0629ac8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsProfileInteractor.java @@ -0,0 +1,52 @@ +package org.smartregister.chw.interactor; + +import android.content.Context; + +import org.smartregister.chw.anc.model.BaseUpcomingService; +import org.smartregister.chw.core.interactor.CoreHivProfileInteractor; +import org.smartregister.chw.hiv.contract.BaseHivProfileContract; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.dao.AbstractDao; +import org.smartregister.domain.Alert; +import org.smartregister.domain.AlertStatus; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; + +import timber.log.Timber; + +public class CbhsProfileInteractor extends CoreHivProfileInteractor { + public CbhsProfileInteractor(Context context) { + super(context); + } + + @Override + protected Alert getAlerts(Context context, String baseEntityID) { + try { + List baseUpcomingServices = new ArrayList<>(new CbhsUpcomingServicesInteractor().getMemberServices(context, toMember(HivDao.getMember(baseEntityID)))); + if (baseUpcomingServices.size() > 0) { + Comparator comparator = (o1, o2) -> o1.getServiceDate().compareTo(o2.getServiceDate()); + Collections.sort(baseUpcomingServices, comparator); + + BaseUpcomingService baseUpcomingService = baseUpcomingServices.get(0); + Date serviceDate = baseUpcomingService.getServiceDate(); + String serviceName = baseUpcomingService.getServiceName(); + AlertStatus upcomingServiceAlertStatus = serviceDate != null && serviceDate.before(new Date()) ? AlertStatus.urgent : AlertStatus.normal; + String formattedServiceDate = serviceDate != null ? AbstractDao.getDobDateFormat().format(serviceDate) : null; + return new Alert(baseEntityID, serviceName, serviceName, upcomingServiceAlertStatus, formattedServiceDate, "", true); + } + } catch (Exception e) { + Timber.e(e); + } + return null; + } + + @Override + public void updateProfileHivStatusInfo(HivMemberObject memberObject, BaseHivProfileContract.InteractorCallback callback) { + super.updateProfileHivStatusInfo(memberObject, callback); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsUpcomingServicesInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsUpcomingServicesInteractor.java new file mode 100644 index 0000000000..52ff795650 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/CbhsUpcomingServicesInteractor.java @@ -0,0 +1,71 @@ +package org.smartregister.chw.interactor; + +import android.content.Context; + +import org.jeasy.rules.api.Rules; +import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.anc.interactor.BaseAncUpcomingServicesInteractor; +import org.smartregister.chw.anc.model.BaseUpcomingService; +import org.smartregister.chw.core.R; +import org.smartregister.chw.core.application.CoreChwApplication; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.dao.ChwCBHSDao; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.domain.HivAlertObject; +import org.smartregister.chw.rule.CbhsFollowupRule; +import org.smartregister.chw.util.ChwHomeVisitUtil; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class CbhsUpcomingServicesInteractor extends BaseAncUpcomingServicesInteractor { + protected MemberObject memberObject; + protected Context context; + + public static Rules getHivRules() { + return CoreChwApplication.getInstance().getRulesEngineHelper().rules(CoreConstants.RULE_FILE.HIV_FOLLOW_UP_VISIT); + } + + @Override + public List getMemberServices(Context context, MemberObject memberObject) { + this.memberObject = memberObject; + this.context = context; + List serviceList = new ArrayList<>(); + evaluateHiv(serviceList); + return serviceList; + } + + private void evaluateHiv(List serviceList) { + String hiv_date = null; + Date serviceDueDate = null; + Date serviceOverDueDate = null; + String serviceName = null; + + List hivList = HivDao.getHivDetails(memberObject.getBaseEntityId()); + if (hivList.size() > 0) { + for (HivAlertObject hiv : hivList) { + hiv_date = hiv.getHivStartDate(); + } + } + + Date hivDate = new Date(new BigDecimal(hiv_date).longValue()); + Date nextVisitDate = ChwCBHSDao.getNextVisitDate(memberObject.getBaseEntityId()); + + CbhsFollowupRule alertRule = ChwHomeVisitUtil.getCBHSVisitStatus(nextVisitDate, hivDate); + serviceDueDate = alertRule.getDueDate(); + serviceOverDueDate = alertRule.getOverDueDate(); + serviceName = context.getString(R.string.cbhs_follow_up_visit); + + BaseUpcomingService upcomingService = new BaseUpcomingService(); + if (serviceName != null) { + upcomingService.setServiceDate(serviceDueDate); + upcomingService.setOverDueDate(serviceOverDueDate); + upcomingService.setServiceName(serviceName); + serviceList.add(upcomingService); + } + + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPMedicalHistoryInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPMedicalHistoryInteractor.java new file mode 100644 index 0000000000..c1928011ad --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPMedicalHistoryInteractor.java @@ -0,0 +1,71 @@ +package org.smartregister.chw.interactor; + +import static org.smartregister.chw.anc.util.VisitUtils.getVisitDetailsOnly; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitGroups; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitsOnly; + +import android.content.Context; + +import com.google.gson.Gson; + +import org.smartregister.chw.anc.contract.BaseAncMedicalHistoryContract; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.VisitUtils; +import org.smartregister.chw.core.CoreBaseAncMedicalHistoryInteractor; +import org.smartregister.chw.domain.SortableVisit; +import org.smartregister.chw.util.Constants; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class KvpPrEPMedicalHistoryInteractor extends CoreBaseAncMedicalHistoryInteractor { + public static List getVisits(String memberID, String... eventTypes) { + + List visits = new ArrayList<>(); + if (eventTypes != null && eventTypes.length > 0) { + for (String eventType : eventTypes) { + List visit = getVisitsOnly(memberID, eventType); + visits.addAll(visit); + } + } + + int x = 0; + while (visits.size() > x) { + Visit visit = visits.get(x); + List detailList = getVisitDetailsOnly(visit.getVisitId()); + visits.get(x).setVisitDetails(getVisitGroups(detailList)); + x++; + } + + List sortableVisits = new ArrayList<>(); + for (Visit visit : visits) { + Gson gson = new Gson(); + SortableVisit sortableVisit = gson.fromJson(gson.toJson(visit), SortableVisit.class); + sortableVisits.add(sortableVisit); + } + + Collections.sort(sortableVisits); + + return sortableVisits; + } + + @Override + public void getMemberHistory(final String memberID, final Context context, final BaseAncMedicalHistoryContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + + String[] eventTypes = new String[]{Constants.Events.KVP_PREP_FOLLOWUP_VISIT}; + List visits = getVisits(memberID, eventTypes); + final List all_visits = new ArrayList<>(visits); + + for (Visit visit : visits) { + List child_visits = VisitUtils.getChildVisits(visit.getVisitId()); + all_visits.addAll(child_visits); + } + appExecutors.mainThread().execute(() -> callBack.onDataFetched(all_visits)); + }; + + appExecutors.diskIO().execute(runnable); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPVisitInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPVisitInteractor.java new file mode 100644 index 0000000000..a5ad814af6 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/KvpPrEPVisitInteractor.java @@ -0,0 +1,104 @@ +package org.smartregister.chw.interactor; + +import org.smartregister.chw.R; +import org.smartregister.chw.actionhelper.KvpPrEPPreventiveServicesActionHelper; +import org.smartregister.chw.actionhelper.KvpPrEPReferralServicesActionHelper; +import org.smartregister.chw.actionhelper.KvpPrEPSbccServicesActionHelper; +import org.smartregister.chw.actionhelper.KvpPrEPStructuralServicesActionHelper; +import org.smartregister.chw.actionhelper.KvpPrEPVisitTypeActionHelper; +import org.smartregister.chw.kvp.contract.BaseKvpVisitContract; +import org.smartregister.chw.kvp.domain.VisitDetail; +import org.smartregister.chw.kvp.interactor.BaseKvpVisitInteractor; +import org.smartregister.chw.kvp.model.BaseKvpVisitAction; +import org.smartregister.chw.kvp.util.Constants; + +import java.util.List; +import java.util.Map; + +import timber.log.Timber; + +public class KvpPrEPVisitInteractor extends BaseKvpVisitInteractor { + @Override + protected void populateActionList(BaseKvpVisitContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + try { + evaluateVisitType(details); + evaluateSBCCServices(details); + evaluatePreventiveServices(details); + evaluateStructuralServices(details); + evaluateReferralServices(details); + } catch (BaseKvpVisitAction.ValidationException e) { + Timber.e(e); + } + + appExecutors.mainThread().execute(() -> callBack.preloadActions(actionList)); + }; + + appExecutors.diskIO().execute(runnable); + } + + private void evaluateVisitType(Map> details) throws BaseKvpVisitAction.ValidationException { + + KvpPrEPVisitTypeActionHelper actionHelper = new KvpPrEPVisitTypeActionHelper(); + BaseKvpVisitAction action = getBuilder(context.getString(R.string.kvp_prep_visit_type)) + .withOptional(false) + .withDetails(details) + .withHelper(actionHelper) + .withFormName(Constants.KVP_PrEP_FOLLOWUP_FORMS.VISIT_TYPE) + .build(); + + actionList.put(context.getString(R.string.kvp_prep_visit_type), action); + } + + private void evaluateSBCCServices(Map> details) throws BaseKvpVisitAction.ValidationException { + + KvpPrEPSbccServicesActionHelper actionHelper = new KvpPrEPSbccServicesActionHelper(); + BaseKvpVisitAction action = getBuilder(context.getString(R.string.kvp_prep_sbcc_services)) + .withOptional(false) + .withDetails(details) + .withHelper(actionHelper) + .withFormName(Constants.KVP_PrEP_FOLLOWUP_FORMS.SBCC_SERVICES) + .build(); + + actionList.put(context.getString(R.string.kvp_prep_sbcc_services), action); + } + + private void evaluatePreventiveServices(Map> details) throws BaseKvpVisitAction.ValidationException { + KvpPrEPPreventiveServicesActionHelper actionHelper = new KvpPrEPPreventiveServicesActionHelper(memberObject.getBaseEntityId()); + BaseKvpVisitAction action = getBuilder(context.getString(R.string.kvp_prep_preventive_services)) + .withOptional(true) + .withDetails(details) + .withHelper(actionHelper) + .withFormName(Constants.KVP_PrEP_FOLLOWUP_FORMS.PREVENTIVE_SERVICES) + .build(); + + actionList.put(context.getString(R.string.kvp_prep_preventive_services), action); + } + + private void evaluateStructuralServices(Map> details) throws BaseKvpVisitAction.ValidationException { + + KvpPrEPStructuralServicesActionHelper actionHelper = new KvpPrEPStructuralServicesActionHelper(); + BaseKvpVisitAction action = getBuilder(context.getString(R.string.kvp_prep_structural_services)) + .withOptional(true) + .withDetails(details) + .withHelper(actionHelper) + .withFormName(Constants.KVP_PrEP_FOLLOWUP_FORMS.STRUCTURAL_SERVICES) + .build(); + + actionList.put(context.getString(R.string.kvp_prep_structural_services), action); + } + + private void evaluateReferralServices(Map> details) throws BaseKvpVisitAction.ValidationException { + + KvpPrEPReferralServicesActionHelper actionHelper = new KvpPrEPReferralServicesActionHelper(); + BaseKvpVisitAction action = getBuilder(context.getString(R.string.kvp_prep_referral_services)) + .withOptional(true) + .withDetails(details) + .withHelper(actionHelper) + .withFormName(Constants.KVP_PrEP_FOLLOWUP_FORMS.REFERRAL_SERVICES) + .build(); + + actionList.put(context.getString(R.string.kvp_prep_referral_services), action); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java index 7f5637d6ea..aa2081923f 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java @@ -1,5 +1,7 @@ package org.smartregister.chw.interactor; +import org.smartregister.CoreLibrary; +import org.smartregister.P2POptions; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.contract.LoginJobScheduler; @@ -8,10 +10,12 @@ import org.smartregister.chw.core.job.StockUsageReportJob; import org.smartregister.chw.core.job.VaccineRecurringServiceJob; import org.smartregister.chw.job.BasePncCloseJob; +import org.smartregister.chw.job.PncCloseDateServiceJob; import org.smartregister.chw.job.ScheduleJob; import org.smartregister.immunization.job.VaccineServiceJob; import org.smartregister.job.DocumentConfigurationServiceJob; import org.smartregister.job.ImageUploadServiceJob; +import org.smartregister.job.P2pServiceJob; import org.smartregister.job.PlanIntentServiceJob; import org.smartregister.job.PullUniqueIdsServiceJob; import org.smartregister.job.SyncLocationsByLevelAndTagsServiceJob; @@ -52,7 +56,11 @@ public void scheduleJobsPeriodically() { StockUsageReportJob.scheduleJob(StockUsageReportJob.TAG, TimeUnit.MINUTES.toMinutes(BuildConfig.STOCK_USAGE_REPORT_MINUTES), getFlexValue(BuildConfig.STOCK_USAGE_REPORT_MINUTES)); if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) - DocumentConfigurationServiceJob.scheduleJob(DocumentConfigurationServiceJob.TAG,TimeUnit.MINUTES.toMinutes(BuildConfig.DATA_SYNC_DURATION_MINUTES), getFlexValue(BuildConfig.DATA_SYNC_DURATION_MINUTES)); + DocumentConfigurationServiceJob.scheduleJob(DocumentConfigurationServiceJob.TAG, TimeUnit.MINUTES.toMinutes(BuildConfig.DATA_SYNC_DURATION_MINUTES), getFlexValue(BuildConfig.DATA_SYNC_DURATION_MINUTES)); + + + PncCloseDateServiceJob.scheduleJob(PncCloseDateServiceJob.TAG, TimeUnit.MINUTES.toMinutes( + BuildConfig.STOCK_USAGE_REPORT_MINUTES), getFlexValue(BuildConfig.STOCK_USAGE_REPORT_MINUTES)); } @Override @@ -63,6 +71,7 @@ public void scheduleJobsImmediately() { HomeVisitServiceJob.scheduleJobImmediately(HomeVisitServiceJob.TAG); BasePncCloseJob.scheduleJobImmediately(BasePncCloseJob.TAG); PlanIntentServiceJob.scheduleJobImmediately(PlanIntentServiceJob.TAG); + PncCloseDateServiceJob.scheduleJobImmediately(PncCloseDateServiceJob.TAG); if (ChwApplication.getApplicationFlavor().hasTasks()) SyncTaskServiceJob.scheduleJobImmediately(SyncTaskServiceJob.TAG); @@ -79,6 +88,12 @@ public void scheduleJobsImmediately() { if (ChwApplication.getApplicationFlavor().hasServiceReport()) ChwIndicatorGeneratingJob.scheduleJobImmediately(ChwIndicatorGeneratingJob.TAG); + + P2POptions p2POptions = CoreLibrary.getInstance().getP2POptions(); + if (p2POptions != null && p2POptions.isEnableP2PLibrary()) { + // Finish processing any unprocessed sync records here + P2pServiceJob.scheduleJobImmediately(P2pServiceJob.TAG); + } } @Override diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/MotherChampionMedicalHistoryInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/MotherChampionMedicalHistoryInteractor.java new file mode 100644 index 0000000000..4d353985c1 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/MotherChampionMedicalHistoryInteractor.java @@ -0,0 +1,61 @@ +package org.smartregister.chw.interactor; + +import static org.smartregister.chw.anc.util.VisitUtils.getVisitDetailsOnly; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitGroups; +import static org.smartregister.chw.anc.util.VisitUtils.getVisitsOnly; + +import android.content.Context; + +import org.smartregister.chw.anc.contract.BaseAncMedicalHistoryContract; +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.VisitUtils; +import org.smartregister.chw.core.CoreBaseAncMedicalHistoryInteractor; +import org.smartregister.chw.util.Constants; + +import java.util.ArrayList; +import java.util.List; + +public class MotherChampionMedicalHistoryInteractor extends CoreBaseAncMedicalHistoryInteractor { + public static List getVisits(String memberID, String... eventTypes) { + + List visits = new ArrayList<>(); + if (eventTypes != null && eventTypes.length > 0) { + for (String eventType : eventTypes) { + List visit = getVisitsOnly(memberID, eventType); + visits.addAll(visit); + } + } else { + getVisitsOnly(memberID, Constants.Events.MOTHER_CHAMPION_FOLLOWUP); + } + + int x = 0; + while (visits.size() > x) { + Visit visit = visits.get(x); + List detailList = getVisitDetailsOnly(visit.getVisitId()); + visits.get(x).setVisitDetails(getVisitGroups(detailList)); + x++; + } + + return visits; + } + + @Override + public void getMemberHistory(final String memberID, final Context context, final BaseAncMedicalHistoryContract.InteractorCallBack callBack) { + final Runnable runnable = () -> { + + String[] eventTypes = new String[2]; + eventTypes[0] = Constants.Events.MOTHER_CHAMPION_FOLLOWUP; + List visits = getVisits(memberID, eventTypes); + final List all_visits = new ArrayList<>(visits); + + for (Visit visit : visits) { + List child_visits = VisitUtils.getChildVisits(visit.getVisitId()); + all_visits.addAll(child_visits); + } + appExecutors.mainThread().execute(() -> callBack.onDataFetched(all_visits)); + }; + + appExecutors.diskIO().execute(runnable); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/job/ChwJobCreator.java b/opensrp-chw/src/main/java/org/smartregister/chw/job/ChwJobCreator.java index 3bd73769b6..f4f55e9e46 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/job/ChwJobCreator.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/job/ChwJobCreator.java @@ -10,7 +10,9 @@ import org.smartregister.chw.core.job.ChwIndicatorGeneratingJob; import org.smartregister.chw.core.job.HomeVisitServiceJob; import org.smartregister.chw.core.job.StockUsageReportJob; +import org.smartregister.chw.core.job.SyncTaskWithClientEventsServiceJob; import org.smartregister.chw.core.job.VaccineRecurringServiceJob; +import org.smartregister.chw.core.sync.intent.SyncClientEventsPerTaskIntentService; import org.smartregister.chw.sync.ChwSyncIntentService; import org.smartregister.chw.sync.intent.ChwSyncTaskIntentService; import org.smartregister.job.DocumentConfigurationServiceJob; @@ -62,8 +64,12 @@ public Job create(@NonNull String tag) { return new SyncLocationsByLevelAndTagsServiceJob(); case StockUsageReportJob.TAG: return new StockUsageReportJob(); + case SyncTaskWithClientEventsServiceJob.TAG: + return new SyncTaskWithClientEventsServiceJob(SyncClientEventsPerTaskIntentService.class); case DocumentConfigurationServiceJob.TAG: return new DocumentConfigurationServiceJob(DocumentConfigurationIntentService.class); + case PncCloseDateServiceJob.TAG: + return new PncCloseDateServiceJob(); //TODO uncomment to enable plans /*case PlanIntentServiceJob.TAG: return new PlanIntentServiceJob();*/ diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/job/PncCloseDateServiceJob.java b/opensrp-chw/src/main/java/org/smartregister/chw/job/PncCloseDateServiceJob.java new file mode 100644 index 0000000000..02ab324d3e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/job/PncCloseDateServiceJob.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.job; + +import android.content.Intent; + +import androidx.annotation.NonNull; + +import org.smartregister.AllConstants; +import org.smartregister.chw.sync.intent.PncCloseDateIntentService; +import org.smartregister.job.BaseJob; + +public class PncCloseDateServiceJob extends BaseJob { + + public static final String TAG = "PncCloseDateServiceJob"; + + @NonNull + @Override + protected Result onRunJob(@NonNull Params params) { + Intent intent = new Intent(getApplicationContext(), PncCloseDateIntentService.class); + getApplicationContext().startService(intent); + return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/listener/AgywServiceActionHandler.java b/opensrp-chw/src/main/java/org/smartregister/chw/listener/AgywServiceActionHandler.java new file mode 100644 index 0000000000..62d4d8561a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/listener/AgywServiceActionHandler.java @@ -0,0 +1,24 @@ +package org.smartregister.chw.listener; + +import android.app.Activity; +import android.content.Context; +import android.widget.Toast; + +import org.smartregister.chw.activity.AgywServicesFormActivity; +import org.smartregister.chw.agyw.domain.MemberObject; +import org.smartregister.chw.agyw.domain.ServiceCard; +import org.smartregister.chw.agyw.handlers.BaseServiceActionHandler; + +public class AgywServiceActionHandler extends BaseServiceActionHandler { + + @Override + protected void startVisitActivity(Context context, ServiceCard serviceCard, MemberObject memberObject) { + if (serviceCard.getFormName() != null) { + try { + AgywServicesFormActivity.startMe((Activity) context, serviceCard.getFormName(), memberObject.getBaseEntityId(), memberObject.getAge()); + } catch (Exception e) { + Toast.makeText(context, "Something happened!", Toast.LENGTH_LONG).show(); + } + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/listener/CdpBottomNavigationListener.java b/opensrp-chw/src/main/java/org/smartregister/chw/listener/CdpBottomNavigationListener.java new file mode 100644 index 0000000000..7c3f21ed23 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/listener/CdpBottomNavigationListener.java @@ -0,0 +1,39 @@ +package org.smartregister.chw.listener; + +import android.app.Activity; +import android.view.MenuItem; + +import androidx.annotation.NonNull; + +import org.smartregister.chw.R; +import org.smartregister.chw.cdp.activity.BaseCdpRegisterActivity; +import org.smartregister.chw.cdp.listener.BaseCdpBottomNavigationListener; + +public class CdpBottomNavigationListener extends BaseCdpBottomNavigationListener { + private final Activity context; + + public CdpBottomNavigationListener(Activity context) { + super(context); + this.context = context; + } + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem item) { + super.onNavigationItemSelected(item); + + BaseCdpRegisterActivity baseRegisterActivity = (BaseCdpRegisterActivity) context; + int itemId = item.getItemId(); + if (itemId == R.id.action_home) { + baseRegisterActivity.switchToBaseFragment(); + } else if (itemId == R.id.action_order_receive) { + baseRegisterActivity.switchToFragment(1); + } else if (itemId == R.id.action_receive_from_msd) { + baseRegisterActivity.switchToFragment(2); + } else if (itemId == R.id.action_add_outlet) { + baseRegisterActivity.startOutletForm(); + baseRegisterActivity.switchToBaseFragment(); + } + + return true; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/listener/ChwMotherChampionBottomNavigationListener.java b/opensrp-chw/src/main/java/org/smartregister/chw/listener/ChwMotherChampionBottomNavigationListener.java new file mode 100644 index 0000000000..66005c1e07 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/listener/ChwMotherChampionBottomNavigationListener.java @@ -0,0 +1,59 @@ +package org.smartregister.chw.listener; + +import android.app.Activity; +import android.view.MenuItem; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.R; +import org.smartregister.chw.activity.MotherChampionRegisterActivity; +import org.smartregister.chw.pmtct.listener.PmtctBottomNavigationListener; +import org.smartregister.family.util.JsonFormUtils; + +import androidx.annotation.NonNull; +import timber.log.Timber; + +import static org.smartregister.util.JsonFormUtils.ENTITY_ID; +import static org.smartregister.util.JsonFormUtils.VALUE; +import static org.smartregister.util.JsonFormUtils.generateRandomUUIDString; + +public class ChwMotherChampionBottomNavigationListener extends PmtctBottomNavigationListener { + + private final MotherChampionRegisterActivity baseRegisterActivity; + + public ChwMotherChampionBottomNavigationListener(Activity context) { + super(context); + this.baseRegisterActivity = (MotherChampionRegisterActivity) context; + } + + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem item) { + if (item.getItemId() == R.id.action_home) { + baseRegisterActivity.switchToFragment(0); + return true; + } else if (item.getItemId() == R.id.action_received_referrals) { + baseRegisterActivity.switchToFragment(1); + return true; + } else if (item.getItemId() == R.id.action_followup) { + baseRegisterActivity.switchToFragment(2); + return true; + } else if (item.getItemId() == R.id.action_sbcc) { +// JSONObject form; +// try { +// form = (new FormUtils()).getFormJsonFromRepositoryOrAssets(baseRegisterActivity, org.smartregister.chw.util.Constants.JsonForm.getMotherChampionSbccForm()); +// if (form != null) { +// String randomId = generateRandomUUIDString(); +// form.put(ENTITY_ID,randomId); +// baseRegisterActivity.startActivityForResult(org.smartregister.chw.core.utils.FormUtils.getStartFormActivity(form, baseRegisterActivity.getString(R.string.sbcc), baseRegisterActivity), JsonFormUtils.REQUEST_CODE_GET_JSON); +// } +// } catch (JSONException e) { +// Timber.e(e); +// } + baseRegisterActivity.switchToFragment(3); + return true; + } else + return super.onNavigationItemSelected(item); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/AllClientsMemberModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/AllClientsMemberModel.java deleted file mode 100644 index 83b0619527..0000000000 --- a/opensrp-chw/src/main/java/org/smartregister/chw/model/AllClientsMemberModel.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.smartregister.chw.model; - -import org.smartregister.chw.contract.AllClientsMemberContract; -import org.smartregister.family.FamilyLibrary; -import org.smartregister.family.domain.FamilyEventClient; -import org.smartregister.family.util.JsonFormUtils; - -public class AllClientsMemberModel implements AllClientsMemberContract.Model { - @Override - public FamilyEventClient processJsonForm(String jsonString, String familyBaseEntityId) { - return JsonFormUtils.processFamilyUpdateForm(FamilyLibrary.getInstance().context().allSharedPreferences(), jsonString, familyBaseEntityId); - } -} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/AncPartnerFollowupRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/AncPartnerFollowupRegisterFragmentModel.java new file mode 100644 index 0000000000..e30a018574 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/AncPartnerFollowupRegisterFragmentModel.java @@ -0,0 +1,60 @@ +package org.smartregister.chw.model; + +import org.smartregister.chw.core.model.CoreAncRegisterFragmentModel; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.core.utils.ChwDBConstants; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class AncPartnerFollowupRegisterFragmentModel extends CoreAncRegisterFragmentModel { + + public AncPartnerFollowupRegisterFragmentModel() { + setFlavor(new AncRegisterFragmentModelFlv()); + } + + @Override + protected String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.LAST_INTERACTED_WITH); + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(tableName + "." + ChwDBConstants.LMP); + columnList.add(CoreConstants.TABLE_NAME.ANC_MEMBER_LOG + "." + org.smartregister.chw.anc.util.DBConstants.KEY.DATE_CREATED); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.CONFIRMED_VISITS); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.LAST_HOME_VISIT); + columnList.add(tableName + "." + ChwDBConstants.VISIT_NOT_DONE); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.LAST_MENSTRUAL_PERIOD); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + "." + DBConstants.KEY.BASE_ENTITY_ID + " as " + org.smartregister.chw.util.Constants.PartnerRegistrationConstants.FormSubmissionId); + columnList.addAll(getFlavor().mainColumns(tableName)); + + return columnList.toArray(new String[0]); + } + + @Override + public String mainSelect(String tableName, String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.ANC_MEMBER_LOG + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.ANC_MEMBER_LOG + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY + " ON " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + ".entity_id" + " COLLATE NOCASE "); + queryBuilder.customJoin("LEFT JOIN (select base_entity_id , max(visit_date) visit_date from visits GROUP by base_entity_id) VISIT_SUMMARY ON VISIT_SUMMARY.base_entity_id = " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/AncRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/AncRegisterFragmentModel.java index a59009939c..4f61472b9e 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/model/AncRegisterFragmentModel.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/AncRegisterFragmentModel.java @@ -1,16 +1,50 @@ package org.smartregister.chw.model; import org.smartregister.chw.core.model.CoreAncRegisterFragmentModel; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.core.utils.ChwDBConstants; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; import org.smartregister.family.util.DBConstants; +import java.util.HashSet; +import java.util.Set; + public class AncRegisterFragmentModel extends CoreAncRegisterFragmentModel { public AncRegisterFragmentModel() { setFlavor(new AncRegisterFragmentModelFlv()); } + @Override + protected String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.LAST_INTERACTED_WITH); + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(tableName + "." + ChwDBConstants.LMP); + columnList.add(CoreConstants.TABLE_NAME.ANC_MEMBER_LOG + "." + org.smartregister.chw.anc.util.DBConstants.KEY.DATE_CREATED); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.CONFIRMED_VISITS); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.LAST_HOME_VISIT); + columnList.add(tableName + "." + ChwDBConstants.VISIT_NOT_DONE); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(tableName + "." + org.smartregister.chw.anc.util.DBConstants.KEY.LAST_MENSTRUAL_PERIOD); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + + columnList.addAll(getFlavor().mainColumns(tableName)); + + return columnList.toArray(new String[0]); + } + @Override public String mainSelect(String tableName, String mainCondition) { SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwAllClientsRegisterModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwAllClientsRegisterModel.java index 79903b7a46..a68af227cb 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwAllClientsRegisterModel.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwAllClientsRegisterModel.java @@ -1,6 +1,8 @@ package org.smartregister.chw.model; -import androidx.annotation.Nullable; +import android.content.Context; + +import com.vijay.jsonwizard.utils.FormUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; @@ -14,6 +16,7 @@ import java.util.List; +import androidx.annotation.Nullable; import timber.log.Timber; import static com.vijay.jsonwizard.utils.FormUtils.fields; @@ -25,11 +28,23 @@ public class ChwAllClientsRegisterModel extends OpdRegisterActivityModel { + Context context; + + public ChwAllClientsRegisterModel(Context context) { + this.context = context; + } + @Nullable @Override public JSONObject getFormAsJson(String formName, String entityId, String currentLocationId) { try { - JSONObject form = OpdUtils.getJsonFormToJsonObject(formName); + JSONObject form; + if (context != null) { + form = (new FormUtils()).getFormJsonFromRepositoryOrAssets(context, formName); + } else { + form = OpdUtils.getJsonFormToJsonObject(formName); + } + if (form == null) { return null; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwPncRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwPncRegisterFragmentModel.java index 7c81692f05..755fb8977c 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwPncRegisterFragmentModel.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/ChwPncRegisterFragmentModel.java @@ -1,12 +1,37 @@ package org.smartregister.chw.model; import org.smartregister.chw.core.model.PncRegisterFragmentModel; +import org.smartregister.chw.core.utils.ChildDBConstants; import org.smartregister.chw.core.utils.ChwDBConstants; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; import org.smartregister.family.util.DBConstants; +import java.util.HashSet; +import java.util.Set; + public class ChwPncRegisterFragmentModel extends PncRegisterFragmentModel { + @Override + protected String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + ChwDBConstants.DELIVERY_DATE); + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + + return columnList.toArray(new String[columnList.size()]); + } @Override public String mainSelect(String tableName, String mainCondition) { @@ -14,7 +39,7 @@ public String mainSelect(String tableName, String mainCondition) { queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " AND " + tableName + "." + ChwDBConstants.IS_CLOSED + " IS " + 0 + " AND " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + ChwDBConstants.IS_CLOSED + " IS " + 0 + " AND " + tableName + "." + ChwDBConstants.DELIVERY_DATE + " IS NOT NULL COLLATE NOCASE "); queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY + " ON " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); - queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.ANC_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.ANC_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " AND " + tableName + "." + ChwDBConstants.IS_CLOSED + " IS " + 0 + " AND " + tableName + "." + ChwDBConstants.DELIVERY_DATE + " IS NOT NULL COLLATE NOCASE "); +// queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.ANC_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.ANC_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " AND " + tableName + "." + ChwDBConstants.IS_CLOSED + " IS " + 0 + " AND " + tableName + "." + ChwDBConstants.DELIVERY_DATE + " IS NOT NULL COLLATE NOCASE "); queryBuilder.customJoin("LEFT JOIN (select base_entity_id , max(visit_date) visit_date from visits GROUP by base_entity_id) VISIT_SUMMARY ON VISIT_SUMMARY.base_entity_id = " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); return queryBuilder.mainCondition(mainCondition); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/HivCommunityFollowupFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivCommunityFollowupFragmentModel.java new file mode 100644 index 0000000000..8fc8c553bb --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivCommunityFollowupFragmentModel.java @@ -0,0 +1,59 @@ +package org.smartregister.chw.model; + + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.hiv.model.BaseHivCommunityFollowupModel; +import org.smartregister.chw.hiv.util.Constants.Tables; +import org.smartregister.chw.hiv.util.DBConstants.Key; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class HivCommunityFollowupFragmentModel extends BaseHivCommunityFollowupModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + Key.ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(Tables.HIV_COMMUNITY_FOLLOWUP + "." + Key.REASONS_FOR_ISSUING_COMMUNITY_REFERRAL); + columnList.add(Tables.HIV_COMMUNITY_FOLLOWUP + "." + Key.LAST_INTERACTED_WITH); + columnList.add(Tables.HIV_COMMUNITY_FOLLOWUP + "." + Key.HIV_COMMUNITY_REFERRAL_DATE); + columnList.add(Tables.HIV_COMMUNITY_FOLLOWUP + "." + Key.COMMENTS); + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/HivIndexContactsRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivIndexContactsRegisterFragmentModel.java new file mode 100644 index 0000000000..629b4ac595 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivIndexContactsRegisterFragmentModel.java @@ -0,0 +1,62 @@ +package org.smartregister.chw.model; + + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.hiv.model.BaseHivRegisterFragmentModel; +import org.smartregister.chw.hiv.util.Constants.Tables; +import org.smartregister.chw.hiv.util.DBConstants.Key; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class HivIndexContactsRegisterFragmentModel extends BaseHivRegisterFragmentModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + CoreConstants.TABLE_NAME.FAMILY + " ON " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN (select base_entity_id , max(visit_date) visit_date from visits GROUP by base_entity_id) VISIT_SUMMARY ON VISIT_SUMMARY.base_entity_id = " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(Tables.HIV_INDEX + "." + Key.HIV_CLIENT_ID); + columnList.add(Tables.HIV_INDEX + "." + Key.HIV_TEST_ELIGIBILITY); + columnList.add(Tables.HIV_INDEX + "." + Key.HAS_STARTED_MEDICATION); + columnList.add(Tables.HIV_INDEX + "." + Key.TEST_RESULTS); + columnList.add(Tables.HIV_INDEX + "." + Key.HOW_TO_NOTIFY_CONTACT_CLIENT); + columnList.add(Tables.HIV_INDEX + "." + Key.HAS_THE_CONTACT_CLIENT_BEEN_TESTED); + columnList.add(Tables.HIV_INDEX + "." + Key.FOLLOWED_UP_BY_CHW); + columnList.add(Tables.HIV_INDEX + "." + Key.ENROLLED_TO_CLINIC); + columnList.add(Tables.HIV_INDEX + "." + Key.HIV_INDEX_REGISTRATION_DATE); + columnList.add(Tables.HIV_INDEX + "." + Key.IS_CLOSED); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/HivRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivRegisterFragmentModel.java new file mode 100644 index 0000000000..69fd287d7c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/HivRegisterFragmentModel.java @@ -0,0 +1,59 @@ +package org.smartregister.chw.model; + + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.hiv.model.BaseHivRegisterFragmentModel; +import org.smartregister.chw.hiv.util.DBConstants.Key; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class HivRegisterFragmentModel extends BaseHivRegisterFragmentModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(tableName + "." + Key.CTC_NUMBER); + columnList.add(tableName + "." + Key.CBHS_NUMBER); + columnList.add(tableName+ "." + Key.CLIENT_HIV_STATUS_DURING_REGISTRATION); + columnList.add(tableName+ "." + Key.CLIENT_HIV_STATUS_AFTER_TESTING); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFURecordFeedbackModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFURecordFeedbackModel.java new file mode 100644 index 0000000000..9662c15898 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFURecordFeedbackModel.java @@ -0,0 +1,43 @@ +package org.smartregister.chw.model; + +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.referral.model.BaseIssueReferralModel; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +import androidx.annotation.NonNull; + +public class LTFURecordFeedbackModel extends BaseIssueReferralModel { + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFUReferralModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFUReferralModel.java new file mode 100644 index 0000000000..e1c3a6a692 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/LTFUReferralModel.java @@ -0,0 +1,66 @@ +package org.smartregister.chw.model; + +import org.smartregister.chw.core.model.BaseReferralModel; +import org.smartregister.chw.core.utils.ChwDBConstants; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class LTFUReferralModel extends BaseReferralModel { + + @Override + public String mainSelect(String tableName, String entityTable, String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName, entityTable), CoreConstants.DB_CONSTANTS.ID); + queryBuilder.customJoin(String.format("INNER JOIN %s ON %s.%s = %s.%s AND task.business_status = 'Referred' COLLATE NOCASE ", + entityTable, entityTable, DBConstants.KEY.BASE_ENTITY_ID, tableName, CoreConstants.DB_CONSTANTS.FOR)); + queryBuilder.customJoin(String.format("INNER JOIN %s ON %s.%s = %s.%s COLLATE NOCASE AND ec_referral.chw_referral_service = 'LTFU' COLLATE NOCASE ", CoreConstants.TABLE_NAME.REFERRAL, + CoreConstants.TABLE_NAME.REFERRAL, DBConstants.KEY.BASE_ENTITY_ID, tableName, ChwDBConstants.TaskTable.REASON_REFERENCE)); + queryBuilder.customJoin("LEFT JOIN ec_family ON ec_family_member.relational_id = ec_family.id COLLATE NOCASE"); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + protected String[] mainColumns(String tableName, String entityTable) { + Set columns = new HashSet<>(Arrays.asList(super.mainColumns(tableName, entityTable))); + addClientDetails(entityTable, columns); + addTaskDetails(columns); + return columns.toArray(new String[]{}); + } + + private void addClientDetails(String table, Set columns) { + columns.add(table + "." + "relational_id as relationalid"); + columns.add(table + "." + DBConstants.KEY.BASE_ENTITY_ID); + columns.add(table + "." + DBConstants.KEY.FIRST_NAME); + columns.add(table + "." + DBConstants.KEY.MIDDLE_NAME); + columns.add(table + "." + DBConstants.KEY.LAST_NAME); + columns.add(table + "." + DBConstants.KEY.DOB); + columns.add(table + "." + DBConstants.KEY.GENDER); + columns.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columns.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columns.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columns.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columns.add(CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columns.add(CoreConstants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + + } + + private void addTaskDetails(Set columns) { + columns.add(CoreConstants.TABLE_NAME.TASK + "." + CoreConstants.DB_CONSTANTS.FOCUS); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + CoreConstants.DB_CONSTANTS.OWNER); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + CoreConstants.DB_CONSTANTS.REQUESTER); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + CoreConstants.DB_CONSTANTS.START); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + "reason_reference"); + columns.add(CoreConstants.TABLE_NAME.REFERRAL + "." + org.smartregister.chw.referral.util.DBConstants.Key.PROBLEM + " AS REFERRAL_CLINIC" ); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + "location AS " + org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_HF); + columns.add(CoreConstants.TABLE_NAME.REFERRAL + "." + org.smartregister.chw.referral.util.DBConstants.Key.PROBLEM); + columns.add(CoreConstants.TABLE_NAME.REFERRAL + "." + org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_SERVICE); + columns.add(CoreConstants.TABLE_NAME.REFERRAL + "." + org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_DATE); + columns.add(CoreConstants.TABLE_NAME.TASK + "." + CoreConstants.DB_CONSTANTS.FOCUS + " AS " + org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_TYPE); + + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/MalariaRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/MalariaRegisterFragmentModel.java new file mode 100644 index 0000000000..9d978c8746 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/MalariaRegisterFragmentModel.java @@ -0,0 +1,54 @@ +package org.smartregister.chw.model; + +import androidx.annotation.NonNull; + +import org.smartregister.chw.core.model.CoreMalariaRegisterFragmentModel; +import org.smartregister.chw.util.ChildDBConstants; +import org.smartregister.chw.util.ChwDBConstants; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class MalariaRegisterFragmentModel extends CoreMalariaRegisterFragmentModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.ANC_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.ANC_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.PNC_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.PNC_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + protected String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + columnList.add(tableName + "." + DBConstants.KEY.LAST_INTERACTED_WITH); + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(tableName + "." + org.smartregister.chw.malaria.util.DBConstants.KEY.MALARIA_TEST_DATE); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.ENTITY_TYPE); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add(Constants.TABLE_NAME.PNC_MEMBER + "." + ChwDBConstants.DELIVERY_DATE); + columnList.add(Constants.TABLE_NAME.PNC_MEMBER + "." + ChwDBConstants.IS_CLOSED + " as " + org.smartregister.chw.malaria.util.DBConstants.KEY.IS_PNC_CLOSED); + columnList.add(Constants.TABLE_NAME.ANC_MEMBER + "." + ChwDBConstants.IS_CLOSED + " as " + org.smartregister.chw.malaria.util.DBConstants.KEY.IS_ANC_CLOSED); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + org.smartregister.chw.anc.util.DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/MotherChampionRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/MotherChampionRegisterFragmentModel.java new file mode 100644 index 0000000000..07a5199ba6 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/MotherChampionRegisterFragmentModel.java @@ -0,0 +1,52 @@ +package org.smartregister.chw.model; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.pmtct.model.BasePmtctRegisterFragmentModel; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +import androidx.annotation.NonNull; + +public class MotherChampionRegisterFragmentModel extends BasePmtctRegisterFragmentModel { + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName+ "." +DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + org.smartregister.chw.tb.util.DBConstants.Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/PmtctFollowupRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/PmtctFollowupRegisterFragmentModel.java new file mode 100644 index 0000000000..76925cc30f --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/PmtctFollowupRegisterFragmentModel.java @@ -0,0 +1,52 @@ +package org.smartregister.chw.model; + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.pmtct.model.BasePmtctRegisterFragmentModel; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class PmtctFollowupRegisterFragmentModel extends BasePmtctRegisterFragmentModel { + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + ".entity_id" + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + ".entity_id AS " + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + org.smartregister.chw.tb.util.DBConstants.Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccRegisterFragmentModel.java new file mode 100644 index 0000000000..0d69314788 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccRegisterFragmentModel.java @@ -0,0 +1,32 @@ +package org.smartregister.chw.model; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.pmtct.model.BasePmtctRegisterFragmentModel; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +import androidx.annotation.NonNull; + +public class SbccRegisterFragmentModel extends BasePmtctRegisterFragmentModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccSessionModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccSessionModel.java new file mode 100644 index 0000000000..b11efc7077 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/SbccSessionModel.java @@ -0,0 +1,51 @@ +package org.smartregister.chw.model; + +public class SbccSessionModel { + private String sessionDate; + private String sessionLocation; + private String sessionId; + + public String getSessionParticipants() { + return sessionParticipants; + } + + public void setSessionParticipants(String sessionParticipants) { + this.sessionParticipants = sessionParticipants; + } + + private String sessionParticipants; + + public SbccSessionModel() { + } + + public SbccSessionModel(String sessionDate, String sessionLocation, String sessionId) { + this.sessionDate = sessionDate; + this.sessionLocation = sessionLocation; + this.sessionId = sessionId; + } + + public String getSessionDate() { + return sessionDate; + } + + + public void setSessionDate(String sessionDate) { + this.sessionDate = sessionDate; + } + + public String getSessionLocation() { + return sessionLocation; + } + + public void setSessionLocation(String sessionLocation) { + this.sessionLocation = sessionLocation; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/TbCommunityFollowupFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/TbCommunityFollowupFragmentModel.java new file mode 100644 index 0000000000..9ab1521ef5 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/TbCommunityFollowupFragmentModel.java @@ -0,0 +1,63 @@ +package org.smartregister.chw.model; + + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.tb.model.BaseTbCommunityFollowupModel; +import org.smartregister.chw.tb.util.Constants.Tables; +import org.smartregister.chw.tb.util.DBConstants.Key; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +import timber.log.Timber; + +public class TbCommunityFollowupFragmentModel extends BaseTbCommunityFollowupModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + Key.ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + Timber.e("Coze :: query = "+queryBuilder.toString()); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(Tables.TB_COMMUNITY_FOLLOWUP + "." + Key.REASONS_FOR_ISSUING_COMMUNITY_REFERRAL); + columnList.add(Tables.TB_COMMUNITY_FOLLOWUP + "." + Key.LAST_INTERACTED_WITH); + columnList.add(Tables.TB_COMMUNITY_FOLLOWUP + "." + Key.TB_COMMUNITY_REFERRAL_DATE); + columnList.add(Tables.TB_COMMUNITY_FOLLOWUP + "." + Key.COMMENTS); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/model/TbRegisterFragmentModel.java b/opensrp-chw/src/main/java/org/smartregister/chw/model/TbRegisterFragmentModel.java new file mode 100644 index 0000000000..a41d2ae988 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/model/TbRegisterFragmentModel.java @@ -0,0 +1,60 @@ +package org.smartregister.chw.model; + + +import androidx.annotation.NonNull; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.core.utils.ChildDBConstants; +import org.smartregister.chw.tb.model.BaseTbRegisterFragmentModel; +import org.smartregister.chw.tb.util.Constants.Tables; +import org.smartregister.chw.tb.util.DBConstants.Key; +import org.smartregister.chw.util.Constants; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.family.util.DBConstants; + +import java.util.HashSet; +import java.util.Set; + +public class TbRegisterFragmentModel extends BaseTbRegisterFragmentModel { + + @NonNull + @Override + public String mainSelect(@NonNull String tableName, @NonNull String mainCondition) { + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName)); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " ON " + tableName + "." + DBConstants.KEY.BASE_ENTITY_ID + " = " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.BASE_ENTITY_ID + " COLLATE NOCASE "); + queryBuilder.customJoin("INNER JOIN " + Constants.TABLE_NAME.FAMILY + " ON " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " = " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T1 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.PRIMARY_CAREGIVER + " = T1." + DBConstants.KEY.BASE_ENTITY_ID); + queryBuilder.customJoin("LEFT JOIN " + Constants.TABLE_NAME.FAMILY_MEMBER + " as T2 ON " + Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FAMILY_HEAD + " = T2." + DBConstants.KEY.BASE_ENTITY_ID); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + @NotNull + public String[] mainColumns(String tableName) { + Set columnList = new HashSet<>(); + + columnList.add(tableName + "." + DBConstants.KEY.BASE_ENTITY_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID + " as " + ChildDBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.FIRST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.MIDDLE_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.LAST_NAME); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DOB); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.GENDER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.UNIQUE_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.RELATIONAL_ID); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.OTHER_PHONE_NUMBER); + columnList.add("T2." + DBConstants.KEY.PHONE_NUMBER + " AS " + Key.FAMILY_HEAD_PHONE_NUMBER); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.VILLAGE_TOWN); + columnList.add("T1." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T1." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.PRIMARY_CAREGIVER); + columnList.add("T2." + DBConstants.KEY.FIRST_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.MIDDLE_NAME + " || " + "' '" + " || " + "T2." + DBConstants.KEY.LAST_NAME + " AS " + DBConstants.KEY.FAMILY_HEAD); + columnList.add(Constants.TABLE_NAME.FAMILY + "." + DBConstants.KEY.FIRST_NAME + " as " + org.smartregister.chw.anc.util.DBConstants.KEY.FAMILY_NAME); + columnList.add(Tables.TB + "." + Key.PLACE_OF_DOMICILE); + columnList.add(Tables.TB + "." + Key.COMMUNITY_CLIENT_TB_REGISTRATION_NUMBER); + columnList.add(Tables.TB + "." + Key.CLIENT_TB_STATUS_DURING_REGISTRATION); + columnList.add(Tables.TB + "." + Key.CLIENT_TB_STATUS_AFTER_TESTING); + + return columnList.toArray(new String[columnList.size()]); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AllClientsMemberPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AllClientsMemberPresenter.java index 6ad9427050..1aad4e7d30 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AllClientsMemberPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AllClientsMemberPresenter.java @@ -4,49 +4,21 @@ import org.apache.commons.lang3.tuple.Triple; import org.smartregister.chw.activity.AllClientsMemberProfileActivity; import org.smartregister.chw.anc.util.NCUtils; -import org.smartregister.chw.contract.AllClientsMemberContract; +import org.smartregister.chw.core.activity.CoreAllClientsMemberProfileActivity; import org.smartregister.chw.core.application.CoreChwApplication; +import org.smartregister.chw.core.presenter.CoreAllClientsMemberPresenter; import org.smartregister.chw.dao.FamilyDao; -import org.smartregister.chw.interactor.AllClientsMemberInteractor; -import org.smartregister.chw.model.AllClientsMemberModel; import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.family.contract.FamilyOtherMemberContract; -import org.smartregister.family.contract.FamilyProfileContract; -import org.smartregister.family.domain.FamilyEventClient; import org.smartregister.family.util.DBConstants; import org.smartregister.family.util.Utils; -import java.lang.ref.WeakReference; import java.text.MessageFormat; import static org.smartregister.chw.util.Utils.getClientName; -public class AllClientsMemberPresenter implements AllClientsMemberContract.Presenter, FamilyProfileContract.InteractorCallBack, FamilyOtherMemberContract.InteractorCallBack { - - private AllClientsMemberContract.Interactor interactor; - - private WeakReference view; - private String baseEntityId; - - public AllClientsMemberPresenter(AllClientsMemberProfileActivity allClientsMemberProfileActivity, String baseEntityId) { - this.baseEntityId = baseEntityId; - interactor = new AllClientsMemberInteractor(); - view = new WeakReference<>(allClientsMemberProfileActivity); - } - - @Override - public void updateLocationInfo(String jsonString, String familyBaseEntityId) { - interactor.updateLocationInfo(jsonString, new AllClientsMemberModel().processJsonForm(jsonString, familyBaseEntityId), this); - } - - @Override - public AllClientsMemberContract.View getView() { - return view.get(); - } - - @Override - public void startFormForEdit(CommonPersonObjectClient client) { - //Overridden: Not Needed +public class AllClientsMemberPresenter extends CoreAllClientsMemberPresenter { + public AllClientsMemberPresenter(CoreAllClientsMemberProfileActivity allClientsMemberProfileActivity, String baseEntityId) { + super(allClientsMemberProfileActivity, baseEntityId); } @Override @@ -85,21 +57,4 @@ public void onUniqueIdFetched(Triple triple, String enti public void onNoUniqueId() { //Overridden: Not Needed } - - @Override - public void onRegistrationSaved(boolean editMode, boolean isSaved, FamilyEventClient familyEventClient) { - AllClientsMemberProfileActivity view = (AllClientsMemberProfileActivity) getView(); - if (editMode) { - view.hideProgressDialog(); - - refreshProfileView(); - - view.refreshList(); - } - } - - @Override - public void refreshProfileView() { - interactor.updateProfileInfo(baseEntityId, this); - } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AncMemberProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AncMemberProfilePresenter.java index f6c8780e2f..afbbf64332 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AncMemberProfilePresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/AncMemberProfilePresenter.java @@ -11,6 +11,7 @@ import org.smartregister.chw.anc.domain.MemberObject; import org.smartregister.chw.core.contract.AncMemberProfileContract; import org.smartregister.chw.core.presenter.CoreAncMemberProfilePresenter; +import org.smartregister.chw.dao.ChwAncDao; import org.smartregister.chw.model.ReferralTypeModel; import org.smartregister.chw.util.Constants; import org.smartregister.chw.util.Utils; @@ -39,6 +40,26 @@ public void referToFacility() { } } + @Override + public void refreshProfileTopSection(MemberObject memberObject) { + super.refreshProfileTopSection(memberObject); + String riskLabel = org.smartregister.chw.anc.util.Constants.HOME_VISIT.PREGNANCY_RISK_LOW; + if(ChwAncDao.isClientHighRisk(memberObject.getBaseEntityId())){ + riskLabel = org.smartregister.chw.anc.util.Constants.HOME_VISIT.PREGNANCY_RISK_HIGH; + } + getView().setPregnancyRiskLabel(riskLabel); + } + + @Override + public void setPregnancyRiskTransportProfileDetails(MemberObject memberObject) { + super.setPregnancyRiskTransportProfileDetails(memberObject); + String riskLabel = org.smartregister.chw.anc.util.Constants.HOME_VISIT.PREGNANCY_RISK_LOW; + if(ChwAncDao.isClientHighRisk(memberObject.getBaseEntityId())){ + riskLabel = org.smartregister.chw.anc.util.Constants.HOME_VISIT.PREGNANCY_RISK_HIGH; + } + getView().setPregnancyRiskLabel(riskLabel); + } + @Override public void startAncReferralForm() { if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { @@ -47,7 +68,7 @@ public void startAncReferralForm() { JSONObject formJson = (new FormUtils()).getFormJsonFromRepositoryOrAssets(context, Constants.JSON_FORM.getAncUnifiedReferralForm()); formJson.put(Constants.REFERRAL_TASK_FOCUS, referralTypeModels.get(0).getReferralType()); ReferralRegistrationActivity.startGeneralReferralFormActivityForResults(context, - getEntityId(), formJson, true); + getEntityId(), formJson, false); } catch (Exception ex) { Timber.e(ex); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChildProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChildProfilePresenter.java index e05e168ac0..e417fac0ff 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChildProfilePresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChildProfilePresenter.java @@ -90,7 +90,7 @@ public void startSickChildReferralForm() { JSONObject formJson = (new FormUtils()).getFormJsonFromRepositoryOrAssets(getView().getContext(), Constants.JSON_FORM.getChildUnifiedReferralForm()); formJson.put(Constants.REFERRAL_TASK_FOCUS, referralTypeModels.get(0).getReferralType()); ReferralRegistrationActivity.startGeneralReferralFormActivityForResults((Activity) getView().getContext(), - getChildBaseEntityId(), formJson, true); + getChildBaseEntityId(), formJson, false); } catch (Exception e) { Timber.e(e); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAllClientRegisterPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAllClientRegisterPresenter.java index f117ba9b3b..b09a7919c7 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAllClientRegisterPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAllClientRegisterPresenter.java @@ -50,11 +50,6 @@ public void onRegistrationSaved(boolean inEditMode) { if (getView() != null) { getView().refreshList(FetchStatus.fetched); getView().hideProgressDialog(); - NavigationMenu navigationMenu = NavigationMenu.getInstance((Activity) viewReference.get(), - null, null); - if (navigationMenu != null) { - navigationMenu.refreshCount(); - } } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAncPartnerFollowupRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAncPartnerFollowupRegisterFragmentPresenter.java new file mode 100644 index 0000000000..6ee010fb20 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ChwAncPartnerFollowupRegisterFragmentPresenter.java @@ -0,0 +1,39 @@ +package org.smartregister.chw.presenter; + +import org.smartregister.chw.anc.contract.BaseAncRegisterFragmentContract; +import org.smartregister.chw.anc.util.DBConstants; +import org.smartregister.chw.core.presenter.AncRegisterFragmentPresenter; +import org.smartregister.chw.core.utils.CoreConstants; + +public class ChwAncPartnerFollowupRegisterFragmentPresenter extends AncRegisterFragmentPresenter { + + public ChwAncPartnerFollowupRegisterFragmentPresenter(BaseAncRegisterFragmentContract.View view, BaseAncRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + public String getDefaultSortQuery() { + return " MAX(ec_anc_register.last_interacted_with , ifnull(VISIT_SUMMARY.visit_date,0)) DESC "; + } + + + @Override + public String getMainCondition() { + return " " + CoreConstants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.KEY.DATE_REMOVED + " is null " + + "AND " + CoreConstants.TABLE_NAME.ANC_MEMBER + "." + DBConstants.KEY.IS_CLOSED + " is 0 " + + "AND last_menstrual_period <> '0' " + + "AND " + CoreConstants.TABLE_NAME.ANC_PARTNER_FOLLOWUP + "." + org.smartregister.chw.hiv.util.DBConstants.Key.BASE_ENTITY_ID + " NOT IN " + + "(SELECT referral_form_id" + + " FROM ec_anc_partner_community_feedback" + + " WHERE client_found = 'no'" + + " or (client_found = 'yes'" + + " and partner_agree_attending_hf is not null" + + " and (partner_agree_attending_hf = 'no' or " + + " ec_anc_partner_community_feedback.base_entity_id in (select feedback_form_id from ec_anc_partners)))) "; + } + + @Override + public String getMainTable() { + return CoreConstants.TABLE_NAME.ANC_MEMBER; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/CompletedReferralRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/CompletedReferralRegisterFragmentPresenter.java new file mode 100644 index 0000000000..8b5f855031 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/CompletedReferralRegisterFragmentPresenter.java @@ -0,0 +1,49 @@ +package org.smartregister.chw.presenter; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.ChwDBConstants; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.referral.contract.BaseReferralRegisterFragmentContract; +import org.smartregister.chw.referral.presenter.BaseReferralRegisterFragmentPresenter; +import org.smartregister.chw.referral.util.DBConstants; +import org.smartregister.chw.util.Constants; + +import static org.smartregister.chw.referral.util.Constants.ReferralType; +import static org.smartregister.chw.referral.util.Constants.Tables; + +public class CompletedReferralRegisterFragmentPresenter extends BaseReferralRegisterFragmentPresenter { + + public CompletedReferralRegisterFragmentPresenter(BaseReferralRegisterFragmentContract.View view, BaseReferralRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + @NotNull + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + + "AND " + Tables.REFERRAL + "." + DBConstants.Key.REFERRAL_TYPE + " = '" + ReferralType.COMMUNITY_TO_FACILITY_REFERRAL + "' " + + "AND " + CoreConstants.TABLE_NAME.TASK + "." + ChwDBConstants.TaskTable.BUSINESS_STATUS + " = '" + CoreConstants.BUSINESS_STATUS.COMPLETE + "' "; + + } + + @Override + @NotNull + public String getDueFilterCondition() { + return " "; + + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @Override + public String getMainTable() { + return Tables.REFERRAL; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/FamilyProfileMemberPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/FamilyProfileMemberPresenter.java index a4923886b3..eec3ad67fb 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/FamilyProfileMemberPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/FamilyProfileMemberPresenter.java @@ -28,6 +28,6 @@ public String getMainCondition() { } public String getChildFilter() { - return " and (( ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.ENTRY_POINT + ",'') <> 'PNC' ) or (ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.ENTRY_POINT + ",'') = 'PNC' and ( date(" + CoreConstants.TABLE_NAME.CHILD + "." + DBConstants.KEY.DOB + ", '+28 days') <= date() and ((SELECT is_closed FROM ec_family_member WHERE base_entity_id = " + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.MOTHER_ENTITY_ID + " ) = 0))) or (ifnull(ec_child.entry_point,'') = 'PNC' and (SELECT is_closed FROM ec_family_member WHERE base_entity_id = ec_child.mother_entity_id ) = 1)) " ; + return " and (( ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.ENTRY_POINT + ",'') <> 'PNC' ) or (ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.ENTRY_POINT + ",'') = 'PNC' and ( date(" + CoreConstants.TABLE_NAME.CHILD + "." + DBConstants.KEY.DOB + ", '+42 days') <= date() and ((SELECT is_closed FROM ec_family_member WHERE base_entity_id = " + CoreConstants.TABLE_NAME.CHILD + "." + ChildDBConstants.KEY.MOTHER_ENTITY_ID + " ) = 0))) or (ifnull(ec_child.entry_point,'') = 'PNC' and (SELECT is_closed FROM ec_family_member WHERE base_entity_id = ec_child.mother_entity_id ) = 1)) " ; } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivCommunityFollowupFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivCommunityFollowupFragmentPresenter.java new file mode 100644 index 0000000000..120e013923 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivCommunityFollowupFragmentPresenter.java @@ -0,0 +1,45 @@ +package org.smartregister.chw.presenter; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.hiv.contract.BaseHivRegisterFragmentContract; +import org.smartregister.chw.hiv.presenter.BaseHivCommunityFollowupPresenter; +import org.smartregister.chw.hiv.util.Constants.Tables; +import org.smartregister.chw.hiv.util.DBConstants; +import org.smartregister.chw.util.Constants; + +public class HivCommunityFollowupFragmentPresenter extends BaseHivCommunityFollowupPresenter { + + public HivCommunityFollowupFragmentPresenter(BaseHivRegisterFragmentContract.View view, BaseHivRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + @NotNull + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + + "AND " + Tables.HIV_COMMUNITY_FOLLOWUP + "." + DBConstants.Key.IS_CLOSED + " = '0' " + + "AND " + Tables.HIV_COMMUNITY_FOLLOWUP + "." + DBConstants.Key.BASE_ENTITY_ID + " NOT IN (SELECT " + DBConstants.Key.COMMUNITY_REFERRAL_FORM_ID + " FROM " + Tables.HIV_COMMUNITY_FEEDBACK + " ) "; + + } + + @Override + @NotNull + public String getDueFilterCondition() { + return CoreConstants.TABLE_NAME.HIV_MEMBER + ".base_entity_id in (select base_entity_id from schedule_service where strftime('%Y-%m-%d') BETWEEN due_date and expiry_date and schedule_name = '" + CoreConstants.SCHEDULE_TYPES.HIV_VISIT + "' and ifnull(not_done_date,'') = '' and ifnull(completion_date,'') = '' ) "; + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @Override + public String getMainTable() { + return Tables.HIV_COMMUNITY_FOLLOWUP; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactProfilePresenter.java new file mode 100644 index 0000000000..e21789d7ca --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactProfilePresenter.java @@ -0,0 +1,31 @@ +package org.smartregister.chw.presenter; + +import android.app.Activity; + +import org.smartregister.chw.activity.HivIndexContactProfileActivity; +import org.smartregister.chw.activity.HivProfileActivity; +import org.smartregister.chw.contract.HivIndexContactProfileContract; +import org.smartregister.chw.core.presenter.CoreHivIndexContactProfilePresenter; +import org.smartregister.chw.hiv.domain.HivIndexContactObject; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.util.Utils; + +import java.util.List; + +public class HivIndexContactProfilePresenter extends CoreHivIndexContactProfilePresenter + implements org.smartregister.chw.contract.AncMemberProfileContract.Presenter { + + private HivIndexContactObject hivIndexContactObject; + + public HivIndexContactProfilePresenter(HivIndexContactProfileContract.View view, HivIndexContactProfileContract.Interactor interactor, + HivIndexContactObject hivIndexContactObject) { + super(view, interactor, hivIndexContactObject); + this.hivIndexContactObject = hivIndexContactObject; + } + + @Override + public void referToFacility() { + List referralTypeModels = ((HivIndexContactProfileActivity) getView()).getReferralTypeModels(); + Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, hivIndexContactObject.getBaseEntityId()); + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactsContactsRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactsContactsRegisterFragmentPresenter.java new file mode 100644 index 0000000000..26fb59c2ae --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivIndexContactsContactsRegisterFragmentPresenter.java @@ -0,0 +1,50 @@ +package org.smartregister.chw.presenter; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.hiv.contract.BaseHivRegisterFragmentContract; +import org.smartregister.chw.hiv.presenter.BaseHivIndexContactsRegisterFragmentPresenter; +import org.smartregister.chw.hiv.util.Constants.Tables; +import org.smartregister.chw.hiv.util.DBConstants; + +public class HivIndexContactsContactsRegisterFragmentPresenter extends BaseHivIndexContactsRegisterFragmentPresenter { + + public HivIndexContactsContactsRegisterFragmentPresenter(BaseHivRegisterFragmentContract.View view, BaseHivRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + @NotNull + public String getMainCondition() { + return " " + + Tables.HIV_INDEX + "." + DBConstants.Key.TEST_RESULTS + " IS NULL AND " + + Tables.HIV_INDEX + "." + DBConstants.Key.REFER_TO_CHW + " = 'Yes' COLLATE NOCASE AND " + + Tables.HIV_INDEX + "." + DBConstants.Key.HOW_TO_NOTIFY_CONTACT_CLIENT + " <> 'na'"; + + } + + @Override + @NotNull + public String getDueFilterCondition() { + return " " + + Tables.HIV_INDEX + "." + DBConstants.Key.FOLLOWED_UP_BY_CHW + " IS NULL"; + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + + + if (getConfig().getFilterFields() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @Override + public String getMainTable() { + return Tables.HIV_INDEX; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivProfilePresenter.java new file mode 100644 index 0000000000..34d42ace37 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivProfilePresenter.java @@ -0,0 +1,30 @@ +package org.smartregister.chw.presenter; + +import android.app.Activity; + +import org.smartregister.chw.activity.HivProfileActivity; +import org.smartregister.chw.contract.HivProfileContract; +import org.smartregister.chw.core.presenter.CoreHivProfilePresenter; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.util.Utils; + +import java.util.List; + +public class HivProfilePresenter extends CoreHivProfilePresenter + implements org.smartregister.chw.contract.AncMemberProfileContract.Presenter { + + private HivMemberObject hivMemberObject; + + public HivProfilePresenter(HivProfileContract.View view, HivProfileContract.Interactor interactor, + HivMemberObject hivMemberObject) { + super(view, interactor, hivMemberObject); + this.hivMemberObject = hivMemberObject; + } + + @Override + public void referToFacility() { + List referralTypeModels = ((HivProfileActivity) getView()).getReferralTypeModels(); + Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, hivMemberObject.getBaseEntityId()); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivRegisterFragmentPresenter.java new file mode 100644 index 0000000000..b1e31abb28 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/HivRegisterFragmentPresenter.java @@ -0,0 +1,50 @@ +package org.smartregister.chw.presenter; + +import static org.smartregister.chw.util.Constants.TableName.CBHS_REGISTER; +import androidx.annotation.NonNull; +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.hiv.contract.BaseHivRegisterFragmentContract; +import org.smartregister.chw.hiv.presenter.BaseHivRegisterFragmentPresenter; +import org.smartregister.chw.hiv.util.DBConstants; +import org.smartregister.chw.util.Constants; + +public class HivRegisterFragmentPresenter extends BaseHivRegisterFragmentPresenter { + public HivRegisterFragmentPresenter(BaseHivRegisterFragmentContract.View view, BaseHivRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + + @Override + @NotNull + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + + "AND " + CBHS_REGISTER + "." + DBConstants.Key.IS_CLOSED + " = '0' "; + } + + @Override + @NotNull + public String getDueFilterCondition() { + return CBHS_REGISTER + ".base_entity_id in (select base_entity_id from schedule_service where strftime('%Y-%m-%d') BETWEEN due_date and expiry_date and schedule_name = '" + CoreConstants.SCHEDULE_TYPES.HIV_VISIT + "' and ifnull(not_done_date,'') = '' and ifnull(completion_date,'') = '' ) "; + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @NonNull + @Override + public String getDefaultSortQuery() { + return getMainTable() + "." + DBConstants.Key.HIV_REGISTRATION_DATE + " DESC "; + } + + @Override + public String getMainTable() { + return CBHS_REGISTER; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFURecordFeedbackPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFURecordFeedbackPresenter.java new file mode 100644 index 0000000000..ab82de0f2c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFURecordFeedbackPresenter.java @@ -0,0 +1,243 @@ +package org.smartregister.chw.presenter; + +import android.app.Activity; + +import com.nerdstone.neatformcore.domain.model.NFormViewData; + +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.json.JSONObject; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.custom_views.NavigationMenu; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.CoreReferralUtils; +import org.smartregister.chw.model.LTFURecordFeedbackModel; +import org.smartregister.chw.referral.contract.BaseIssueReferralContract; +import org.smartregister.chw.referral.model.AbstractIssueReferralModel; +import org.smartregister.chw.referral.presenter.BaseIssueReferralPresenter; +import org.smartregister.chw.referral.util.DBConstants; +import org.smartregister.chw.util.Constants; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.clientandeventmodel.Obs; +import org.smartregister.domain.Location; +import org.smartregister.domain.Task; +import org.smartregister.family.FamilyLibrary; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.repository.BaseRepository; +import org.smartregister.repository.LocationRepository; +import org.smartregister.sync.helper.ECSyncHelper; +import org.smartregister.util.JsonFormUtils; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import androidx.annotation.NonNull; +import timber.log.Timber; + + +public class LTFURecordFeedbackPresenter extends BaseIssueReferralPresenter { + private final String referralHf; + private final String taskId; + private final String baseEntityId; + + public LTFURecordFeedbackPresenter(@NonNull String baseEntityID, String taskId, String referralHf, @NonNull BaseIssueReferralContract.View view, @NonNull Class viewModelClass, @NonNull BaseIssueReferralContract.Interactor interactor) { + super(baseEntityID, view, viewModelClass, interactor); + this.referralHf = referralHf; + this.baseEntityId = baseEntityID; + this.taskId = taskId; + } + + + @Override + public Class getViewModel() { + return LTFURecordFeedbackModel.class; + } + + @NonNull + @Override + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.BASE_ENTITY_ID + " = '" + baseEntityId + "'"; + } + + @NotNull + @Override + public String getMainTable() { + return Constants.TABLE_NAME.FAMILY_MEMBER; + } + + @Override + public void onRegistrationSaved(boolean saveSuccessful) { + NavigationMenu navigationMenu = NavigationMenu.getInstance((Activity) getView(), + null, null); + if (navigationMenu != null) { + navigationMenu.refreshCount(); + } + } + + @Override + public void saveForm(@NonNull HashMap valuesHashMap, @NonNull JSONObject jsonObject) { + //first close the referral task + //if from the valuesHasMap followupStatus value is client_found_ready_to_return then call save form super + //else create an event that just sends the feedback to the server + if (StringUtils.containsIgnoreCase(String.valueOf(valuesHashMap.get("followup_status").getValue()), "client_found_ready_to_return")) { + tagWithReferralDetails(valuesHashMap); + super.saveForm(valuesHashMap, jsonObject); + } + try { + createFeedbackEvent(valuesHashMap); + } catch (Exception e) { + Timber.e(e); + } + saveCloseReferralEvent(); + completeTask(); + + } + + private void tagWithReferralDetails(HashMap valuesHashMap) { + + LocationRepository locationRepository = new LocationRepository(); + Location location = locationRepository.getLocationById(referralHf); + + valuesHashMap.put("problem", generateProblem()); + valuesHashMap.put("chw_referral_hf", generateChwReferralHf(referralHf, location.getProperties().getName())); + } + + private NFormViewData generateProblem() { + NFormViewData problem = new NFormViewData(); + NFormViewData problemValue = new NFormViewData(); + HashMap problemValueHash = new HashMap<>(); + + + HashMap problemMetaData = new HashMap<>(); + problemMetaData.put("openmrs_entity", "concept"); + problemMetaData.put("openmrs_entity_id", "problem"); + + HashMap problemValueMetaData = new HashMap<>(); + problemValueMetaData.put("openmrs_entity", "concept"); + problemValueMetaData.put("openmrs_entity_id", "client_returning_to_services"); + + problemValue.setMetadata(problemValueMetaData); + problemValue.setValue("LTF Client Returning to Service"); + + problemValueHash.put("client_returning_to_services", problemValue); + + problem.setMetadata(problemMetaData); + problem.setValue(problemValueHash); + problem.setVisible(true); + problem.setType("Calculation"); + + return problem; + } + + private NFormViewData generateChwReferralHf(String referralHfCode, String referralHfName) { + NFormViewData chwReferralHf = new NFormViewData(); + HashMap chwReferralHfMetaData = new HashMap<>(); + + NFormViewData chwReferralHfValue = new NFormViewData(); + HashMap chwReferralHfValueMetaData = new HashMap<>(); + + chwReferralHfValueMetaData.put("openmrs_entity", "concept"); + chwReferralHfValueMetaData.put("openmrs_entity_id", referralHfCode); + + chwReferralHfValue.setMetadata(chwReferralHfValueMetaData); + + chwReferralHfValue.setValue(referralHfName); + + chwReferralHfMetaData.put("openmrs_entity", "concept"); + chwReferralHfMetaData.put("openmrs_entity_id", "chw_referral_hf"); + + chwReferralHf.setMetadata(chwReferralHfMetaData); + chwReferralHf.setValue(chwReferralHfValue); + chwReferralHf.setVisible(true); + chwReferralHf.setType("Calculation"); + + return chwReferralHf; + } + + private void saveCloseReferralEvent() { + try { + AllSharedPreferences sharedPreferences = Utils.getAllSharedPreferences(); + ECSyncHelper syncHelper = FamilyLibrary.getInstance().getEcSyncHelper(); + Event baseEvent = (Event) new Event() + .withBaseEntityId(baseEntityId) + .withEventDate(new Date()) + .withEventType(CoreConstants.EventType.CLOSE_REFERRAL) + .withFormSubmissionId(JsonFormUtils.generateRandomUUIDString()) + .withEntityType(CoreConstants.TABLE_NAME.CLOSE_REFERRAL) + .withProviderId(sharedPreferences.fetchRegisteredANM()) + .withLocationId(getTask().getLocation()) + .withTeamId(sharedPreferences.fetchDefaultTeamId(sharedPreferences.fetchRegisteredANM())) + .withTeam(sharedPreferences.fetchDefaultTeam(sharedPreferences.fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + + baseEvent.addObs((new Obs()).withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK).withValue(getTask().getIdentifier()) + .withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK).withFieldType("formsubmissionField").withFieldDataType("text").withParentCode("").withHumanReadableValues(new ArrayList<>())); + baseEvent.addObs((new Obs()).withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK_PREVIOUS_STATUS).withValue(getTask().getStatus()) + .withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK_PREVIOUS_STATUS).withFieldType("formsubmissionField").withFieldDataType("text").withParentCode("").withHumanReadableValues(new ArrayList<>())); + baseEvent.addObs((new Obs()).withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK_PREVIOUS_BUSINESS_STATUS).withValue(getTask().getBusinessStatus()) + .withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK_PREVIOUS_BUSINESS_STATUS).withFieldType("formsubmissionField").withFieldDataType("text").withParentCode("").withHumanReadableValues(new ArrayList<>())); + org.smartregister.chw.util.JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), baseEvent);// tag docs + + //setting the location uuid of the referral initiator so that to allow the event to sync back to the chw app since it sync data by location. + baseEvent.setLocationId(getTask().getLocation()); + + JSONObject eventJson = new JSONObject(JsonFormUtils.gson.toJson(baseEvent)); + syncHelper.addEvent(baseEntityId, eventJson); + long lastSyncTimeStamp = ChwApplication.getInstance().getContext().allSharedPreferences().fetchLastUpdatedAtDate(0); + Date lastSyncDate = new Date(lastSyncTimeStamp); + ChwApplication.getClientProcessor(ChwApplication.getInstance().getContext().applicationContext()).processClient(syncHelper.getEvents(lastSyncDate, BaseRepository.TYPE_Unprocessed)); + ChwApplication.getInstance().getContext().allSharedPreferences().saveLastUpdatedAtDate(lastSyncDate.getTime()); + } catch (Exception e) { + Timber.e(e, "LTFURecordFeedbackPresenter --> saveCloseReferralEvent"); + } + + } + + private void createFeedbackEvent(HashMap valuesHashMap) throws Exception { + List obs = org.smartregister.chw.util.JsonFormUtils.getObsForNeatForm(valuesHashMap); + if (obs.size() > 0) { + Event baseEvent = (Event) new Event() + .withBaseEntityId(baseEntityId) + .withEventDate(new Date()) + .withEventType("LTFU Feedback") + .withFormSubmissionId(JsonFormUtils.generateRandomUUIDString()) + .withEntityType(CoreConstants.TABLE_NAME.REFERRAL) + .withProviderId(Utils.getAllSharedPreferences().fetchRegisteredANM()) + .withLocationId(referralHf) + .withTeamId(Utils.getAllSharedPreferences().fetchDefaultTeamId(Utils.getAllSharedPreferences().fetchRegisteredANM())) + .withTeam(Utils.getAllSharedPreferences().fetchDefaultTeam(Utils.getAllSharedPreferences().fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + + for (Obs ob : obs) { + baseEvent.addObs(ob); + } + baseEvent.addObs((new Obs()).withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK).withValue(getTask().getIdentifier()) + .withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK).withFieldType("formsubmissionField").withFieldDataType("text").withParentCode("").withHumanReadableValues(new ArrayList<>())); + JSONObject eventJson = new JSONObject(JsonFormUtils.gson.toJson(baseEvent)); + FamilyLibrary.getInstance().getEcSyncHelper().addEvent(baseEntityId, eventJson); + long lastSyncTimeStamp = ChwApplication.getInstance().getContext().allSharedPreferences().fetchLastUpdatedAtDate(0); + Date lastSyncDate = new Date(lastSyncTimeStamp); + ChwApplication.getClientProcessor(ChwApplication.getInstance().getContext().applicationContext()).processClient(FamilyLibrary.getInstance().getEcSyncHelper().getEvents(lastSyncDate, BaseRepository.TYPE_Unprocessed)); + ChwApplication.getInstance().getContext().allSharedPreferences().saveLastUpdatedAtDate(lastSyncDate.getTime()); + } + } + + private Task getTask() { + return ChwApplication.getInstance().getTaskRepository().getTaskByIdentifier(taskId); + } + + private void completeTask() { + Task currentTask = getTask(); + currentTask.setForEntity(baseEntityId); + currentTask.setStatus(Task.TaskStatus.IN_PROGRESS); + CoreReferralUtils.completeTask(currentTask, false); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFUReferralFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFUReferralFragmentPresenter.java new file mode 100644 index 0000000000..2a3c4aca58 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LTFUReferralFragmentPresenter.java @@ -0,0 +1,41 @@ +package org.smartregister.chw.presenter; + +import org.smartregister.chw.core.contract.BaseReferralRegisterFragmentContract; +import org.smartregister.chw.core.presenter.BaseReferralFragmentPresenter; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.model.LTFUReferralModel; +import org.smartregister.commonregistry.CommonPersonObjectClient; + +import java.util.HashSet; + +public class LTFUReferralFragmentPresenter extends BaseReferralFragmentPresenter { + protected BaseReferralRegisterFragmentContract.View view; + + public LTFUReferralFragmentPresenter(BaseReferralRegisterFragmentContract.View view) { + super(view); + this.model = new LTFUReferralModel(); + this.view = view; + } + + @Override + public void initializeQueries(String mainCondition) { + String countSelect = model.countSelect(CoreConstants.TABLE_NAME.TASK, mainCondition); + String mainSelect = model.mainSelect(CoreConstants.TABLE_NAME.TASK, CoreConstants.TABLE_NAME.FAMILY_MEMBER, mainCondition); + + view.initializeQueryParams(CoreConstants.TABLE_NAME.FAMILY_MEMBER, countSelect, mainSelect); + view.initializeAdapter(new HashSet<>(), CoreConstants.TABLE_NAME.TASK); + + view.countExecute(); + view.filterandSortInInitializeQueries(); + } + + @Override + public void fetchClient() { + interactor.getClientDetails(getBaseEntityId(), this, getTaskFocus()); + } + + @Override + public void clientDetails(CommonPersonObjectClient client) { + view.setClient(client); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LoginPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LoginPresenter.java index 59271b5fcc..1eda020160 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LoginPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/LoginPresenter.java @@ -4,14 +4,10 @@ import android.graphics.drawable.GradientDrawable; import android.view.View; import android.widget.CheckBox; -import android.widget.ImageView; import android.widget.TextView; -import com.android.volley.toolbox.ImageLoader; - import org.smartregister.chw.R; import org.smartregister.chw.application.ChwApplication; -import org.smartregister.chw.core.utils.ImageLoaderRequest; import org.smartregister.chw.interactor.LoginInteractor; import org.smartregister.configurableviews.model.LoginConfiguration; import org.smartregister.configurableviews.model.ViewConfiguration; @@ -26,8 +22,6 @@ public class LoginPresenter extends BaseLoginPresenter implements BaseLoginContract.Presenter { - private static final String TAG = LoginPresenter.class.getCanonicalName(); - public LoginPresenter(BaseLoginContract.View loginView) { mLoginView = new WeakReference<>(loginView); mLoginInteractor = new LoginInteractor(this); @@ -67,13 +61,6 @@ public void processViewCustomizations() { loginLayout.setBackground(gradientDrawable); } - ImageView imageView = getLoginView().getActivityContext().findViewById(R.id.login_logo); - if (metadata.getLogoUrl() != null) { - ImageLoaderRequest.getInstance(getLoginView().getActivityContext()).getImageLoader() - .get(metadata.getLogoUrl(), ImageLoader.getImageListener(imageView, - R.drawable.ic_who_logo, R.drawable.ic_who_logo)).getBitmap(); - } - } catch (Exception e) { Timber.e(e); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MalariaRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MalariaRegisterFragmentPresenter.java index 58dae574a3..2456eb44be 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MalariaRegisterFragmentPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MalariaRegisterFragmentPresenter.java @@ -10,4 +10,8 @@ public MalariaRegisterFragmentPresenter(MalariaRegisterFragmentContract.View vie super(view, model, viewConfigurationIdentifier); } + public String getMainCondition() { + return " ec_family_member.date_removed is null AND datetime('NOW') <= datetime(ec_malaria_confirmation.last_interacted_with/1000, 'unixepoch', 'localtime','+15 days') AND ec_malaria_confirmation.is_closed = 0"; + } + } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MotherChampionRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MotherChampionRegisterFragmentPresenter.java new file mode 100644 index 0000000000..2832995e23 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/MotherChampionRegisterFragmentPresenter.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.presenter; + +import org.smartregister.chw.pmtct.contract.PmtctRegisterFragmentContract; +import org.smartregister.chw.pmtct.presenter.BasePmtctRegisterFragmentPresenter; + +import static org.smartregister.chw.core.utils.CoreConstants.TABLE_NAME; + +public class MotherChampionRegisterFragmentPresenter extends BasePmtctRegisterFragmentPresenter { + public MotherChampionRegisterFragmentPresenter(PmtctRegisterFragmentContract.View view, PmtctRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + public String getMainCondition() { + return " ec_family_member.date_removed is null "; + } + + @Override + public String getMainTable() { + return TABLE_NAME.MOTHER_CHAMPION; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/OrdersRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/OrdersRegisterFragmentPresenter.java new file mode 100644 index 0000000000..abc67ece5f --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/OrdersRegisterFragmentPresenter.java @@ -0,0 +1,17 @@ +package org.smartregister.chw.presenter; + +import org.smartregister.chw.cdp.contract.BaseOrdersRegisterFragmentContract; +import org.smartregister.chw.cdp.presenter.BaseOrdersRegisterFragmentPresenter; +import org.smartregister.chw.cdp.util.Constants; +import org.smartregister.chw.cdp.util.DBConstants; + +public class OrdersRegisterFragmentPresenter extends BaseOrdersRegisterFragmentPresenter { + public OrdersRegisterFragmentPresenter(BaseOrdersRegisterFragmentContract.View view, BaseOrdersRegisterFragmentContract.Model model) { + super(view, model); + } + + @Override + public String getMainCondition() { + return super.getMainCondition() + " AND " + getMainTable() + "." + DBConstants.KEY.REQUEST_TYPE + " = '" + Constants.ORDER_TYPES.COMMUNITY_TO_FACILITY_ORDER + "' "; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctFollowupRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctFollowupRegisterFragmentPresenter.java new file mode 100644 index 0000000000..febf2ada1c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctFollowupRegisterFragmentPresenter.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.presenter; + +import static org.smartregister.chw.core.utils.CoreConstants.TABLE_NAME; + +import org.smartregister.chw.pmtct.contract.PmtctRegisterFragmentContract; +import org.smartregister.chw.pmtct.presenter.BasePmtctRegisterFragmentPresenter; + +public class PmtctFollowupRegisterFragmentPresenter extends BasePmtctRegisterFragmentPresenter { + public PmtctFollowupRegisterFragmentPresenter(PmtctRegisterFragmentContract.View view, PmtctRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + public String getMainCondition() { + return " ec_family_member.date_removed is null AND ec_pmtct_community_followup.base_entity_id NOT IN (SELECT community_referral_form_id FROM ec_pmtct_community_feedback)"; + } + + @Override + public String getMainTable() { + return TABLE_NAME.PMTCT_COMMUNITY_FOLLOWUP; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctMemberProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctMemberProfilePresenter.java new file mode 100644 index 0000000000..dd62d54412 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PmtctMemberProfilePresenter.java @@ -0,0 +1,23 @@ +package org.smartregister.chw.presenter; + +import android.app.Activity; + +import org.smartregister.chw.activity.MotherChampionProfileActivity; +import org.smartregister.chw.core.contract.CorePmtctProfileContract; +import org.smartregister.chw.core.presenter.CorePmtctMemberProfilePresenter; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.pmtct.domain.MemberObject; +import org.smartregister.chw.util.Utils; + +import java.util.List; + +public class PmtctMemberProfilePresenter extends CorePmtctMemberProfilePresenter { + public PmtctMemberProfilePresenter(CorePmtctProfileContract.View view, CorePmtctProfileContract.Interactor interactor, MemberObject memberObject) { + super(view, interactor, memberObject); + } + + public void referToFacility() { + List referralTypeModels = ((MotherChampionProfileActivity) getView()).getReferralTypeModels(); + Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, memberObject.getBaseEntityId()); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PncMemberProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PncMemberProfilePresenter.java index 9ee178ea35..a3e6ba1305 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PncMemberProfilePresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/PncMemberProfilePresenter.java @@ -81,11 +81,9 @@ public void startPncReferralForm() { @Override public void referToFacility() { List referralTypeModels = getView().getReferralTypeModels(); - if (referralTypeModels.size() == 1) { - startPncReferralForm(); - } else { - org.smartregister.chw.util.Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, getEntityId()); - } + + org.smartregister.chw.util.Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, getEntityId()); + } @Override diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ReferralRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ReferralRegisterFragmentPresenter.java index 6f572e630f..080b55b59d 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ReferralRegisterFragmentPresenter.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/ReferralRegisterFragmentPresenter.java @@ -22,7 +22,9 @@ public ReferralRegisterFragmentPresenter(BaseReferralRegisterFragmentContract.Vi @NotNull public String getMainCondition() { return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + - "AND " + Tables.REFERRAL + "." + DBConstants.Key.REFERRAL_TYPE + " = '" + ReferralType.COMMUNITY_TO_FACILITY_REFERRAL + "' "; + "AND " + Tables.REFERRAL + "." + DBConstants.Key.REFERRAL_TYPE + " = '" + ReferralType.COMMUNITY_TO_FACILITY_REFERRAL + "' " + + "AND " + CoreConstants.TABLE_NAME.TASK + "." + ChwDBConstants.TaskTable.BUSINESS_STATUS + " <> '" + CoreConstants.BUSINESS_STATUS.CANCELLED + "' " + + "AND " + CoreConstants.TABLE_NAME.TASK + "." + ChwDBConstants.TaskTable.BUSINESS_STATUS + " <> '" + CoreConstants.BUSINESS_STATUS.COMPLETE + "' "; } @@ -30,7 +32,7 @@ public String getMainCondition() { @NotNull public String getDueFilterCondition() { return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + - "AND " + Constants.TABLE_NAME.TASK + "." + ChwDBConstants.TaskTable.BUSINESS_STATUS + " = '" + CoreConstants.BUSINESS_STATUS.REFERRED + "' " + + "AND " + Constants.TABLE_NAME.TASK + "." + ChwDBConstants.TaskTable.BUSINESS_STATUS + " = '" + CoreConstants.BUSINESS_STATUS.EXPIRED + "' " + "AND " + Tables.REFERRAL + "." + DBConstants.Key.REFERRAL_TYPE + " = '" + ReferralType.COMMUNITY_TO_FACILITY_REFERRAL + "' "; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/SbccRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/SbccRegisterFragmentPresenter.java new file mode 100644 index 0000000000..4eb9688113 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/SbccRegisterFragmentPresenter.java @@ -0,0 +1,21 @@ +package org.smartregister.chw.presenter; + +import org.smartregister.chw.pmtct.contract.PmtctRegisterFragmentContract; +import org.smartregister.chw.pmtct.presenter.BasePmtctRegisterFragmentPresenter; +import org.smartregister.chw.util.Constants; + +public class SbccRegisterFragmentPresenter extends BasePmtctRegisterFragmentPresenter { + public SbccRegisterFragmentPresenter(PmtctRegisterFragmentContract.View view, PmtctRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + public String getMainTable() { + return Constants.TableName.SBCC; + } + + @Override + public String getMainCondition() { + return Constants.TableName.SBCC + "." + "is_closed is 0"; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbCommunityFollowupFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbCommunityFollowupFragmentPresenter.java new file mode 100644 index 0000000000..60bd7120bc --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbCommunityFollowupFragmentPresenter.java @@ -0,0 +1,46 @@ +package org.smartregister.chw.presenter; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.tb.contract.BaseTbRegisterFragmentContract; +import org.smartregister.chw.tb.presenter.BaseTbCommunityFollowupPresenter; +import org.smartregister.chw.tb.util.Constants.Tables; +import org.smartregister.chw.tb.util.DBConstants; +import org.smartregister.chw.util.Constants; + +public class TbCommunityFollowupFragmentPresenter extends BaseTbCommunityFollowupPresenter { + + public TbCommunityFollowupFragmentPresenter(BaseTbRegisterFragmentContract.View view, BaseTbRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + @NotNull + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + + "AND " + Tables.TB_COMMUNITY_FOLLOWUP + "." + DBConstants.Key.IS_CLOSED + " = '0' " + + "AND " + Tables.TB_COMMUNITY_FOLLOWUP + "." + DBConstants.Key.BASE_ENTITY_ID + " NOT IN (SELECT " + DBConstants.Key.COMMUNITY_REFERRAL_FORM_ID + " FROM " + Tables.TB_COMMUNITY_FEEDBACK + " ) "; + + } + + @Override + @NotNull + public String getDueFilterCondition() { + return CoreConstants.TABLE_NAME.TB_MEMBER + ".base_entity_id in (select base_entity_id from schedule_service where strftime('%Y-%m-%d') BETWEEN due_date and expiry_date and schedule_name = '" + CoreConstants.SCHEDULE_TYPES.TB_VISIT + "' and ifnull(not_done_date,'') = '' and ifnull(completion_date,'') = '' ) "; + + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @Override + public String getMainTable() { + return Tables.TB_COMMUNITY_FOLLOWUP; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbProfilePresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbProfilePresenter.java new file mode 100644 index 0000000000..f3d627fb1c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbProfilePresenter.java @@ -0,0 +1,30 @@ +package org.smartregister.chw.presenter; + +import android.app.Activity; + +import org.smartregister.chw.activity.TbProfileActivity; +import org.smartregister.chw.contract.TbProfileContract; +import org.smartregister.chw.core.presenter.CoreTbProfilePresenter; +import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.chw.tb.domain.TbMemberObject; +import org.smartregister.chw.util.Utils; + +import java.util.List; + +public class TbProfilePresenter extends CoreTbProfilePresenter + implements org.smartregister.chw.contract.AncMemberProfileContract.Presenter { + + private TbMemberObject tbMemberObject; + + public TbProfilePresenter(TbProfileContract.View view, TbProfileContract.Interactor interactor, + TbMemberObject tbMemberObject) { + super(view, interactor, tbMemberObject); + this.tbMemberObject = tbMemberObject; + } + + @Override + public void referToFacility() { + List referralTypeModels = ((TbProfileActivity) getView()).getReferralTypeModels(); + Utils.launchClientReferralActivity((Activity) getView(), referralTypeModels, tbMemberObject.getBaseEntityId()); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbRegisterFragmentPresenter.java b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbRegisterFragmentPresenter.java new file mode 100644 index 0000000000..819183c7b5 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/presenter/TbRegisterFragmentPresenter.java @@ -0,0 +1,47 @@ +package org.smartregister.chw.presenter; + +import org.jetbrains.annotations.NotNull; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.tb.contract.BaseTbRegisterFragmentContract; +import org.smartregister.chw.tb.presenter.BaseTbRegisterFragmentPresenter; +import org.smartregister.chw.tb.util.Constants.Tables; +import org.smartregister.chw.tb.util.DBConstants; +import org.smartregister.chw.util.Constants; + +public class TbRegisterFragmentPresenter extends BaseTbRegisterFragmentPresenter { + + public TbRegisterFragmentPresenter(BaseTbRegisterFragmentContract.View view, BaseTbRegisterFragmentContract.Model model, String viewConfigurationIdentifier) { + super(view, model, viewConfigurationIdentifier); + } + + @Override + @NotNull + public String getMainCondition() { + return " " + Constants.TABLE_NAME.FAMILY_MEMBER + "." + DBConstants.Key.DATE_REMOVED + " is null " + + "AND " + Tables.TB + "." + DBConstants.Key.TB_CASE_CLOSURE_DATE + " is null " + + "AND (" + Tables.TB + "." + DBConstants.Key.CLIENT_TB_STATUS_AFTER_TESTING + " = 'Positive' OR " + Tables.TB + "." + DBConstants.Key.CLIENT_TB_STATUS_AFTER_TESTING + " IS NULL ) "+ + "AND " + Tables.TB + "." + DBConstants.Key.IS_CLOSED + " = '0' "; + + } + + @Override + @NotNull + public String getDueFilterCondition() { + return CoreConstants.TABLE_NAME.TB_MEMBER + ".base_entity_id in (select base_entity_id from schedule_service where strftime('%Y-%m-%d') BETWEEN due_date and expiry_date and schedule_name = '" + CoreConstants.SCHEDULE_TYPES.TB_VISIT + "' and ifnull(not_done_date,'') = '' and ifnull(completion_date,'') = '' ) "; + + } + + @Override + public void processViewConfigurations() { + super.processViewConfigurations(); + if (getConfig().getSearchBarText() != null && getView() != null) { + getView().updateSearchBarHint(getView().getContext().getString(R.string.search_name_or_id)); + } + } + + @Override + public String getMainTable() { + return Tables.TB; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/AncFollowupRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/AncFollowupRegisterProvider.java new file mode 100644 index 0000000000..192231aa9b --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/AncFollowupRegisterProvider.java @@ -0,0 +1,26 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; + +import org.smartregister.chw.anc.provider.AncRegisterProvider; +import org.smartregister.chw.core.provider.ChwAncRegisterProvider; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.view.contract.SmartRegisterClient; + +import java.util.Set; + +public class AncFollowupRegisterProvider extends ChwAncRegisterProvider { + + + public AncFollowupRegisterProvider(Context context, CommonRepository commonRepository, Set visibleColumns, View.OnClickListener onClickListener, View.OnClickListener paginationClickListener) { + super(context, commonRepository, visibleColumns, onClickListener, paginationClickListener); + } + + @Override + public void getView(Cursor cursor, SmartRegisterClient client, AncRegisterProvider.RegisterViewHolder viewHolder) { + super.getView(cursor, client, viewHolder); + viewHolder.dueWrapper.setVisibility(View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllClientsRegisterQueryProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllClientsRegisterQueryProvider.java new file mode 100644 index 0000000000..abdd97b81d --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllClientsRegisterQueryProvider.java @@ -0,0 +1,14 @@ +package org.smartregister.chw.provider; + +import org.smartregister.chw.core.provider.CoreAllClientsRegisterQueryProvider; +import org.smartregister.chw.util.ChwQueryConstant; + +import androidx.annotation.NonNull; + +public class ChwAllClientsRegisterQueryProvider extends CoreAllClientsRegisterQueryProvider { + @NonNull + @Override + public String mainSelectWhereIDsIn() { + return ChwQueryConstant.ALL_CLIENTS_SELECT_QUERY; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllMaleClientsQueryProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllMaleClientsQueryProvider.java new file mode 100644 index 0000000000..645b6057f7 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwAllMaleClientsQueryProvider.java @@ -0,0 +1,14 @@ +package org.smartregister.chw.provider; + +import org.smartregister.chw.core.provider.CoreAllClientsRegisterQueryProvider; +import org.smartregister.chw.util.ChwQueryForMaleClients; + +import androidx.annotation.NonNull; + +public class ChwAllMaleClientsQueryProvider extends CoreAllClientsRegisterQueryProvider { + @NonNull + @Override + public String mainSelectWhereIDsIn() { + return ChwQueryForMaleClients.ALL_MALE_CLIENTS_SELECT_QUERY; + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwDueRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwDueRegisterProvider.java index 6293adf50c..f5689e3f6c 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwDueRegisterProvider.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwDueRegisterProvider.java @@ -108,6 +108,10 @@ private String getVisitType(String scheduleName) { return " · " + context.getString(R.string.family_kit); case CoreConstants.SCHEDULE_TYPES.ROUTINE_HOUSEHOLD_VISIT: return " · " + context.getString(R.string.routine_household_visit); + case CoreConstants.SCHEDULE_TYPES.HIV_VISIT: + return context.getString(R.string.routine_hiv_visit); + case CoreConstants.SCHEDULE_TYPES.TB_VISIT: + return context.getString(R.string.routine_tb_visit); default: return context.getString(R.string.home_visit_suffix); } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMaleClientRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMaleClientRegisterProvider.java new file mode 100644 index 0000000000..83c8abad3e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMaleClientRegisterProvider.java @@ -0,0 +1,90 @@ +package org.smartregister.chw.provider; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.Intent; +import android.view.View; + +import org.apache.commons.text.WordUtils; +import org.joda.time.DateTime; +import org.joda.time.Period; +import org.smartregister.chw.R; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.family.util.DBConstants; +import org.smartregister.family.util.Utils; +import org.smartregister.opd.OpdLibrary; +import org.smartregister.opd.configuration.OpdRegisterProviderMetadata; +import org.smartregister.opd.holders.OpdRegisterViewHolder; +import org.smartregister.opd.utils.ConfigurationInstancesHelper; + +import java.util.Map; + +import androidx.annotation.NonNull; + +import static org.smartregister.chw.util.Constants.PartnerRegistrationConstants.INTENT_BASE_ENTITY_ID; + +public class ChwMaleClientRegisterProvider extends OpdRegisterProvider { + private final Context context; + + private OpdRegisterProviderMetadata opdRegisterProviderMetadata; + + public ChwMaleClientRegisterProvider(@NonNull Context context, @NonNull View.OnClickListener onClickListener, @NonNull View.OnClickListener paginationClickListener) { + super(context, onClickListener, paginationClickListener); + this.context = context; + this.opdRegisterProviderMetadata = ConfigurationInstancesHelper + .newInstance(OpdLibrary.getInstance() + .getOpdConfiguration() + .getOpdRegisterProviderMetadata()); + } + + @Override + public void populatePatientColumn(CommonPersonObjectClient commonPersonObjectClient, OpdRegisterViewHolder viewHolder) { + int age_val = new Period(new DateTime(opdRegisterProviderMetadata.getDob(commonPersonObjectClient.getColumnmaps())), new DateTime()).getYears(); + + Map patientColumnMaps = commonPersonObjectClient.getColumnmaps(); + + viewHolder.hideRegisterType(); + viewHolder.removeCareGiverName(); + String firstName = opdRegisterProviderMetadata.getClientFirstName(patientColumnMaps); + String middleName = opdRegisterProviderMetadata.getClientMiddleName(patientColumnMaps); + String lastName = opdRegisterProviderMetadata.getClientLastName(patientColumnMaps); + String fullName = org.smartregister.util.Utils.getName(firstName, middleName + " " + lastName); + String baseEntityId = commonPersonObjectClient.entityId(); + String age = String.valueOf(age_val); + + fillValue(viewHolder.textViewChildName, WordUtils.capitalize(fullName) + ", " + + WordUtils.capitalize(age)); + setAddressAndGender(commonPersonObjectClient, viewHolder); + viewHolder.itemView.findViewById(R.id.go_to_profile_image_view).setVisibility(View.GONE); + viewHolder.itemView.setOnClickListener(v -> { + AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); + builder.setTitle(R.string.register_partner_dialog_title); + builder.setMessage(WordUtils.capitalize(fullName) + ", " + WordUtils.capitalize(age)); + builder.setCancelable(true); + builder.setPositiveButton(v.getContext().getString(R.string.yes), (dialog, id) -> { + Activity parentActivity = (Activity) context; + Intent intent = new Intent(); + intent.putExtra(INTENT_BASE_ENTITY_ID, baseEntityId); + parentActivity.setResult(Activity.RESULT_OK, intent); + parentActivity.finish(); + }); + builder.setNegativeButton(v.getContext().getString(R.string.cancel), ((dialog, id) -> dialog.cancel())); + + AlertDialog alertDialog = builder.create(); + alertDialog.show(); + }); + } + + + @Override + public void setAddressAndGender(CommonPersonObjectClient pc, OpdRegisterViewHolder viewHolder) { + super.setAddressAndGender(pc, viewHolder); + String gender_key = Utils.getValue(pc.getColumnmaps(), DBConstants.KEY.GENDER, true); + String gender = ""; + if (gender_key.equalsIgnoreCase("Male")) { + gender = context.getString(org.smartregister.chw.core.R.string.male); + } + fillValue(viewHolder.textViewGender, gender); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMemberRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMemberRegisterProvider.java index f5f7ff40e5..9ddbed7ea0 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMemberRegisterProvider.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwMemberRegisterProvider.java @@ -1,5 +1,7 @@ package org.smartregister.chw.provider; +import static org.smartregister.chw.core.utils.Utils.getDuration; + import android.content.Context; import android.database.Cursor; import android.graphics.Color; @@ -43,8 +45,6 @@ import timber.log.Timber; -import static org.smartregister.chw.core.utils.Utils.getDuration; - public class ChwMemberRegisterProvider extends FamilyMemberRegisterProvider { private Context context; private View.OnClickListener onClickListener; @@ -194,7 +194,8 @@ private void setMemberProfileAvatar(int imageResourceIdentifier, CommonPersonObj if (StringUtils.isNotBlank(dod)) { registerViewHolder.profile.setImageResource(imageResourceIdentifier); } else { - imageRenderHelper.refreshProfileImage(commonPersonObject.getCaseId(), registerViewHolder.profile, imageResourceIdentifier); +// imageRenderHelper.refreshProfileImage(commonPersonObject.getCaseId(), registerViewHolder.profile, imageResourceIdentifier); + registerViewHolder.profile.setImageResource(imageResourceIdentifier); } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwPncRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwPncRegisterProvider.java new file mode 100644 index 0000000000..b67d1ebf15 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/ChwPncRegisterProvider.java @@ -0,0 +1,20 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.view.View; + +import org.smartregister.chw.core.rule.PncVisitAlertRule; +import org.smartregister.commonregistry.CommonRepository; + +import java.util.Set; + +public class ChwPncRegisterProvider extends org.smartregister.chw.core.provider.ChwPncRegisterProvider { + public ChwPncRegisterProvider(Context context, CommonRepository commonRepository, Set visibleColumns, View.OnClickListener onClickListener, View.OnClickListener paginationClickListener) { + super(context, commonRepository, visibleColumns, onClickListener, paginationClickListener); + } + + @Override + protected void updateDueColumn(Context context, RegisterViewHolder viewHolder, PncVisitAlertRule pncVisitAlertRule) { + viewHolder.dueWrapper.setVisibility(View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/LTFURegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/LTFURegisterProvider.java new file mode 100644 index 0000000000..b4ce1c0a42 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/LTFURegisterProvider.java @@ -0,0 +1,58 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.view.View; +import android.widget.TextView; + +import org.smartregister.chw.R; +import org.smartregister.chw.core.holders.ReferralViewHolder; +import org.smartregister.chw.core.provider.BaseReferralRegisterProvider; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.domain.Location; +import org.smartregister.family.util.Utils; +import org.smartregister.repository.LocationRepository; + +public class LTFURegisterProvider extends BaseReferralRegisterProvider { + private final Context context; + + public LTFURegisterProvider(Context context, View.OnClickListener onClickListener, View.OnClickListener paginationClickListener) { + super(context, onClickListener, paginationClickListener); + this.context = context; + } + + @Override + public void populatePatientColumn(CommonPersonObjectClient pc, ReferralViewHolder viewHolder) { + super.populatePatientColumn(pc, viewHolder); + TextView referralClinic = viewHolder.itemView.findViewById(R.id.referral_clinic); + referralClinic.setText(getReferralClinic(Utils.getValue(pc.getColumnmaps(), "REFERRAL_CLINIC", true))); + + TextView referredByTextView = viewHolder.itemView.findViewById(org.smartregister.chw.core.R.id.referred_by); + LocationRepository locationRepository = new LocationRepository(); + String locationId = Utils.getValue(pc.getColumnmaps(), org.smartregister.chw.referral.util.DBConstants.Key.REFERRAL_HF, false); + Location location = locationRepository.getLocationById(locationId); + if(location != null) { + referredByTextView.setText(context.getString(R.string.referred_by, location.getProperties().getName())); + }else{ + referredByTextView.setText(context.getString(R.string.referred_by, locationId)); + } + + } + + + private String getReferralClinic(String key){ + switch (key.toLowerCase()){ + case "ctc": + return context.getString(R.string.ltfu_clinic_ctc); + case "pwid": + return context.getString(R.string.ltfu_clinic_pwid); + case "prep": + return context.getString(R.string.ltfu_clinic_prep); + case "pmtct": + return context.getString(R.string.ltfu_clinic_pmtct); + case "tb": + return context.getString(R.string.ltfu_clinic_tb); + default: + return key.toUpperCase(); + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/MotherChampionRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/MotherChampionRegisterProvider.java new file mode 100644 index 0000000000..5edddddb6c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/MotherChampionRegisterProvider.java @@ -0,0 +1,22 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; + +import org.smartregister.provider.PmtctRegisterProvider; +import org.smartregister.view.contract.SmartRegisterClient; + +import java.util.Set; + +public class MotherChampionRegisterProvider extends PmtctRegisterProvider { + public MotherChampionRegisterProvider(Context context, View.OnClickListener paginationClickListener, View.OnClickListener onClickListener, Set visibleColumns) { + super(context, paginationClickListener, onClickListener, visibleColumns); + } + + @Override + public void getView(Cursor cursor, SmartRegisterClient smartRegisterClient, RegisterViewHolder registerViewHolder) { + super.getView(cursor, smartRegisterClient, registerViewHolder); + registerViewHolder.dueWrapper.setVisibility(View.GONE); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/OpdRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/OpdRegisterProvider.java new file mode 100644 index 0000000000..6f572f255d --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/OpdRegisterProvider.java @@ -0,0 +1,98 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.text.TextUtils; +import android.view.View; + +import androidx.annotation.NonNull; + +import org.apache.commons.text.WordUtils; +import org.joda.time.DateTime; +import org.joda.time.Period; +import org.smartregister.chw.R; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.family.util.DBConstants; +import org.smartregister.family.util.Utils; +import org.smartregister.opd.OpdLibrary; +import org.smartregister.opd.configuration.OpdRegisterProviderMetadata; +import org.smartregister.opd.holders.OpdRegisterViewHolder; +import org.smartregister.opd.utils.ConfigurationInstancesHelper; +import org.smartregister.opd.utils.OpdDbConstants; + +import java.util.Map; + +import timber.log.Timber; + +public class OpdRegisterProvider extends org.smartregister.opd.provider.OpdRegisterProvider { + private final Context context; + + private OpdRegisterProviderMetadata opdRegisterProviderMetadata; + + public OpdRegisterProvider(@NonNull Context context, @NonNull View.OnClickListener onClickListener, @NonNull View.OnClickListener paginationClickListener) { + super(context, onClickListener, paginationClickListener); + this.context = context; + this.opdRegisterProviderMetadata = ConfigurationInstancesHelper + .newInstance(OpdLibrary.getInstance() + .getOpdConfiguration() + .getOpdRegisterProviderMetadata()); + } + + @Override + public void populatePatientColumn(CommonPersonObjectClient commonPersonObjectClient, OpdRegisterViewHolder viewHolder) { + super.populatePatientColumn(commonPersonObjectClient, viewHolder); + Map patientColumnMaps = commonPersonObjectClient.getColumnmaps(); + String registerType = org.smartregister.util.Utils.getValue(commonPersonObjectClient.getColumnmaps(), + OpdDbConstants.KEY.REGISTER_TYPE, true); + + if (!TextUtils.isEmpty(registerType)) { + viewHolder.showRegisterType(); + String type = getTranslatedRegisterType(registerType); + fillValue(viewHolder.tvRegisterType, type); + } else { + viewHolder.hideRegisterType(); + } + String firstName = opdRegisterProviderMetadata.getClientFirstName(patientColumnMaps); + String middleName = opdRegisterProviderMetadata.getClientMiddleName(patientColumnMaps); + String lastName = opdRegisterProviderMetadata.getClientLastName(patientColumnMaps); + String fullName = org.smartregister.util.Utils.getName(firstName, middleName + " " + lastName); + + try { + String age = String.valueOf(new Period(new DateTime(opdRegisterProviderMetadata.getDob(patientColumnMaps)), new DateTime()).getYears()); + fillValue(viewHolder.textViewChildName, WordUtils.capitalize(fullName) + ", " + + WordUtils.capitalize(age)); + } catch (Exception e) { + Timber.e(e); + } + } + + private String getTranslatedRegisterType(String registerType) { + if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.CHILD)) { + return context.getString(R.string.menu_child); + } else if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.ANC)) { + return context.getString(R.string.menu_anc); + } else if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.PNC)) { + return context.getString(R.string.menu_pnc); + } else if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.FAMILY_PLANNING)) { + return context.getString(R.string.menu_family_planning); + } else if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.MALARIA)) { + return context.getString(R.string.menu_malaria); + } else if (registerType.equalsIgnoreCase(CoreConstants.REGISTER_TYPE.INDEPENDENT)) { + return context.getString(R.string.menu_independent); + } + return registerType; + } + + @Override + public void setAddressAndGender(CommonPersonObjectClient pc, OpdRegisterViewHolder viewHolder) { + super.setAddressAndGender(pc, viewHolder); + String gender_key = Utils.getValue(pc.getColumnmaps(), DBConstants.KEY.GENDER, true); + String gender = ""; + if (gender_key.equalsIgnoreCase("Male")) { + gender = context.getString(org.smartregister.chw.core.R.string.male); + } else if (gender_key.equalsIgnoreCase("Female")) { + gender = context.getString(org.smartregister.chw.core.R.string.female); + } + fillValue(viewHolder.textViewGender, gender); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/provider/SbccRegisterProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/provider/SbccRegisterProvider.java new file mode 100644 index 0000000000..77a4471d70 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/provider/SbccRegisterProvider.java @@ -0,0 +1,49 @@ +package org.smartregister.chw.provider; + +import android.content.Context; +import android.database.Cursor; +import android.view.View; + +import org.smartregister.chw.util.Constants; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.provider.HvlResultsViewProvider; +import org.smartregister.util.Utils; +import org.smartregister.view.contract.SmartRegisterClient; + +import java.util.Set; + +import timber.log.Timber; + +public class SbccRegisterProvider extends HvlResultsViewProvider { + private Set visibleColumns; + + public SbccRegisterProvider(Context context, View.OnClickListener paginationClickListener, View.OnClickListener onClickListener, java.util.Set visibleColumns) { + super(context, paginationClickListener, onClickListener, visibleColumns); + this.visibleColumns = visibleColumns; + } + + public void getView(Cursor cursor, SmartRegisterClient smartRegisterClient, RegisterViewHolder registerViewHolder) { ; + if (visibleColumns.isEmpty()) { + populatePatientColumn(registerViewHolder); + } + } + + private void populatePatientColumn(final RegisterViewHolder viewHolder) { + try { + +// String sampleId = Utils.getValue(pc.getColumnmaps(), Constants.DBConstants.SBCC_DATE, false); +// String collectionDate = Utils.getValue(pc.getColumnmaps(), Constants.DBConstants.SBCC_DATE, false); + + + + viewHolder.hvlWrapper.setVisibility(View.GONE); + viewHolder.dueWrapper.setVisibility(View.VISIBLE); + + // viewHolder.sampleId.setText(sampleId); + // viewHolder.collectionDate.setText(collectionDate); + + } catch (Exception e) { + Timber.e(e); + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/repository/ChwRepository.java b/opensrp-chw/src/main/java/org/smartregister/chw/repository/ChwRepository.java index 063a0d9a01..d9e9a7bcf9 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/repository/ChwRepository.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/repository/ChwRepository.java @@ -8,21 +8,74 @@ import org.smartregister.chw.BuildConfig; import org.smartregister.chw.core.application.CoreChwApplication; import org.smartregister.chw.core.repository.CoreChwRepository; +import org.smartregister.reporting.ReportingLibrary; + +import java.util.Arrays; +import java.util.Collections; import timber.log.Timber; public class ChwRepository extends CoreChwRepository { private Context context; + private static String appVersionCodePref = "APP_VERSION_CODE"; public ChwRepository(Context context, org.smartregister.Context openSRPContext) { super(context, AllConstants.DATABASE_NAME, BuildConfig.DATABASE_VERSION, openSRPContext.session(), CoreChwApplication.createCommonFtsObject(), openSRPContext.sharedRepositoriesArray()); this.context = context; } + private static boolean checkIfAppUpdated() { + String savedAppVersion = ReportingLibrary.getInstance().getContext().allSharedPreferences().getPreference(appVersionCodePref); + if (savedAppVersion.isEmpty()) { + return true; + } else { + int savedVersion = Integer.parseInt(savedAppVersion); + return (org.smartregister.chw.core.BuildConfig.VERSION_CODE > savedVersion); + } + } + @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - Timber.w(CoreChwRepository.class.getName(), "Upgrading database from version " - + oldVersion + " to " + newVersion + ", which will destroy all old data"); + Timber.w(ChwRepository.class.getName(), + "Upgrading database from version " + oldVersion + " to " + + newVersion + ", which will destroy all old data"); + int upgradeTo = oldVersion + 1; + while (upgradeTo <= newVersion) { + switch (upgradeTo) { + case 2: + upgradeToVersion2(db); + break; + default: + break; + } + upgradeTo++; + } ChwRepositoryFlv.onUpgrade(context, db, oldVersion, newVersion); } + + private static void upgradeToVersion2(SQLiteDatabase db) { + try { + ReportingLibrary reportingLibraryInstance = ReportingLibrary.getInstance(); + String indicatorDataInitialisedPref = "INDICATOR_DATA_INITIALISED"; + + boolean indicatorDataInitialised = Boolean.parseBoolean(reportingLibraryInstance.getContext().allSharedPreferences().getPreference(indicatorDataInitialisedPref)); + boolean isUpdated = checkIfAppUpdated(); + if (!indicatorDataInitialised || isUpdated) { + + String indicatorsConfigFile = "config/indicator-definitions.yml"; + String agywindicatorConfigFile = "config/agyw-monthly-report.yml"; + + for (String configFile : Collections.unmodifiableList( + Arrays.asList(indicatorsConfigFile,agywindicatorConfigFile))) { + reportingLibraryInstance.readConfigFile(configFile, db); + } + + reportingLibraryInstance.initIndicatorData(indicatorsConfigFile, db); // This will persist the data in the DB + reportingLibraryInstance.getContext().allSharedPreferences().savePreference(indicatorDataInitialisedPref, "true"); + reportingLibraryInstance.getContext().allSharedPreferences().savePreference(appVersionCodePref, String.valueOf(org.smartregister.chw.core.BuildConfig.VERSION_CODE)); + } + } catch (Exception e) { + Timber.e(e); + } + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/rule/CbhsFollowupRule.java b/opensrp-chw/src/main/java/org/smartregister/chw/rule/CbhsFollowupRule.java new file mode 100644 index 0000000000..046665e106 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/rule/CbhsFollowupRule.java @@ -0,0 +1,94 @@ +package org.smartregister.chw.rule; + +import org.joda.time.DateTime; +import org.joda.time.Days; +import org.joda.time.LocalDate; +import org.smartregister.chw.core.rule.HivFollowupRule; +import org.smartregister.chw.core.utils.CoreConstants; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +public class CbhsFollowupRule extends HivFollowupRule { + public static final String RULE_KEY = "hivFollowupRule"; + private String visitID; + private DateTime hivDate; + private DateTime dueDate; + private DateTime overDueDate; + private DateTime nextVisitDate; + private DateTime expiryDate; + private int daysDifference; + + public CbhsFollowupRule(Date hivDate, Date nextVisitDate) { + super(hivDate, nextVisitDate); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + this.hivDate = hivDate != null ? new DateTime(sdf.format(hivDate)) : null; + this.nextVisitDate = nextVisitDate == null ? null : new DateTime(nextVisitDate); + isValid(); + } + + public String getVisitID() { + return visitID; + } + + public void setVisitID(String visitID) { + this.visitID = visitID; + } + + public int getDaysDifference() { + return daysDifference; + } + + public boolean isValid() { + if (nextVisitDate != null) { + this.dueDate = nextVisitDate.plusDays(0); + this.overDueDate = nextVisitDate.plusDays(28); + this.expiryDate = nextVisitDate.plusDays(365); + } else { + this.dueDate = hivDate.plusDays(28); + this.overDueDate = hivDate.plusDays(35); + this.expiryDate = hivDate.plusDays(365); + } + + daysDifference = Days.daysBetween(new DateTime(), new DateTime(dueDate)).getDays(); + return true; + } + + public Date getDueDate() { + return dueDate != null ? dueDate.toDate() : null; + } + + public Date getOverDueDate() { + return overDueDate != null ? overDueDate.toDate() : null; + } + + public Date getExpiryDate() { + return expiryDate != null ? expiryDate.toDate() : null; + } + + @Override + public String getRuleKey() { + return "hivFollowupRule"; + } + + @Override + public String getButtonStatus() { + DateTime currentDate = new DateTime(new LocalDate().toDate()); + DateTime lastVisit = nextVisitDate; + + if (currentDate.isBefore(expiryDate)) { + if ((currentDate.isAfter(overDueDate) || currentDate.isEqual(overDueDate))) + return CoreConstants.VISIT_STATE.OVERDUE; + if ((currentDate.isAfter(dueDate) || currentDate.isEqual(dueDate)) && currentDate.isBefore(overDueDate)) + return CoreConstants.VISIT_STATE.DUE; + if (lastVisit != null && currentDate.isEqual(lastVisit)) + return CoreConstants.VISIT_STATE.VISIT_DONE; + return CoreConstants.VISIT_STATE.NOT_DUE_YET; + + } + return CoreConstants.VISIT_STATE.EXPIRED; + } + + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/schedulers/ChwScheduleTaskExecutor.java b/opensrp-chw/src/main/java/org/smartregister/chw/schedulers/ChwScheduleTaskExecutor.java index a1336421e1..68c3926463 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/schedulers/ChwScheduleTaskExecutor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/schedulers/ChwScheduleTaskExecutor.java @@ -10,9 +10,11 @@ import org.smartregister.chw.task.ChildHomeVisitScheduler; import org.smartregister.chw.task.FamilyKitCheckScheduler; import org.smartregister.chw.task.FpVisitScheduler; +import org.smartregister.chw.task.HivVisitScheduler; import org.smartregister.chw.task.MalariaScheduler; import org.smartregister.chw.task.PNCVisitScheduler; import org.smartregister.chw.task.RoutineHouseHoldVisitScheduler; +import org.smartregister.chw.task.TbVisitScheduler; import org.smartregister.chw.task.WashCheckScheduler; import java.util.ArrayList; @@ -24,6 +26,10 @@ public class ChwScheduleTaskExecutor extends ScheduleTaskExecutor { private static ChwScheduleTaskExecutor scheduleTaskExecutor; + protected ChwScheduleTaskExecutor() { + //scheduleServiceMap.put(); + } + public static ChwScheduleTaskExecutor getInstance() { if (scheduleTaskExecutor == null) { scheduleTaskExecutor = new ChwScheduleTaskExecutor(); @@ -31,10 +37,6 @@ public static ChwScheduleTaskExecutor getInstance() { return scheduleTaskExecutor; } - protected ChwScheduleTaskExecutor() { - //scheduleServiceMap.put(); - } - @Override protected Map> getClassifier() { if (scheduleServiceMap == null || scheduleServiceMap.size() == 0) { @@ -59,6 +61,12 @@ protected Map> getClassifier() { if (ChwApplication.getApplicationFlavor().hasFamilyPlanning()) initializeFPClassifier(scheduleServiceMap); + if (ChwApplication.getApplicationFlavor().hasTB()) + initializeTBClassifier(scheduleServiceMap); + + if (ChwApplication.getApplicationFlavor().hasHIV()) + initializeHIVClassifier(scheduleServiceMap); + if (ChwApplication.getApplicationFlavor().hasRoutineVisit()) initializeRoutineHouseholdClassifier(scheduleServiceMap); @@ -140,6 +148,20 @@ private void initializeFPClassifier(Map> classifie addToClassifers(FamilyPlanningConstants.EventType.FAMILY_PLANNING_CHANGE_METHOD, classifier, scheduleServices); } + private void initializeHIVClassifier(Map> classifier) { + List scheduleServices = new ArrayList<>(); + scheduleServices.add(new HivVisitScheduler()); + addToClassifers(org.smartregister.chw.hiv.util.Constants.EventType.FOLLOW_UP_VISIT, classifier, scheduleServices); + addToClassifers(org.smartregister.chw.hiv.util.Constants.EventType.REGISTRATION, classifier, scheduleServices); + } + + private void initializeTBClassifier(Map> classifier) { + List scheduleServices = new ArrayList<>(); + scheduleServices.add(new TbVisitScheduler()); + addToClassifers(org.smartregister.chw.tb.util.Constants.EventType.FOLLOW_UP_VISIT, classifier, scheduleServices); + addToClassifers(org.smartregister.chw.tb.util.Constants.EventType.REGISTRATION, classifier, scheduleServices); + } + private void initializeRoutineHouseholdClassifier(Map> classifier) { List scheduleServices = new ArrayList<>(); scheduleServices.add(new RoutineHouseHoldVisitScheduler()); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/service/SchedulesIntentService.java b/opensrp-chw/src/main/java/org/smartregister/chw/service/SchedulesIntentService.java index ff6d84eef5..2f511bd155 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/service/SchedulesIntentService.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/service/SchedulesIntentService.java @@ -10,6 +10,7 @@ import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.dao.ScheduleDao; import org.smartregister.chw.fp.util.FamilyPlanningConstants; +import org.smartregister.chw.hiv.util.Constants; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; import org.smartregister.receiver.SyncStatusBroadcastReceiver; @@ -65,6 +66,14 @@ protected void onHandleIntent(@Nullable Intent intent) { if (ChwApplication.getApplicationFlavor().hasFamilyPlanning()) executeFpVisitSchedules(); + // execute all tb schedules + if (ChwApplication.getApplicationFlavor().hasTB()) + executeTbVisitSchedules(); + + // execute all hiv schedules + if (ChwApplication.getApplicationFlavor().hasHIV()) + executeHivVisitSchedules(); + if (ChwApplication.getApplicationFlavor().hasRoutineVisit()) executeRoutineHouseholdSchedules(); } @@ -142,6 +151,28 @@ private void executeFpVisitSchedules() { ChwScheduleTaskExecutor.getInstance().execute(baseID, FamilyPlanningConstants.EventType.FAMILY_PLANNING_REGISTRATION, new Date()); } } + private void executeHivVisitSchedules() { + Timber.v("Computing Hiv schedules"); + ChwApplication.getInstance().getScheduleRepository().deleteSchedulesNotCreatedToday(CoreConstants.SCHEDULE_TYPES.HIV_VISIT, CoreConstants.SCHEDULE_GROUPS.HOME_VISIT); + List baseEntityIDs = ScheduleDao.getActiveHivClients(CoreConstants.SCHEDULE_TYPES.HIV_VISIT, CoreConstants.SCHEDULE_GROUPS.HOME_VISIT); + if (baseEntityIDs == null) return; + + for (String baseID : baseEntityIDs) { + Timber.v(" Computing HIV schedules for %s", baseID); + ChwScheduleTaskExecutor.getInstance().execute(baseID, Constants.EventType.REGISTRATION, new Date()); + } + } + private void executeTbVisitSchedules() { + Timber.v("Computing Tb schedules"); + ChwApplication.getInstance().getScheduleRepository().deleteSchedulesNotCreatedToday(CoreConstants.SCHEDULE_TYPES.TB_VISIT, CoreConstants.SCHEDULE_GROUPS.HOME_VISIT); + List baseEntityIDs = ScheduleDao.getActiveTbClients(CoreConstants.SCHEDULE_TYPES.TB_VISIT, CoreConstants.SCHEDULE_GROUPS.HOME_VISIT); + if (baseEntityIDs == null) return; + + for (String baseID : baseEntityIDs) { + Timber.v(" Computing Tb schedules for %s", baseID); + ChwScheduleTaskExecutor.getInstance().execute(baseID, org.smartregister.chw.tb.util.Constants.EventType.REGISTRATION, new Date()); + } + } private void executeRoutineHouseholdSchedules() { Timber.v("Computing Routine household schedules"); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/sync/ChwClientProcessor.java b/opensrp-chw/src/main/java/org/smartregister/chw/sync/ChwClientProcessor.java index fd0fdc39ec..0a2bf1e0f5 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/sync/ChwClientProcessor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/sync/ChwClientProcessor.java @@ -3,19 +3,28 @@ import android.content.Context; +import org.apache.commons.lang3.StringUtils; import org.smartregister.CoreLibrary; +import org.smartregister.chw.anc.util.NCUtils; import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.core.sync.CoreClientProcessor; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.schedulers.ChwScheduleTaskExecutor; import org.smartregister.chw.service.ChildAlertService; +import org.smartregister.chw.util.Constants; import org.smartregister.domain.Event; +import org.smartregister.domain.Obs; import org.smartregister.domain.db.EventClient; import org.smartregister.domain.jsonmapping.ClientClassification; import org.smartregister.domain.jsonmapping.Table; import org.smartregister.receiver.SyncStatusBroadcastReceiver; import org.smartregister.sync.ClientProcessorForJava; +import java.util.ArrayList; +import java.util.List; + +import timber.log.Timber; + public class ChwClientProcessor extends CoreClientProcessor { private ChwClientProcessor(Context context) { @@ -60,6 +69,21 @@ public void processEvents(ClientClassification clientClassification, Table vacci if (!CoreLibrary.getInstance().isPeerToPeerProcessing() && !SyncStatusBroadcastReceiver.getInstance().isSyncing()) { ChildAlertService.updateAlerts(baseEntityID); } + break; + case Constants.Events.CBHS_FOLLOWUP: + case Constants.Events.MOTHER_CHAMPION_FOLLOWUP: + case Constants.Events.ANC_FIRST_FACILITY_VISIT: + case Constants.Events.ANC_RECURRING_FACILITY_VISIT: + case Constants.Events.AGYW_STRUCTURAL_SERVICES: + case Constants.Events.AGYW_BEHAVIORAL_SERVICES: + case Constants.Events.AGYW_BIO_MEDICAL_SERVICES: + case Constants.Events.KVP_PREP_FOLLOWUP_VISIT: + if (eventClient.getEvent() == null) { + return; + } + processVisitEvent(eventClient); + processEvent(eventClient.getEvent(), eventClient.getClient(), clientClassification); + break; default: break; } @@ -69,4 +93,40 @@ public void processEvents(ClientClassification clientClassification, Table vacci ChwScheduleTaskExecutor.getInstance().execute(event.getBaseEntityId(), event.getEventType(), event.getEventDate().toDate()); } } + + private void processVisitEvent(EventClient eventClient) { + try { + NCUtils.processHomeVisit(eventClient); + } catch (Exception e) { + String formID = (eventClient != null && eventClient.getEvent() != null) ? eventClient.getEvent().getFormSubmissionId() : "no form id"; + Timber.e("Form id " + formID + ". " + e.toString()); + } + } + + + @Override + protected String getHumanReadableConceptResponse(String value, Object object) { + try { + if (StringUtils.isBlank(value) || (object != null && !(object instanceof Obs))) { + return value; + } + // Skip human readable values and just get values which would aid in translations + final String VALUES = "values"; + List values = new ArrayList(); + + Object valueObject = getValue(object, VALUES); + if (valueObject instanceof List) { + values = (List) valueObject; + } + if (object == null || values.isEmpty()) { + return value; + } + + return values.size() == 1 ? values.get(0).toString() : values.toString(); + + } catch (Exception e) { + Timber.e(e); + } + return value; + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/sync/helper/ChwTaskServiceHelper.java b/opensrp-chw/src/main/java/org/smartregister/chw/sync/helper/ChwTaskServiceHelper.java index d617c18b5f..6eaabb1e8e 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/sync/helper/ChwTaskServiceHelper.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/sync/helper/ChwTaskServiceHelper.java @@ -1,7 +1,6 @@ package org.smartregister.chw.sync.helper; import org.smartregister.CoreLibrary; -import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.domain.Task; import org.smartregister.location.helper.LocationHelper; @@ -18,7 +17,6 @@ public class ChwTaskServiceHelper extends TaskServiceHelper { private ChwTaskServiceHelper(TaskRepository taskRepository) { super(taskRepository); - setSyncByGroupIdentifier(false); } public static ChwTaskServiceHelper getInstance() { @@ -31,13 +29,11 @@ public static ChwTaskServiceHelper getInstance() { @Override protected List getLocationIds() { LocationHelper locationHelper = LocationHelper.getInstance(); - ArrayList allowedLevels = ChwApplication.getInstance().getAllowedLocationLevels(); - List locations = new ArrayList<>(); - if (allowedLevels != null) { - List locationIds = locationHelper.generateDefaultLocationHierarchy(allowedLevels); - if (locationIds != null) { - locations.add(locationHelper.getOpenMrsLocationId(locationIds.get(0))); - } + ArrayList locations = new ArrayList<>(); + if (locationHelper != null) { + String defaultLocation = locationHelper.getDefaultLocation(); + List locationsFromHierarchy = locationHelper.locationsFromHierarchy(true, defaultLocation); + locations.addAll(locationsFromHierarchy); } return locations; } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/ChwSyncTaskIntentService.java b/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/ChwSyncTaskIntentService.java index 9bd9f7041b..fff22331e7 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/ChwSyncTaskIntentService.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/ChwSyncTaskIntentService.java @@ -2,6 +2,7 @@ import android.content.Intent; +import org.smartregister.chw.core.job.SyncTaskWithClientEventsServiceJob; import org.smartregister.chw.core.utils.CoreReferralUtils; import org.smartregister.chw.sync.helper.ChwTaskServiceHelper; import org.smartregister.sync.intent.SyncTaskIntentService; @@ -12,5 +13,6 @@ protected void onHandleIntent(Intent intent) { ChwTaskServiceHelper taskServiceHelper = ChwTaskServiceHelper.getInstance(); taskServiceHelper.syncTasks(); CoreReferralUtils.completeClosedReferralTasks(); + SyncTaskWithClientEventsServiceJob.scheduleJobImmediately(SyncTaskWithClientEventsServiceJob.TAG); } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/PncCloseDateIntentService.java b/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/PncCloseDateIntentService.java new file mode 100644 index 0000000000..e49591f590 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/sync/intent/PncCloseDateIntentService.java @@ -0,0 +1,31 @@ +package org.smartregister.chw.sync.intent; + +import android.app.IntentService; +import android.content.Intent; + +import org.smartregister.chw.activity.PncMemberProfileActivity; +import org.smartregister.chw.anc.domain.MemberObject; +import org.smartregister.chw.dao.ChwPNCDao; + +import java.util.List; + +public class PncCloseDateIntentService extends IntentService { + + private static final String TAG = PncCloseDateIntentService.class.getSimpleName(); + + + public PncCloseDateIntentService() { + super(TAG); + } + + @Override + protected void onHandleIntent(Intent intent) { + List memberObjectList = ChwPNCDao.getPncMembersWithMoreThan42Days(); + if (memberObjectList != null && memberObjectList.size() > 0) { + for (MemberObject memberObject : memberObjectList) { + PncMemberProfileActivity.closePncMemberVisits(memberObject.getBaseEntityId()); + } + } + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwGoToMemberProfileBasedOnRegisterTask.java b/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwGoToMemberProfileBasedOnRegisterTask.java index 5098fe6577..2e7fee2340 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwGoToMemberProfileBasedOnRegisterTask.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwGoToMemberProfileBasedOnRegisterTask.java @@ -7,15 +7,21 @@ import org.smartregister.chw.activity.AncMemberProfileActivity; import org.smartregister.chw.activity.ChildProfileActivity; import org.smartregister.chw.activity.FamilyPlanningMemberProfileActivity; +import org.smartregister.chw.activity.HivIndexContactProfileActivity; +import org.smartregister.chw.activity.HivProfileActivity; import org.smartregister.chw.activity.MalariaProfileActivity; import org.smartregister.chw.activity.PncMemberProfileActivity; +import org.smartregister.chw.activity.TbProfileActivity; import org.smartregister.chw.anc.activity.BaseAncMemberProfileActivity; import org.smartregister.chw.core.activity.CoreAboveFiveChildProfileActivity; import org.smartregister.chw.core.activity.CoreChildProfileActivity; import org.smartregister.chw.core.task.CoreChwNotificationGoToMemberProfileTask; import org.smartregister.chw.fp.dao.FpDao; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.dao.HivIndexDao; import org.smartregister.chw.malaria.activity.BaseMalariaProfileActivity; import org.smartregister.chw.pnc.activity.BasePncMemberProfileActivity; +import org.smartregister.chw.tb.dao.TbDao; import org.smartregister.commonregistry.CommonPersonObjectClient; public class ChwGoToMemberProfileBasedOnRegisterTask extends CoreChwNotificationGoToMemberProfileTask { @@ -29,6 +35,21 @@ protected void goToFpProfile(String baseEntityId, Activity activity) { FamilyPlanningMemberProfileActivity.startFpMemberProfileActivity(activity, FpDao.getMember(baseEntityId)); } + @Override + protected void goToHivProfile(String baseEntityId, Activity activity) { + HivProfileActivity.startHivProfileActivity(activity, HivDao.getMember(baseEntityId)); + } + + @Override + protected void goToHivIndexContactProfile(String baseEntityId, Activity activity) { + HivIndexContactProfileActivity.startHivIndexContactProfileActivity(activity, HivIndexDao.getMember(baseEntityId)); + } + + @Override + protected void goToTbProfile(String baseEntityId, Activity activity) { + TbProfileActivity.startTbProfileActivity(activity, TbDao.getMember(baseEntityId)); + } + @Override protected Class getAboveFiveChildProfileActivityClass() { return AboveFiveChildProfileActivity.class; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwStartDraftMonthlyFormTask.java b/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwStartDraftMonthlyFormTask.java new file mode 100644 index 0000000000..b5918a6f77 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/task/ChwStartDraftMonthlyFormTask.java @@ -0,0 +1,109 @@ +package org.smartregister.chw.task; + +import static com.vijay.jsonwizard.constants.JsonFormConstants.REPORT_MONTH; + +import android.content.Intent; +import android.util.Log; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.smartregister.chw.core.activity.HIA2ReportsActivity; +import org.smartregister.chw.core.application.CoreChwApplication; +import org.smartregister.chw.core.domain.Hia2Indicator; +import org.smartregister.chw.core.domain.MonthlyTally; +import org.smartregister.chw.core.repository.HIA2IndicatorsRepository; +import org.smartregister.chw.core.repository.MonthlyTalliesRepository; +import org.smartregister.chw.core.task.StartDraftMonthlyFormTask; +import org.smartregister.util.FormUtils; + +import java.util.Date; +import java.util.List; + +import timber.log.Timber; + +public class ChwStartDraftMonthlyFormTask extends StartDraftMonthlyFormTask { + + public ChwStartDraftMonthlyFormTask(HIA2ReportsActivity baseActivity, Date date, String formName) { + super(baseActivity, date, formName); + } + + @Override + protected Intent doInBackground(Void... params) { + try { + MonthlyTalliesRepository monthlyTalliesRepository = CoreChwApplication.getInstance().monthlyTalliesRepository(); + List monthlyTallies = monthlyTalliesRepository.findDrafts(MonthlyTalliesRepository.DF_YYYYMM.format(date)); + + HIA2IndicatorsRepository hIA2IndicatorsRepository = CoreChwApplication.getInstance().hIA2IndicatorsRepository(); + List hia2Indicators = hIA2IndicatorsRepository.fetchAll(); + if (hia2Indicators == null || hia2Indicators.isEmpty()) { + return null; + } + JSONObject form = new FormUtils(baseActivity).getFormJson(formName); + + JSONArray fieldsArray = form.getJSONObject("step1").getJSONArray("fields"); + JSONArray fieldsArray2 = form.getJSONObject("step2").getJSONArray("fields"); + JSONArray fieldsArray3 = form.getJSONObject("step3").getJSONArray("fields"); + JSONArray fieldsArray4 = form.getJSONObject("step4").getJSONArray("fields"); + JSONArray fieldsArray5 = form.getJSONObject("step5").getJSONArray("fields"); + JSONArray fieldsArray6 = form.getJSONObject("step6").getJSONArray("fields"); + JSONArray fieldsArray7 = form.getJSONObject("step7").getJSONArray("fields"); + + + int i = 1; + // This map holds each category as key and all the fields for that category as the + // value (jsonarray) + for (Hia2Indicator hia2Indicator : hia2Indicators) { + + if (hia2Indicator.getDescription() == null) { + hia2Indicator.setDescription(""); + } + String label; + + try { + int resourceId = baseActivity.getResources().getIdentifier(hia2Indicator.getDescription(), "string", baseActivity.getPackageName()); + label = baseActivity.getResources().getString(resourceId); + } catch (Exception e) { + Timber.e(e); + label = hia2Indicator.getDescription(); + } + JSONObject labelJsonObject = new JSONObject(); + JSONObject editTextJsonObject = new JSONObject(); + updateJsonObjects(editTextJsonObject, labelJsonObject, hia2Indicator, label, monthlyTallies); + if (i <= 5) { + fieldsArray.put(labelJsonObject); + fieldsArray.put(editTextJsonObject); + } else if (i <= 9) { + fieldsArray2.put(labelJsonObject); + fieldsArray2.put(editTextJsonObject); + } else if (i <= 10) { + fieldsArray3.put(labelJsonObject); + fieldsArray3.put(editTextJsonObject); + } else if (i <= 15) { + fieldsArray4.put(labelJsonObject); + fieldsArray4.put(editTextJsonObject); + } else if (i <= 17) { + fieldsArray5.put(labelJsonObject); + fieldsArray5.put(editTextJsonObject); + } else if (i <= 29) { + fieldsArray6.put(labelJsonObject); + fieldsArray6.put(editTextJsonObject); + } else if (i <= 44) { + fieldsArray7.put(labelJsonObject); + fieldsArray7.put(editTextJsonObject); + } + i++; + } + // Add the confirm button + JSONObject buttonObject = createFormConfirmButton(); + fieldsArray7.put(buttonObject); + form.put(REPORT_MONTH, HIA2ReportsActivity.dfyymmdd.format(date)); + form.put("identifier", "HIA2ReportForm"); + + return createServiceIntent(form); + } catch (Exception e) { + Timber.e(Log.getStackTraceString(e)); + } + + return null; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/task/HivVisitScheduler.java b/opensrp-chw/src/main/java/org/smartregister/chw/task/HivVisitScheduler.java new file mode 100644 index 0000000000..e8fe2335a8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/task/HivVisitScheduler.java @@ -0,0 +1,48 @@ +package org.smartregister.chw.task; + +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.contract.ScheduleTask; +import org.smartregister.chw.core.domain.BaseScheduleTask; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.dao.ChwCBHSDao; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.chw.rule.CbhsFollowupRule; +import org.smartregister.chw.util.ChwHomeVisitUtil; + +import java.util.Date; +import java.util.List; + +public class HivVisitScheduler extends BaseTaskExecutor { + + @Override + public void resetSchedule(String baseEntityID, String scheduleName) { + super.resetSchedule(baseEntityID, scheduleName); + ChwApplication.getInstance().getScheduleRepository().deleteScheduleByGroup(getScheduleGroup(), baseEntityID); + } + + @Override + public List generateTasks(String baseEntityID, String eventName, Date eventDate) { + + BaseScheduleTask baseScheduleTask = prepareNewTaskObject(baseEntityID); + HivMemberObject hivMemberObject = HivDao.getMember(baseEntityID); + Date nextVisitDate = ChwCBHSDao.getNextVisitDate(baseEntityID); + CbhsFollowupRule cbhsFollowupRule = ChwHomeVisitUtil.getCBHSVisitStatus(nextVisitDate, hivMemberObject.getHivRegistrationDate()); + + baseScheduleTask.setScheduleDueDate(cbhsFollowupRule.getDueDate()); + baseScheduleTask.setScheduleExpiryDate(cbhsFollowupRule.getExpiryDate()); + baseScheduleTask.setScheduleOverDueDate(cbhsFollowupRule.getOverDueDate()); + + return toScheduleList(baseScheduleTask); + } + + @Override + public String getScheduleName() { + return CoreConstants.SCHEDULE_TYPES.HIV_VISIT; + } + + @Override + public String getScheduleGroup() { + return CoreConstants.SCHEDULE_GROUPS.HOME_VISIT; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/task/TbVisitScheduler.java b/opensrp-chw/src/main/java/org/smartregister/chw/task/TbVisitScheduler.java new file mode 100644 index 0000000000..dd6646f32c --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/task/TbVisitScheduler.java @@ -0,0 +1,49 @@ +package org.smartregister.chw.task; + +import org.smartregister.chw.anc.domain.Visit; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.core.contract.ScheduleTask; +import org.smartregister.chw.core.domain.BaseScheduleTask; +import org.smartregister.chw.core.rule.TbFollowupRule; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.HomeVisitUtil; +import org.smartregister.chw.tb.dao.TbDao; +import org.smartregister.chw.tb.domain.TbMemberObject; + +import java.util.Date; +import java.util.List; + +public class TbVisitScheduler extends BaseTaskExecutor { + + @Override + public void resetSchedule(String baseEntityID, String scheduleName) { + super.resetSchedule(baseEntityID, scheduleName); + ChwApplication.getInstance().getScheduleRepository().deleteScheduleByGroup(getScheduleGroup(), baseEntityID); + } + + @Override + public List generateTasks(String baseEntityID, String eventName, Date eventDate) { + + BaseScheduleTask baseScheduleTask = prepareNewTaskObject(baseEntityID); + TbMemberObject tbMemberObject = TbDao.getMember(baseEntityID); + Visit lastVisit = TbDao.getLatestVisit(baseEntityID, org.smartregister.chw.tb.util.Constants.EventType.FOLLOW_UP_VISIT); + Date lastVisitDate = lastVisit != null ? lastVisit.getDate() : null; + TbFollowupRule tbFollowupRule = HomeVisitUtil.getTbVisitStatus(lastVisitDate, tbMemberObject.getTbRegistrationDate()); + + baseScheduleTask.setScheduleDueDate(tbFollowupRule.getDueDate()); + baseScheduleTask.setScheduleExpiryDate(tbFollowupRule.getExpiryDate()); + baseScheduleTask.setScheduleOverDueDate(tbFollowupRule.getOverDueDate()); + + return toScheduleList(baseScheduleTask); + } + + @Override + public String getScheduleName() { + return CoreConstants.SCHEDULE_TYPES.TB_VISIT; + } + + @Override + public String getScheduleGroup() { + return CoreConstants.SCHEDULE_GROUPS.HOME_VISIT; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/AllClientsUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/AllClientsUtils.java index 155ac468ae..ea64f4b5fa 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/AllClientsUtils.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/AllClientsUtils.java @@ -8,18 +8,24 @@ import org.jetbrains.annotations.NotNull; import org.smartregister.chw.R; import org.smartregister.chw.activity.AboveFiveChildProfileActivity; +import org.smartregister.chw.activity.AgywProfileActivity; import org.smartregister.chw.activity.AllClientsMemberProfileActivity; import org.smartregister.chw.activity.AncMemberProfileActivity; import org.smartregister.chw.activity.ChildProfileActivity; import org.smartregister.chw.activity.FamilyOtherMemberProfileActivity; import org.smartregister.chw.activity.FamilyPlanningMemberProfileActivity; +import org.smartregister.chw.activity.HivProfileActivity; +import org.smartregister.chw.activity.KvpPrEPProfileActivity; import org.smartregister.chw.activity.MalariaProfileActivity; import org.smartregister.chw.activity.PncMemberProfileActivity; +import org.smartregister.chw.activity.TbProfileActivity; import org.smartregister.chw.anc.domain.MemberObject; import org.smartregister.chw.core.application.CoreChwApplication; import org.smartregister.chw.core.utils.CoreChildUtils; import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.fp.dao.FpDao; +import org.smartregister.chw.hiv.dao.HivDao; +import org.smartregister.chw.tb.dao.TbDao; import org.smartregister.clientandeventmodel.Client; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.family.domain.FamilyEventClient; @@ -64,9 +70,8 @@ public static void gotToPncProfile(Activity activity, CommonPersonObjectClient p activity.startActivity(initProfileActivityIntent(activity, patient, bundle, PncMemberProfileActivity.class)); } - public static void goToAncProfile(Activity activity, CommonPersonObjectClient patient, Bundle bundle) { - patient.getColumnmaps().putAll(CoreChwApplication.ancRegisterRepository().getAncCommonPersonObject(patient.entityId()).getColumnmaps()); - activity.startActivity(initProfileActivityIntent(activity, patient, bundle, AncMemberProfileActivity.class)); + public static void goToAncProfile(Activity activity, CommonPersonObjectClient patient) { + AncMemberProfileActivity.startMe(activity,patient.getCaseId()); } public static void gotToMalariaProfile(Activity activity, CommonPersonObjectClient patient) { @@ -76,6 +81,18 @@ public static void gotToMalariaProfile(Activity activity, CommonPersonObjectClie public static void goToFamilyPlanningProfile(Activity activity, CommonPersonObjectClient patient) { FamilyPlanningMemberProfileActivity.startFpMemberProfileActivity(activity, FpDao.getMember(patient.getCaseId())); } + public static void goToHivProfile(Activity activity, CommonPersonObjectClient patient) { + HivProfileActivity.startHivProfileActivity(activity, HivDao.getMember(patient.getCaseId())); + } + public static void goToTbProfile(Activity activity, CommonPersonObjectClient patient) { + TbProfileActivity.startTbProfileActivity(activity, TbDao.getMember(patient.getCaseId())); + } + public static void goToAgywProfile(Activity activity, CommonPersonObjectClient client){ + AgywProfileActivity.startProfile(activity, client.getCaseId()); + } + public static void goToKvpPrepProfile(Activity activity, CommonPersonObjectClient client){ + KvpPrEPProfileActivity.startProfileActivity(activity, client.getCaseId()); + } private static Intent initProfileActivityIntent(Activity activity, CommonPersonObjectClient patient, Bundle bundle, Class clazz) { Intent intent = new Intent(activity, clazz); diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/CbhsUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/CbhsUtils.java new file mode 100644 index 0000000000..21d4e31fde --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/CbhsUtils.java @@ -0,0 +1,94 @@ +package org.smartregister.chw.util; + +import static org.smartregister.chw.util.Constants.Events.CBHS_CLOSE_VISITS; +import static org.smartregister.chw.util.Constants.TableName.CBHS_REGISTER; +import static org.smartregister.util.JsonFormUtils.FIELDS; + +import android.content.Context; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.smartregister.AllConstants; +import org.smartregister.chw.BuildConfig; +import org.smartregister.chw.anc.AncLibrary; +import org.smartregister.chw.anc.util.NCUtils; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.dao.ChwCBHSDao; +import org.smartregister.chw.hiv.domain.HivMemberObject; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.clientandeventmodel.Obs; +import org.smartregister.repository.AllSharedPreferences; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Locale; +import java.util.UUID; + +import timber.log.Timber; + +public class CbhsUtils { + public static void createCloseCbhsEvent(HivMemberObject hivMemberObject) { + AllSharedPreferences allSharedPreferences = AncLibrary.getInstance().context().allSharedPreferences(); + Event closeCbhsEvent = (Event) new Event() + .withBaseEntityId(hivMemberObject.getBaseEntityId()) + .withEventDate(new Date()) + .withEventType(CBHS_CLOSE_VISITS) + .withFormSubmissionId(UUID.randomUUID().toString()) + .withEntityType(CBHS_REGISTER) + .withProviderId(allSharedPreferences.fetchRegisteredANM()) + .withTeamId(allSharedPreferences.fetchDefaultTeamId(allSharedPreferences.fetchRegisteredANM())) + .withTeam(allSharedPreferences.fetchDefaultTeam(allSharedPreferences.fetchRegisteredANM())) + .withClientDatabaseVersion(BuildConfig.DATABASE_VERSION) + .withClientApplicationVersion(BuildConfig.VERSION_CODE) + .withDateCreated(new Date()); + + closeCbhsEvent.setFormSubmissionId(UUID.randomUUID().toString()); + closeCbhsEvent.setEventDate(new Date()); + + closeCbhsEvent.addObs( + (new Obs()) + .withFormSubmissionField("cbhs_close_visit_date") + .withValue(new Date().toString()) + .withFieldCode("cbhs_close_visit_date") + .withFieldType("formsubmissionField") + .withFieldDataType("text") + .withParentCode("") + .withHumanReadableValues(new ArrayList<>())); + + try { + NCUtils.addEvent(allSharedPreferences, closeCbhsEvent); + NCUtils.startClientProcessing(); + } catch (Exception e) { + Timber.e(e); + } + } + + public static void removeDeceasedClients(HivMemberObject hivMemberObject, Context context) throws Exception { + JSONObject removeFamilyMemberForm = null; + if (ChwCBHSDao.isDeceased(hivMemberObject.getBaseEntityId())) { + try { + removeFamilyMemberForm = (new FormUtils()).getFormJsonFromRepositoryOrAssets(context, CoreConstants.JSON_FORM.FAMILY_DETAILS_REMOVE_MEMBER); + org.smartregister.chw.anc.util.JsonFormUtils.getRegistrationForm(removeFamilyMemberForm, hivMemberObject.getBaseEntityId(), org.smartregister.Context.getInstance().allSharedPreferences().getPreference(AllConstants.CURRENT_LOCATION_ID)); + } catch (Exception e) { + Timber.e(e); + } + + if (removeFamilyMemberForm != null) { + JSONObject stepOne = removeFamilyMemberForm.getJSONObject(org.smartregister.chw.anc.util.JsonFormUtils.STEP1); + JSONArray jsonArray = stepOne.getJSONArray(FIELDS); + + org.smartregister.chw.anc.util.JsonFormUtils.updateFormField(jsonArray, "remove_reason", "Death"); + + org.smartregister.chw.anc.util.JsonFormUtils.updateFormField(jsonArray, "dob", hivMemberObject.getAge()); + org.smartregister.chw.anc.util.JsonFormUtils.updateFormField(jsonArray, "date_died", new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date())); + org.smartregister.chw.anc.util.JsonFormUtils.updateFormField(jsonArray, "age_at_death", Utils.getAgeFromDate(hivMemberObject.getAge()) + "y"); + + Utils.removeUser(null, removeFamilyMemberForm, Utils.context().allSharedPreferences().fetchRegisteredANM()); + } + } + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildDBConstants.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildDBConstants.java index 8bed89e658..1168b7a828 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildDBConstants.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildDBConstants.java @@ -18,7 +18,7 @@ public static String childDueVaccinesFilterForChildrenBelowTwoAndGirlsAgeNineToE private static String childDueVaccinesFilterForChildrenBelowTwoAndGirlsAgeNineToEleven(String dateColumn, String entryPoint, String motherEntityId) { return " (( ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + entryPoint + ",'') <> 'PNC' ) " + " or (ifnull(" + CoreConstants.TABLE_NAME.CHILD + "." + entryPoint + ",'') = 'PNC'" + - " and ( date(" + CoreConstants.TABLE_NAME.CHILD + "." + dateColumn + ", '+28 days') <= date() " + + " and ( date(" + CoreConstants.TABLE_NAME.CHILD + "." + dateColumn + ", '+42 days') <= date() " + " and ((SELECT is_closed FROM ec_family_member WHERE base_entity_id = " + CoreConstants.TABLE_NAME.CHILD + "." + motherEntityId + " ) = 0))) " + " or (ifnull(ec_child.entry_point,'') = 'PNC' " + " and (SELECT is_closed FROM ec_family_member WHERE base_entity_id = ec_child.mother_entity_id ) = 1)) " + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildUtils.java index 0d4b407ebf..164911325a 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildUtils.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChildUtils.java @@ -2,12 +2,15 @@ import android.content.Context; + import com.google.gson.reflect.TypeToken; import org.smartregister.chw.R; import org.smartregister.chw.core.utils.ChildDBConstants; import org.smartregister.chw.core.utils.CoreChildUtils; import org.smartregister.chw.core.utils.ServiceTask; +import org.smartregister.domain.Event; +import org.smartregister.domain.Obs; import org.smartregister.family.util.DBConstants; import org.smartregister.util.DateUtil; @@ -79,10 +82,10 @@ public static String[] mainColumns(String tableName, String familyTable, String public static ServiceTask createServiceTaskFromEvent(String taskType, String details, String title, String formSubmissionId) { ServiceTask serviceTask = new ServiceTask(); - org.smartregister.domain.Event event = ChildUtils.gsonConverter.fromJson(details, new TypeToken() { + Event event = ChildUtils.gsonConverter.fromJson(details, new TypeToken() { }.getType()); - List observations = event.getObs(); - for (org.smartregister.domain.Obs obs : observations) { + List observations = event.getObs(); + for (Obs obs : observations) { if (obs.getFormSubmissionField().equalsIgnoreCase(formSubmissionId)) { List hu = obs.getHumanReadableValues(); String value = ""; @@ -100,11 +103,11 @@ public static ServiceTask createServiceTaskFromEvent(String taskType, String det public static ServiceTask createECDTaskFromEvent(Context context, String taskType, String details, String title) { ServiceTask serviceTask = new ServiceTask(); - org.smartregister.domain.Event event = ChildUtils.gsonConverter.fromJson(details, new TypeToken() { + Event event = ChildUtils.gsonConverter.fromJson(details, new TypeToken() { }.getType()); - List observations = event.getObs(); + List observations = event.getObs(); String label = ""; - for (org.smartregister.domain.Obs obs : observations) { + for (Obs obs : observations) { if (obs.getFormSubmissionField().equalsIgnoreCase("develop_warning_signs")) { List hu = obs.getHumanReadableValues(); String value = ""; @@ -147,5 +150,4 @@ public static String getDurationFromTwoDate(Date dob, Date homeVisitServiceDate) return DateUtil.getDuration(timeDiff); } - } \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwAncJsonFormUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwAncJsonFormUtils.java new file mode 100644 index 0000000000..3a8fb6da59 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwAncJsonFormUtils.java @@ -0,0 +1,118 @@ +package org.smartregister.chw.util; + +import com.vijay.jsonwizard.constants.JsonFormConstants; + +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.Nullable; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.anc.domain.VisitDetail; +import org.smartregister.chw.anc.util.JsonFormUtils; +import org.smartregister.chw.anc.util.NCUtils; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import timber.log.Timber; + +public class ChwAncJsonFormUtils extends JsonFormUtils { + public static void populateForm(@Nullable JSONObject jsonObject, Map> details) { + if (details == null || jsonObject == null) return; + try { + // x steps + String count_str = jsonObject.getString(JsonFormConstants.COUNT); + + int step_count = StringUtils.isNotBlank(count_str) ? Integer.valueOf(count_str) : 1; + while (step_count > 0) { + JSONArray jsonArray = jsonObject.getJSONObject(MessageFormat.format("step{0}", step_count)).getJSONArray(JsonFormConstants.FIELDS); + + int field_count = jsonArray.length() - 1; + while (field_count >= 0) { + + JSONObject jo = jsonArray.getJSONObject(field_count); + String key = jo.getString(JsonFormConstants.KEY); + List detailList = details.get(key); + + if (detailList != null) { + if (jo.getString(JsonFormConstants.TYPE).equalsIgnoreCase(JsonFormConstants.CHECK_BOX)) { + jo.put(JsonFormConstants.VALUE, getValue(jo, detailList)); + } else { + String value = getValue(detailList.get(0)); + if (key.contains("date")) { + value = NCUtils.getFormattedDate(NCUtils.getSaveDateFormat(), NCUtils.getSourceDateFormat(), value); + } + jo.put(JsonFormConstants.VALUE, value); + } + } + + field_count--; + } + + step_count--; + } + + } catch (Exception e) { + Timber.e(e); + } + } + + public static JSONArray getValue(JSONObject jo, List visitDetails) throws JSONException { + JSONArray values = new JSONArray(); + if (jo.getString(JsonFormConstants.TYPE).equalsIgnoreCase(JsonFormConstants.CHECK_BOX)) { + JSONArray options = jo.getJSONArray(JsonFormConstants.OPTIONS_FIELD_NAME); + HashMap valueMap = new HashMap<>(); + + int x = options.length() - 1; + while (x >= 0) { + JSONObject object = options.getJSONObject(x); + valueMap.put(object.getString(JsonFormConstants.KEY), new NameID(object.getString(JsonFormConstants.KEY), x)); + x--; + } + + for (VisitDetail d : visitDetails) { + String val = getValue(d); + List checkedList = new ArrayList<>(Arrays.asList(val.split(", "))); + if (checkedList.size() > 1) { + for (String item : checkedList) { + NameID nid = valueMap.get(item); + if (nid != null) { + values.put(nid.name); + options.getJSONObject(nid.position).put(JsonFormConstants.VALUE, true); + } + } + } else { + NameID nid = valueMap.get(val); + if (nid != null) { + values.put(nid.name); + options.getJSONObject(nid.position).put(JsonFormConstants.VALUE, true); + } + } + } + } else { + for (VisitDetail d : visitDetails) { + String val = getValue(d); + if (StringUtils.isNotBlank(val)) { + values.put(val); + } + } + } + return values; + } + + + + private static class NameID { + private String name; + private int position; + + public NameID(String name, int position) { + this.name = name; + this.position = position; + } + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwHomeVisitUtil.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwHomeVisitUtil.java new file mode 100644 index 0000000000..09a34c465e --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwHomeVisitUtil.java @@ -0,0 +1,17 @@ +package org.smartregister.chw.util; + +import org.smartregister.chw.core.application.CoreChwApplication; +import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.HomeVisitUtil; +import org.smartregister.chw.rule.CbhsFollowupRule; + +import java.util.Date; + +public class ChwHomeVisitUtil extends HomeVisitUtil { + + public static CbhsFollowupRule getCBHSVisitStatus(Date lastVisitDate, Date hivDate) { + CbhsFollowupRule cbhsFollowupRule = new CbhsFollowupRule(hivDate, lastVisitDate); + CoreChwApplication.getInstance().getRulesEngineHelper().getHivRule(cbhsFollowupRule, CoreConstants.RULE_FILE.HIV_FOLLOW_UP_VISIT); + return cbhsFollowupRule; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryConstant.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryConstant.java new file mode 100644 index 0000000000..2c730e1c65 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryConstant.java @@ -0,0 +1,467 @@ +package org.smartregister.chw.util; + +public interface ChwQueryConstant { + String ALL_CLIENTS_SELECT_QUERY = "SELECT * FROM (" + + "/*INDEPENDENT MEMBERS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Independent' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_member.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family.entity_type = 'ec_independent_client'\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register where ec_anc_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome where ec_pregnancy_outcome.delivery_date is not null\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " WHERE datetime('NOW') <= datetime(ec_malaria_confirmation.last_interacted_with/1000, 'unixepoch', 'localtime','+15 days')\n" + + " AND ec_malaria_confirmation.is_closed = 0 AND ec_malaria_confirmation.malaria = 1 \n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_cbhs_register.base_entity_id AS base_entity_id\n" + + " FROM ec_cbhs_register\n" + + " WHERE is_closed is 0 \n" + + ")" + + "UNION ALL" + + "/* CBHS REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'CBHS' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_cbhs_register.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_cbhs_register\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_cbhs_register.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_cbhs_register.is_closed is 0\n" + + " AND ec_cbhs_register.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + ")\n" + + "\n" + + "UNION ALL\n" + + "/*OTHER FAMILY MEMBERS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " NULL AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_member.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND (ec_family.entity_type = 'ec_family' OR ec_family.entity_type is null)\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register where ec_anc_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome where ec_pregnancy_outcome.delivery_date is not null\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " WHERE datetime('NOW') <= datetime(ec_malaria_confirmation.last_interacted_with/1000, 'unixepoch', 'localtime','+15 days')\n" + + " AND ec_malaria_confirmation.is_closed = 0 AND ec_malaria_confirmation.malaria = 1 \n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_cbhs_register.base_entity_id AS base_entity_id\n" + + " FROM ec_cbhs_register\n" + + ")\n" + + "UNION ALL\n" + + "/* ANC REGISTER */\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'ANC' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_anc_register.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_anc_register\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_anc_register.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " and ec_anc_register.is_closed is 0\n" + + " and ec_anc_register.base_entity_id IN (%s)\n" + + "\n" + + "UNION ALL\n" + + "\n" + + "/* PNC REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'PNC' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_pregnancy_outcome.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_pregnancy_outcome\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_pregnancy_outcome.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " and ec_pregnancy_outcome.is_closed is 0\n" + + " and ec_pregnancy_outcome.delivery_date is not null\n" + + " AND ec_pregnancy_outcome.base_entity_id NOT IN\n" + + " (SELECT base_entity_id FROM ec_anc_register WHERE ec_anc_register.is_closed IS 0)\n" + + " AND ec_pregnancy_outcome.base_entity_id IN (%s)\n" + + "\n" + + "UNION ALL\n" + + "/* CHILD REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Child' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_child.last_interacted_with AS last_interacted_with,\n" + + " ec_child.mother_first_name AS mother_first_name,\n" + + " ec_child.mother_middle_name AS mother_middle_name,\n" + + " ec_child.mother_last_name AS mother_last_name\n" + + "FROM (SELECT ec_child.*,\n" + + " mother.first_name AS mother_first_name,\n" + + " mother.last_name AS mother_last_name,\n" + + " mother.middle_name AS mother_middle_name\n" + + " FROM ec_child\n" + + " inner join ec_family on ec_family.base_entity_id = ec_child.relational_id\n" + + " INNER JOIN ec_family_member AS mother ON ec_family.primary_caregiver = mother.base_entity_id\n" + + " ) ec_child\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_child.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "WHERE ec_family_member.is_closed = '0'\n" + + " AND ec_family_member.date_removed is null\n" + + " AND cast(strftime('%Y-%m-%d %H:%M:%S', 'now') - strftime('%Y-%m-%d %H:%M:%S', ec_child.dob) as int) > 0\n" + + " AND ec_child.base_entity_id IN (%s)\n" + + "\n" + + "UNION ALL\n" + + "/* TB REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'TB' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_tb_register.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_tb_register\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_tb_register.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " and ec_tb_register.is_closed is 0\n" + + " and ec_tb_register.tb_case_closure_date is null\n" + + " AND ec_tb_register.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + ")\n" + + "\n" + + "UNION ALL\n" + + "/*ONLY MALARIA PATIENTS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Malaria' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_malaria_confirmation.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_malaria_confirmation\n" + + " on ec_family_member.base_entity_id = ec_malaria_confirmation.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND datetime('NOW') <= datetime(ec_malaria_confirmation.last_interacted_with/1000, 'unixepoch', 'localtime','+15 days')\n" + + " AND ec_malaria_confirmation.is_closed = 0 AND ec_malaria_confirmation.malaria = 1 \n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_cbhs_register.base_entity_id AS base_entity_id\n" + + " FROM ec_cbhs_register\n" + + ")\n" + + "UNION ALL\n" + + "\n" + + "/*ONLY FAMILY PLANNING PATIENTS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Family Planning' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_planning.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_family_planning\n" + + " on ec_family_member.base_entity_id = ec_family_planning.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_planning.is_closed is 0\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_agyw_register.base_entity_id AS base_entity_id\n" + + " FROM ec_agyw_register where ec_agyw_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_hiv_register.base_entity_id AS base_entity_id\n" + + " FROM ec_hiv_register)\n" + + "UNION ALL\n" + + "\n" + + "/*ONLY AGYW clients*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'AGYW' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_agyw_register.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_agyw_register\n" + + " on ec_family_member.base_entity_id = ec_agyw_register.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_agyw_register.is_closed is 0\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_kvp_prep_register.base_entity_id AS base_entity_id\n" + + " FROM ec_kvp_prep_register where ec_kvp_prep_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_cbhs_register.base_entity_id AS base_entity_id\n" + + " FROM ec_cbhs_register)\n" + + "UNION ALL\n" + + "\n" + + "/*ONLY KVP/PrEP clients*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'KVP/PrEP' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_kvp_prep_register.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_kvp_prep_register\n" + + " on ec_family_member.base_entity_id = ec_kvp_prep_register.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_kvp_prep_register.is_closed is 0\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_cbhs_register.base_entity_id AS base_entity_id\n" + + " FROM ec_cbhs_register)\n" + + ")\n" + + "ORDER BY last_interacted_with DESC;"; +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryForMaleClients.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryForMaleClients.java new file mode 100644 index 0000000000..abb08320d3 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwQueryForMaleClients.java @@ -0,0 +1,258 @@ +package org.smartregister.chw.util; + +public interface ChwQueryForMaleClients { + String ALL_MALE_CLIENTS_SELECT_QUERY = "" + + "/*INDEPENDENT MEMBERS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Independent' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_member.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family.entity_type = 'ec_independent_client'\n" + + " AND ec_family_member.gender = 'Male' " + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register where ec_anc_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome where ec_pregnancy_outcome.delivery_date is not null\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_hiv_register.base_entity_id AS base_entity_id\n" + + " FROM ec_hiv_register\n" + + ")" + + "UNION ALL" + + "/* CBHS REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'CBHS' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_hiv_register.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_hiv_register\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_hiv_register.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_member.gender = 'Male' " + + " and ec_hiv_register.is_closed is 0\n" + + " AND ec_hiv_register.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + ")\n" + + "\n" + + "UNION ALL\n" + + "/*OTHER FAMILY MEMBERS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " NULL AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_member.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_member.gender = 'Male' " + + " AND (ec_family.entity_type = 'ec_family' OR ec_family.entity_type is null)\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register where ec_anc_register.is_closed is 0\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome where ec_pregnancy_outcome.delivery_date is not null\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_hiv_register.base_entity_id AS base_entity_id\n" + + " FROM ec_hiv_register\n" + + ")\n" + + "UNION ALL\n" + + "/* TB REGISTER */\n" + + "\n" + + "SELECT ec_family_member.first_name AS first_name,\n" + + " ec_family_member.middle_name AS middle_name,\n" + + " ec_family_member.last_name AS last_name,\n" + + " ec_family_member.gender AS gender,\n" + + " ec_family_member.dob AS dob,\n" + + " ec_family_member.base_entity_id AS base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'TB' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " ec_tb_register.last_interacted_with AS last_interacted_with,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name\n" + + "FROM ec_tb_register\n" + + " inner join ec_family_member on ec_family_member.base_entity_id = ec_tb_register.base_entity_id\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_member.gender = 'Male' " + + " and ec_tb_register.is_closed is 0\n" + + " and ec_tb_register.tb_case_closure_date is null\n" + + " AND ec_tb_register.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + ")\n" + + "\n" + + "UNION ALL\n" + + "/*ONLY MALARIA PATIENTS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Malaria' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_malaria_confirmation.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_malaria_confirmation\n" + + " on ec_family_member.base_entity_id = ec_malaria_confirmation.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_member.gender = 'Male' " + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_family_planning.base_entity_id AS base_entity_id\n" + + " FROM ec_family_planning\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_hiv_register.base_entity_id AS base_entity_id\n" + + " FROM ec_hiv_register\n" + + ")\n" + + "UNION ALL\n" + + "\n" + + "/*ONLY FAMILY PLANNING PATIENTS*/\n" + + "SELECT ec_family_member.first_name,\n" + + " ec_family_member.middle_name,\n" + + " ec_family_member.last_name,\n" + + " ec_family_member.gender,\n" + + " ec_family_member.dob,\n" + + " ec_family_member.base_entity_id,\n" + + " ec_family_member.id as _id,\n" + + " 'Family Planning' AS register_type,\n" + + " ec_family_member.relational_id as relationalid,\n" + + " ec_family.village_town as home_address,\n" + + " NULL AS mother_first_name,\n" + + " NULL AS mother_last_name,\n" + + " NULL AS mother_middle_name,\n" + + " ec_family_planning.last_interacted_with AS last_interacted_with\n" + + "FROM ec_family_member\n" + + " inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" + + " inner join ec_family_planning\n" + + " on ec_family_member.base_entity_id = ec_family_planning.base_entity_id\n" + + "where ec_family_member.date_removed is null\n" + + " AND ec_family_member.gender = 'Male' " + + " AND ec_family_planning.is_closed is 0\n" + + " AND ec_family_member.base_entity_id IN (%s)\n" + + " AND ec_family_member.base_entity_id NOT IN (\n" + + " SELECT ec_anc_register.base_entity_id AS base_entity_id\n" + + " FROM ec_anc_register\n" + + " UNION ALL\n" + + " SELECT ec_pregnancy_outcome.base_entity_id AS base_entity_id\n" + + " FROM ec_pregnancy_outcome\n" + + " UNION ALL\n" + + " SELECT ec_child.base_entity_id AS base_entity_id\n" + + " FROM ec_child\n" + + " UNION ALL\n" + + " SELECT ec_malaria_confirmation.base_entity_id AS base_entity_id\n" + + " FROM ec_malaria_confirmation\n" + + " UNION ALL\n" + + " SELECT ec_tb_register.base_entity_id AS base_entity_id\n" + + " FROM ec_tb_register\n" + + " WHERE ec_tb_register.tb_case_closure_date is null\n" + + " UNION ALL\n" + + " SELECT ec_hiv_register.base_entity_id AS base_entity_id\n" + + " FROM ec_hiv_register\n" + + ")\n" + + "ORDER BY last_interacted_with DESC;"; +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwWebAppInterface.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwWebAppInterface.java new file mode 100644 index 0000000000..71dd6a8ef5 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ChwWebAppInterface.java @@ -0,0 +1,70 @@ +package org.smartregister.chw.util; + +import android.content.Context; +import android.webkit.JavascriptInterface; + +import static org.smartregister.util.Utils.getAllSharedPreferences; + +public class ChwWebAppInterface { + Context mContext; + + String reportType; + + + public ChwWebAppInterface(Context c, String reportType) { + mContext = c; + this.reportType = reportType; + } + + @JavascriptInterface + public String getDataForReport() { + if (reportType.equalsIgnoreCase(Constants.ReportConstants.ReportTypes.CBHS_REPORT)) { + ReportUtils.setPrintJobName("cbhs_monthly_summary-" + ReportUtils.getReportPeriod() + ".pdf"); + return ReportUtils.CBHSReport.computeReport(ReportUtils.getReportDate(), mContext); + } + if(reportType.equalsIgnoreCase(Constants.ReportConstants.ReportTypes.MOTHER_CHAMPION_REPORT)){ + ReportUtils.setPrintJobName("mother_champion_report-" + ReportUtils.getReportPeriod() + ".pdf"); + return ReportUtils.MotherChampionReport.computeReport(ReportUtils.getReportDate()); + } + + + return ""; + } + + @JavascriptInterface + public String getData(String key) { + if (reportType.equalsIgnoreCase(Constants.ReportConstants.ReportTypes.AGYW_REPORT)){ + ReportUtils.setPrintJobName("AGYW_report_ya_mwezi-" + ReportUtils.getReportPeriod() + ".pdf"); + return ReportUtils.AGYWReport.computeReport(ReportUtils.getReportDate()); + } + if (reportType.equalsIgnoreCase(Constants.ReportConstants.ReportTypes.CONDOM_DISTRIBUTION_REPORT)){ + switch (key) { + case Constants.ReportConstants.CDPReportKeys.ISSUING_REPORTS: + ReportUtils.setPrintJobName("CDP_issuing_report_ya_mwezi-" + ReportUtils.getReportPeriod() + ".pdf"); + return ReportUtils.CDPReports.computeIssuingReports(ReportUtils.getReportDate()); + case Constants.ReportConstants.CDPReportKeys.RECEIVING_REPORTS: + ReportUtils.setPrintJobName("CDP_receiving_report_ya_mwezi-" + ReportUtils.getReportPeriod() + ".pdf"); + return ReportUtils.CDPReports.computeReceivingReports(ReportUtils.getReportDate()); + default: + return ""; + } + } + return ""; + } + + + @JavascriptInterface + public String getDataPeriod() { + return ReportUtils.getReportPeriod(); + } + + @JavascriptInterface + public String getDataPeriod(String reportKey) { + return ReportUtils.getReportPeriod(); + } + + @JavascriptInterface + public String getReportingFacility() { + return getAllSharedPreferences().fetchCurrentLocality(); + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/Constants.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/Constants.java index b9948aa316..82ef3aa7db 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/Constants.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/Constants.java @@ -3,6 +3,9 @@ import org.smartregister.chw.core.utils.CoreConstants; import org.smartregister.chw.core.utils.Utils; +import static org.smartregister.chw.core.utils.CoreConstants.JSON_FORM.assetManager; +import static org.smartregister.chw.core.utils.CoreConstants.JSON_FORM.locale; + public class Constants extends CoreConstants { public static final String REFERRAL_TASK_FOCUS = "referral_task_focus"; public static final String REFERRAL_TYPES = "ReferralTypes"; @@ -22,11 +25,18 @@ public static class FORM_SUBMISSION_FIELD { public static String pncHfNextVisitDateFieldType = "pnc_hf_next_visit_date"; } + public static class JsonFormConstants{ + public static String CLIENT_MOVED_LOCATION = "client_moved_location"; + public static final String NAME_OF_HF = "name_of_hf"; + public static final String STEP1 = "step1"; + } public static class EncounterType { public static final String SICK_CHILD = "Sick Child Referral"; public static final String PNC_REFERRAL = "PNC Referral"; public static final String ANC_REFERRAL = "ANC Referral"; + public static final String PMTCT_COMMUNITY_FOLLOWUP_FEEDBACK = "PMTCT Community Followup Feedback"; + public static final String MOTHER_CHAMPION_FOLLOWUP = "Mother Champion Followup"; } public static class ChildIllnessViewType { @@ -54,10 +64,105 @@ public static String getDeliveryKitReceived() { } } + public interface PartnerRegistrationConstants { + String PARTNER_REGISTRATION_EVENT = "Partner Registration"; + int EXISTING_PARTNER_REQUEST_CODE = 12344; + int NEW_PARTNER_REQUEST_CODE = 12345; + String INTENT_BASE_ENTITY_ID = "BASE_ENTITY_ID"; + String PARTNER_BASE_ENTITY_ID = "partner_base_entity_id"; + String FEEDBACK_FORM_ID = "feedback_form_id"; + String FormSubmissionId = "formSubmissionId"; + String INTENT_FORM_SUBMISSION_ID = "form_submission_id"; + String REFERRAL_FORM_SUBMISSION_ID = "referral_form_submission_id"; + String ReferralFormId = "referral_form_id"; + } + public static class CBHSJsonForms { + private static final String CBHS_FOLLOWUP_FORM = "cbhs_followup_form"; + + public static String getCbhsFollowupForm() { + return CBHS_FOLLOWUP_FORM; + } + } + + public static final class JsonForm{ + private static final String PARTNER_REGISTRATION_FORM = "male_partner_registration_form"; + private static final String PMTCT_COMMUNITY_FOLLOWUP_FEEDBACK = "pmtct_community_followup_feedback"; + private static final String MOTHER_CHAMPION_FOLLOWUP_FORM = "mother_champion_followup"; + private static final String MOTHER_CHAMPION_SBCC_FORM = "mother_champion_sbcc_sessions"; + private static final String CBHS_REGISTRATION_FORM = "cbhs_registration"; + + public static String getCbhsRegistrationForm() { + return CBHS_REGISTRATION_FORM; + } + + public static String getMotherChampionFollowupForm() { + return MOTHER_CHAMPION_FOLLOWUP_FORM; + } + + public static String getPmtctCommunityFollowupFeedback() { + return PMTCT_COMMUNITY_FOLLOWUP_FEEDBACK; + } + + public static String getPartnerRegistrationForm() { + return Utils.getLocalForm(PARTNER_REGISTRATION_FORM, locale, assetManager); + } + + public static String getMotherChampionSbccForm() { + return MOTHER_CHAMPION_SBCC_FORM; + } + } public static final class Events { public static final String UPDATE_MALARIA_CONFIGURATION = "Update Malaria Confirmation"; public static final String MALARIA_CONFIRMATION = "malaria_confirmation"; + public static final String ANC_FIRST_FACILITY_VISIT = "ANC First Facility Visit"; + public static final String ANC_RECURRING_FACILITY_VISIT = "ANC Recurring Facility Visit"; + public static final String MOTHER_CHAMPION_FOLLOWUP = "Mother Champion Followup"; + public static final String CBHS_FOLLOWUP = "CBHS Followup"; + public static final String CBHS_CLOSE_VISITS = "CBHS Close Visits"; + public static final String AGYW_STRUCTURAL_SERVICES = "AGYW Structural Services"; + public static final String AGYW_BEHAVIORAL_SERVICES = "AGYW Behavioral Services"; + public static final String AGYW_BIO_MEDICAL_SERVICES = "AGYW Bio Medical Services"; + public static final String KVP_PREP_FOLLOWUP_VISIT = "Kvp PrEP Follow-up Visit"; + } + + public static final class ActionList { + public static final String PMTCT_FOLLOWUP_FEEDBACK = "Pmtct_followup_action"; + } + + public static class TableName { + public static final String MOTHER_CHAMPION_FOLLOWUP = "ec_mother_champion_followup"; + public static final String SBCC = "ec_sbcc"; + public static final String CBHS_REGISTER = "ec_cbhs_register"; + } + + public static class DBConstants{ + public static final String SBCC_DATE = "sbcc_date"; + } + + public interface PmtctFollowupFeedbackConstants { + String referralFormId = "community_referral_form_id"; + } + public static final class ReportConstants { + + public interface ReportTypes { + String CBHS_REPORT = "cbhs_report"; + String MOTHER_CHAMPION_REPORT = "mother_champion_report"; + String CONDOM_DISTRIBUTION_REPORT = "condom_distribution_report"; + String AGYW_REPORT = "agyw_report"; + } + + public interface CDPReportKeys { + String ISSUING_REPORTS = "issuing_reports"; + String RECEIVING_REPORTS = "receiving_reports"; + } + + public interface ReportPaths { + String CBHS_REPORT_PATH = "cbhs-taarifa-ya-mwezi"; + String MOTHER_CHAMPION_REPORT_PATH = "mother-champion-report"; + String CONDOM_DISTRIBUTION_ISSUING_REPORT_PATH = "condom-distribution-issuing-report"; + String CONDOM_DISTRIBUTION_RECEIVING_REPORT_PATH = "condom-distribution-receiving-report"; + } } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/HivstUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/HivstUtils.java new file mode 100644 index 0000000000..4b4e4baac5 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/HivstUtils.java @@ -0,0 +1,27 @@ +package org.smartregister.chw.util; + +import android.app.Activity; + +import com.vijay.jsonwizard.utils.FormUtils; + +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.chw.activity.ReferralRegistrationActivity; +import org.smartregister.chw.core.utils.CoreConstants; + +public class HivstUtils { + + public static void startHIVSTReferral(Activity context, String baseEntityId) { + JSONObject formJsonObject; + try { + formJsonObject = (new FormUtils()).getFormJsonFromRepositoryOrAssets(context, org.smartregister.chw.hivst.util.Constants.FORMS.HIVST_REFERRAL_FORM); + if (formJsonObject != null) { + formJsonObject.put(Constants.REFERRAL_TASK_FOCUS, CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST); + ReferralRegistrationActivity.startGeneralReferralFormActivityForResults(context, baseEntityId, formJsonObject, false); + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java index 3d0e7ab151..34935ab645 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java @@ -3,6 +3,7 @@ import android.content.Context; import android.util.Pair; +import com.nerdstone.neatformcore.domain.model.NFormViewData; import com.vijay.jsonwizard.constants.JsonFormConstants; import net.sqlcipher.database.SQLiteDatabase; @@ -557,7 +558,7 @@ public static String getCheckBoxValue(JSONObject jsonObject, String key) { int y = 0; while (optionSize > y) { JSONObject options = jaOptions.getJSONObject(y); - if (options.getBoolean(JsonFormConstants.VALUE)) { + if (options.has(JsonFormConstants.VALUE) && options.getBoolean(JsonFormConstants.VALUE)) { resBuilder.append(options.getString(JsonFormConstants.TEXT)).append(", "); } y++; @@ -609,6 +610,60 @@ public static void populatedJsonForm(@NotNull JSONObject jsonObject, @NotNull Ma } } + public static List getObsForNeatForm(HashMap detailsHashMap) { + ArrayList obs = new ArrayList<>(); + for (String key : detailsHashMap.keySet()) { + NFormViewData viewData = detailsHashMap.get(key); + Obs ob = new Obs(); + ob.setFormSubmissionField(key); + if (viewData.getMetadata() != null) { + if (viewData.getMetadata().containsKey(OPENMRS_ENTITY)) + ob.setFieldType(viewData.getMetadata().get(OPENMRS_ENTITY).toString()); + if (viewData.getMetadata().containsKey(OPENMRS_ENTITY_ID)) + ob.setFieldCode(viewData.getMetadata().get(OPENMRS_ENTITY_ID).toString()); + if (viewData.getMetadata().containsKey(OPENMRS_ENTITY_PARENT)) + ob.setParentCode(viewData.getMetadata().get(OPENMRS_ENTITY_PARENT).toString()); + } + if (viewData.getValue() instanceof HashMap) { + ArrayList humanReadableValues = new ArrayList<>(); + addHumanReadableValues(ob, humanReadableValues, (HashMap) viewData.getValue()); + if (humanReadableValues.size() > 0) + ob.setHumanReadableValues(humanReadableValues); + } else if (viewData.getValue() instanceof NFormViewData) { + ArrayList humanReadableValues = new ArrayList<>(); + saveValues((NFormViewData) viewData.getValue(), ob, humanReadableValues); + if (humanReadableValues.size() > 0) + ob.setHumanReadableValues(humanReadableValues); + } else { + ob.setValue(viewData.getValue()); + } + obs.add(ob); + } + return obs; + } + + private static void saveValues(NFormViewData optionsNFormViewData, Obs obs, ArrayList humanReadableValues) { + if (optionsNFormViewData.getMetadata() != null) { + if (optionsNFormViewData.getMetadata().containsKey(OPENMRS_ENTITY_ID)) { + obs.setValue(optionsNFormViewData.getMetadata().get(OPENMRS_ENTITY_ID).toString()); + humanReadableValues.add(optionsNFormViewData.getValue()); + } else { + obs.setValue(optionsNFormViewData.getValue()); + } + } + } + + private static void addHumanReadableValues(Obs obs, ArrayList humanReadableValues, HashMap valuesHashMap) { + for (Object key : valuesHashMap.keySet()) { + Object value = valuesHashMap.get(key); + if (value instanceof NFormViewData) { + saveValues((NFormViewData) value, obs, humanReadableValues); + } else { + obs.setValue(value); + } + } + } + public interface Flavor { JSONObject getAutoJsonEditMemberFormString(String title, String formName, Context context, CommonPersonObjectClient client, String eventType, String familyName, boolean isPrimaryCaregiver); @@ -616,3 +671,4 @@ public interface Flavor { } } + diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/KvpVisitUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/KvpVisitUtils.java new file mode 100644 index 0000000000..2e186ce768 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/KvpVisitUtils.java @@ -0,0 +1,45 @@ +package org.smartregister.chw.util; + +import android.content.Context; +import android.widget.Toast; + +import org.smartregister.chw.kvp.KvpLibrary; +import org.smartregister.chw.kvp.domain.Visit; +import org.smartregister.chw.kvp.repository.VisitDetailsRepository; +import org.smartregister.chw.kvp.repository.VisitRepository; +import org.smartregister.chw.kvp.util.Constants; +import org.smartregister.chw.kvp.util.VisitUtils; + +import java.util.ArrayList; +import java.util.List; + +import timber.log.Timber; + +public class KvpVisitUtils extends VisitUtils { + public static void processVisits(Context context) throws Exception { + processVisits(KvpLibrary.getInstance().visitRepository(), KvpLibrary.getInstance().visitDetailsRepository(), context); + } + + public static void processVisits(VisitRepository visitRepository, VisitDetailsRepository visitDetailsRepository, Context context) throws Exception { + + List visits = visitRepository.getAllUnSynced(); + List kvpFollowupVisits = new ArrayList<>(); + + for (Visit v : visits) { + + if (v.getVisitType().equalsIgnoreCase(Constants.EVENT_TYPE.KVP_PrEP_FOLLOW_UP_VISIT)) { + try { + kvpFollowupVisits.add(v); + } catch (Exception e) { + Timber.e(e); + } + } + } + + if (kvpFollowupVisits.size() > 0) { + processVisits(kvpFollowupVisits, visitRepository, visitDetailsRepository); + //TODO: Extract string resource and give a more descriptive text + Toast.makeText(context, "VISIT SAVED AND PROCESSED", Toast.LENGTH_SHORT).show(); + } + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/LocalContentWebViewClient.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/LocalContentWebViewClient.java new file mode 100644 index 0000000000..b4bd78f7d6 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/LocalContentWebViewClient.java @@ -0,0 +1,40 @@ +package org.smartregister.chw.util; + +import android.net.Uri; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebView; + +import org.smartregister.chw.activity.ChwReportsViewActivity; + +import androidx.annotation.RequiresApi; +import androidx.webkit.WebViewAssetLoader; +import androidx.webkit.WebViewClientCompat; + +public class LocalContentWebViewClient extends WebViewClientCompat { + private final WebViewAssetLoader mAssetLoader; + + public LocalContentWebViewClient(WebViewAssetLoader assetLoader) { + mAssetLoader = assetLoader; + } + + @Override + @RequiresApi(21) + public WebResourceResponse shouldInterceptRequest(WebView view, + WebResourceRequest request) { + return mAssetLoader.shouldInterceptRequest(request.getUrl()); + } + + @Override + @SuppressWarnings("deprecation") // to support API < 21 + public WebResourceResponse shouldInterceptRequest(WebView view, + String url) { + return mAssetLoader.shouldInterceptRequest(Uri.parse(url)); + } + + @Override + public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + ChwReportsViewActivity.printWebView = view; + } +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/ReportUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/ReportUtils.java new file mode 100644 index 0000000000..888a39ea3a --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/ReportUtils.java @@ -0,0 +1,183 @@ +package org.smartregister.chw.util; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.os.Build; +import android.print.PrintAttributes; +import android.print.PrintDocumentAdapter; +import android.print.PrintManager; +import android.webkit.WebSettings; +import android.webkit.WebView; + +import org.apache.commons.lang3.StringUtils; +import org.json.JSONException; +import org.smartregister.chw.domain.agyw_reports.AGYWReportObject; +import org.smartregister.chw.domain.cbhs_reports.CbhsMonthlyReportObject; +import org.smartregister.chw.domain.cdp_reports.CdpIssuingReportObject; +import org.smartregister.chw.domain.cdp_reports.CdpReceivingReportObject; +import org.smartregister.chw.domain.mother_champion_report.MotherChampionReportObject; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +import androidx.annotation.RequiresApi; +import androidx.webkit.WebViewAssetLoader; +import timber.log.Timber; + +public class ReportUtils { + private static final int year = Calendar.getInstance().get(Calendar.YEAR); + private static final int month = Calendar.getInstance().get(Calendar.MONTH) + 1; + public static String[] monthNames = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}; + private static String printJobName; + private static String reportPeriod; + + public static String getDefaultReportPeriod() { + String monthString = String.valueOf(month); + if (month < 10) { + monthString = "0" + monthString; + } + return monthString + "-" + year; + } + + public static int getMonth() { + return month; + } + + public static int getYear() { + return year; + } + + public static String displayMonthAndYear(int month, int year) { + return monthNames[month] + ", " + year; + } + + public static String displayMonthAndYear() { + return monthNames[getMonth() - 1] + ", " + getYear(); + } + + public static String getPrintJobName() { + return printJobName; + } + + public static void setPrintJobName(String printJobName) { + ReportUtils.printJobName = printJobName; + } + + public static Date getReportDate() { + if (StringUtils.isNotBlank(reportPeriod)) { + try { + return new SimpleDateFormat("MM-yyyy", Locale.getDefault()).parse(reportPeriod); + } catch (ParseException e) { + Timber.e(e); + } + } + + return new Date(); + } + + public static String getReportPeriod() { + return reportPeriod; + } + + public static void setReportPeriod(String reportPeriod) { + ReportUtils.reportPeriod = reportPeriod; + } + + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + public static void printTheWebPage(WebView webView, Context context) { + + // Creating PrintManager instance + PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE); + PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(getPrintJobName()); + + // Create a print job with name and adapter instance + assert printManager != null; + printManager.print(getPrintJobName(), printAdapter, + new PrintAttributes.Builder().build()); + } + + @SuppressLint("SetJavaScriptEnabled") + public static void loadReportView(String reportPath, WebView mWebView, Context context, String reportType) { + + WebSettings webSettings = mWebView.getSettings(); + webSettings.setJavaScriptEnabled(true); + final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder() + .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(context)) + .build(); + mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader)); + mWebView.addJavascriptInterface(new ChwWebAppInterface(context, reportType), "Android"); + + if (reportType.equals(Constants.ReportConstants.ReportTypes.CONDOM_DISTRIBUTION_REPORT)){ + mWebView.loadUrl("https://appassets.androidplatform.net/assets/reports/cdp_reports/" + reportPath + ".html"); + }else { + mWebView.loadUrl("https://appassets.androidplatform.net/assets/reports/" + reportPath + ".html"); + } + + } + + + public static class CBHSReport { + public static String computeReport(Date now, Context context) { + String report = ""; + CbhsMonthlyReportObject cbhsMonthlyReportObject = new CbhsMonthlyReportObject(now, context); + try { + report = cbhsMonthlyReportObject.getIndicatorDataAsGson(cbhsMonthlyReportObject.getIndicatorData()); + } catch (Exception e) { + Timber.e(e); + } + return report; + } + } + + public static class MotherChampionReport { + public static String computeReport(Date now) { + String report = ""; + MotherChampionReportObject motherChampionReportObject = new MotherChampionReportObject(now); + try { + report = motherChampionReportObject.getIndicatorDataAsGson(motherChampionReportObject.getIndicatorData()); + } catch (Exception e) { + Timber.e(e); + } + return report; + } + } + + public static class CDPReports { + public static String computeIssuingReports(Date startDate) { + CdpIssuingReportObject cdpIssuingReportObject = new CdpIssuingReportObject(startDate); + try { + return cdpIssuingReportObject.getIndicatorDataAsGson(cdpIssuingReportObject.getIndicatorData()); + } catch (JSONException e) { + Timber.e(e); + } + return ""; + } + + public static String computeReceivingReports(Date now) { + String report = ""; + CdpReceivingReportObject cdpReceivingReportObject = new CdpReceivingReportObject(now); + try { + report = cdpReceivingReportObject.getIndicatorDataAsGson(cdpReceivingReportObject.getIndicatorData()); + } catch (Exception e) { + Timber.e(e); + } + return report; + } + } + + public static class AGYWReport { + public static String computeReport(Date now) { + String report = ""; + AGYWReportObject agywReportObject = new AGYWReportObject(now); + try { + report = agywReportObject.getIndicatorDataAsGson(agywReportObject.getIndicatorData()); + } catch (Exception e) { + Timber.e(e); + } + return report; + } + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/Utils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/Utils.java index b0e33d4b46..123c48a8d8 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/Utils.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/Utils.java @@ -1,29 +1,47 @@ package org.smartregister.chw.util; import android.app.Activity; +import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; +import android.util.Pair; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.bottomnavigation.LabelVisibilityMode; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.Triple; import org.jetbrains.annotations.NotNull; +import org.json.JSONArray; +import org.json.JSONObject; import org.smartregister.chw.BuildConfig; import org.smartregister.chw.R; import org.smartregister.chw.activity.ClientReferralActivity; import org.smartregister.chw.application.ChwApplication; import org.smartregister.chw.core.utils.CoreConstants; +import org.smartregister.chw.core.utils.CoreJsonFormUtils; import org.smartregister.chw.model.ReferralTypeModel; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.commonregistry.AllCommonsRepository; +import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.commonregistry.CommonRepository; +import org.smartregister.domain.Client; +import org.smartregister.domain.db.EventClient; +import org.smartregister.family.FamilyLibrary; +import org.smartregister.family.util.DBConstants; import org.smartregister.growthmonitoring.domain.ZScore; import org.smartregister.growthmonitoring.repository.WeightForHeightRepository; import org.smartregister.helper.BottomNavigationHelper; +import org.smartregister.repository.BaseRepository; +import org.smartregister.sync.helper.ECSyncHelper; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Locale; public class Utils extends org.smartregister.chw.core.utils.Utils { @@ -38,21 +56,20 @@ public static void launchClientReferralActivity(Activity activity, List getCommonReferralTypes(Activity activity) { + public static List getCommonReferralTypes(Activity activity, String baseEntityId) { + CommonPersonObjectClient client = Utils.getCommonPersonObjectClient(baseEntityId); + String gender = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.GENDER, false); + List referralTypeModels = new ArrayList<>(); if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) { - - referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.suspected_malaria), - Constants.JSON_FORM.getMalariaReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_MALARIA)); - - referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.hiv_referral), - Constants.JSON_FORM.getHivReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_HIV)); - - referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.tb_referral), - Constants.JSON_FORM.getTbReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_TB)); - referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.gbv_referral), Constants.JSON_FORM.getGbvReferralForm(), CoreConstants.TASKS_FOCUS.SUSPECTED_GBV)); + referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.hts_referral), + CoreConstants.JSON_FORM.getHtsReferralForm(), CoreConstants.TASKS_FOCUS.CONVENTIONAL_HIV_TEST)); + if (gender.equalsIgnoreCase("Female") && isMemberOfReproductiveAge(client, 10, 49)) { + referralTypeModels.add(new ReferralTypeModel(activity.getString(R.string.pregnancy_confirmation_referral), + CoreConstants.JSON_FORM.getPregnancyConfirmationReferralForm(), CoreConstants.TASKS_FOCUS.PREGNANCY_CONFIRMATION)); + } } return referralTypeModels; } @@ -125,4 +142,114 @@ public static String getClientName(String firstName, String middleName, String l } + public static String getClientGender(String baseEntityId) { + CommonRepository commonRepository = org.smartregister.family.util.Utils.context().commonrepository(org.smartregister.family.util.Utils.metadata().familyMemberRegister.tableName); + + final CommonPersonObject commonPersonObject = commonRepository.findByBaseEntityId(baseEntityId); + final CommonPersonObjectClient client = new CommonPersonObjectClient(commonPersonObject.getCaseId(), commonPersonObject.getDetails(), ""); + client.setColumnmaps(commonPersonObject.getColumnmaps()); + return org.smartregister.family.util.Utils.getValue(commonPersonObject.getColumnmaps(), org.smartregister.family.util.DBConstants.KEY.GENDER, false); + } + + /* + * For CBHS Registration + */ + public static void updateAgeAndGender(JSONArray fields, int age, String gender) throws Exception { + boolean foundAge = false; + boolean foundGender = false; + for (int i = 0; i < fields.length(); i++) { + JSONObject field = fields.getJSONObject(i); + if (field.getString("name").equals("age")) { + field.getJSONObject("properties").put("text", String.valueOf(age)); + foundAge = true; + } + if (field.getString("name").equals("gender")) { + field.getJSONObject("properties").put("text", gender); + foundGender = true; + } + if (foundAge && foundGender) { + return; + } + } + } + + + /** + * Removes a user, used for removing clients marked as Deceased + * + * @param familyID + * @param closeFormJsonString + * @param providerId + * @return + * @throws Exception + */ + public static String removeUser(String familyID, JSONObject closeFormJsonString, String providerId) throws Exception { + String res = null; + Triple, String, List> triple = CoreJsonFormUtils.processRemoveMemberEvent(familyID, org.smartregister.family.util.Utils.getAllSharedPreferences(), closeFormJsonString, providerId); + if (triple != null && triple.getLeft() != null) { + processEvents(triple.getRight()); + + if (triple.getLeft().second.equalsIgnoreCase(CoreConstants.EventType.REMOVE_CHILD)) { + updateRepo(triple, org.smartregister.family.util.Utils.metadata().familyMemberRegister.tableName); + updateRepo(triple, CoreConstants.TABLE_NAME.CHILD); + } else if (triple.getLeft().second.equalsIgnoreCase(CoreConstants.EventType.REMOVE_FAMILY)) { + updateRepo(triple, org.smartregister.family.util.Utils.metadata().familyRegister.tableName); + } else { + updateRepo(triple, org.smartregister.family.util.Utils.metadata().familyMemberRegister.tableName); + } + res = triple.getLeft().second; + } + + long lastSyncTimeStamp = getAllSharedPreferences().fetchLastUpdatedAtDate(0); + Date lastSyncDate = new Date(lastSyncTimeStamp); + FamilyLibrary.getInstance().getClientProcessorForJava().processClient(FamilyLibrary.getInstance().getEcSyncHelper().getEvents(lastSyncDate, BaseRepository.TYPE_Unprocessed)); + getAllSharedPreferences().saveLastUpdatedAtDate(lastSyncDate.getTime()); + return res; + } + + private static void processEvents(List events) throws Exception { + ECSyncHelper syncHelper = ChwApplication.getInstance().getEcSyncHelper(); + List clients = new ArrayList<>(); + for (Event e : events) { + JSONObject json = new JSONObject(CoreJsonFormUtils.gson.toJson(e)); + syncHelper.addEvent(e.getBaseEntityId(), json); + + org.smartregister.domain.Event event = CoreJsonFormUtils.gson.fromJson(json.toString(), org.smartregister.domain.Event.class); + clients.add(new EventClient(event, new Client(e.getBaseEntityId()))); + } + FamilyLibrary.getInstance().getClientProcessorForJava().processClient(clients); + } + + private static void updateRepo(Triple, String, List> triple, String tableName) { + AllCommonsRepository commonsRepository = ChwApplication.getInstance().getAllCommonsRepository(tableName); + + Date date_removed = new Date(); + Date dod = null; + if (triple.getLeft() != null && triple.getLeft().first != null) { + dod = triple.getLeft().first; + } + + if (commonsRepository != null && dod == null) { + ContentValues values = new ContentValues(); + values.put(DBConstants.KEY.DATE_REMOVED, getDBFormatedDate(date_removed)); + commonsRepository.update(tableName, values, triple.getMiddle()); + commonsRepository.updateSearch(triple.getMiddle()); + commonsRepository.close(triple.getMiddle()); + } + + // enter the date of death + if (dod != null && commonsRepository != null) { + ContentValues values = new ContentValues(); + values.put(DBConstants.KEY.DOD, getDBFormatedDate(dod)); + commonsRepository.update(tableName, values, triple.getMiddle()); + commonsRepository.updateSearch(triple.getMiddle()); + } + + } + + private static String getDBFormatedDate(Date date) { + return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(date); + } + + } diff --git a/opensrp-chw/src/main/res/drawable-hdpi/childrow_history.png b/opensrp-chw/src/main/res/drawable-hdpi/childrow_history.png deleted file mode 100644 index c299965562..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-hdpi/childrow_history.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-hdpi/childrow_upcoming.png b/opensrp-chw/src/main/res/drawable-hdpi/childrow_upcoming.png deleted file mode 100644 index cb8dfcbef1..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-hdpi/childrow_upcoming.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-hdpi/ic_logo_ba.png b/opensrp-chw/src/main/res/drawable-hdpi/ic_logo_ba.png new file mode 100644 index 0000000000..c075e49c19 Binary files /dev/null and b/opensrp-chw/src/main/res/drawable-hdpi/ic_logo_ba.png differ diff --git a/opensrp-chw/src/main/res/drawable-hdpi/reports_bg_blue_green.xml b/opensrp-chw/src/main/res/drawable-hdpi/reports_bg_blue_green.xml new file mode 100644 index 0000000000..0d8df80878 --- /dev/null +++ b/opensrp-chw/src/main/res/drawable-hdpi/reports_bg_blue_green.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/drawable-mdpi/childrow_history.png b/opensrp-chw/src/main/res/drawable-mdpi/childrow_history.png deleted file mode 100644 index e44560deee..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-mdpi/childrow_history.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-mdpi/childrow_upcoming.png b/opensrp-chw/src/main/res/drawable-mdpi/childrow_upcoming.png deleted file mode 100644 index 032241d662..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-mdpi/childrow_upcoming.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-xhdpi/childrow_history.png b/opensrp-chw/src/main/res/drawable-xhdpi/childrow_history.png deleted file mode 100644 index 9b2913ab7a..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-xhdpi/childrow_history.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-xhdpi/childrow_upcoming.png b/opensrp-chw/src/main/res/drawable-xhdpi/childrow_upcoming.png deleted file mode 100644 index 013648df7c..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-xhdpi/childrow_upcoming.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_history.png b/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_history.png deleted file mode 100644 index ce6c831870..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_history.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_upcoming.png b/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_upcoming.png deleted file mode 100644 index 72ba3b982f..0000000000 Binary files a/opensrp-chw/src/main/res/drawable-xxhdpi/childrow_upcoming.png and /dev/null differ diff --git a/opensrp-chw/src/main/res/drawable/contact_phone_collection.png b/opensrp-chw/src/main/res/drawable/contact_phone_collection.png new file mode 100644 index 0000000000..56f207d751 Binary files /dev/null and b/opensrp-chw/src/main/res/drawable/contact_phone_collection.png differ diff --git a/opensrp-chw/src/main/res/drawable/ic_add_white_24.xml b/opensrp-chw/src/main/res/drawable/ic_add_white_24.xml new file mode 100644 index 0000000000..70046c48fe --- /dev/null +++ b/opensrp-chw/src/main/res/drawable/ic_add_white_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/opensrp-chw/src/main/res/drawable/ic_baseline_save_alt_24.xml b/opensrp-chw/src/main/res/drawable/ic_baseline_save_alt_24.xml new file mode 100644 index 0000000000..ddb9d4df50 --- /dev/null +++ b/opensrp-chw/src/main/res/drawable/ic_baseline_save_alt_24.xml @@ -0,0 +1,5 @@ + + + diff --git a/opensrp-chw/src/main/res/drawable/ic_cbhs_summary.xml b/opensrp-chw/src/main/res/drawable/ic_cbhs_summary.xml new file mode 100644 index 0000000000..03d8eee8e7 --- /dev/null +++ b/opensrp-chw/src/main/res/drawable/ic_cbhs_summary.xml @@ -0,0 +1,10 @@ + + + diff --git a/opensrp-chw/src/main/res/drawable/ic_logo_ba.png b/opensrp-chw/src/main/res/drawable/ic_logo_ba.png new file mode 100644 index 0000000000..c075e49c19 Binary files /dev/null and b/opensrp-chw/src/main/res/drawable/ic_logo_ba.png differ diff --git a/opensrp-chw/src/main/res/drawable/record_btn_selector.xml b/opensrp-chw/src/main/res/drawable/record_btn_selector.xml index da1eb87bfd..2e83558ca1 100644 --- a/opensrp-chw/src/main/res/drawable/record_btn_selector.xml +++ b/opensrp-chw/src/main/res/drawable/record_btn_selector.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/drawable/record_btn_selector_above_twentyfr.xml b/opensrp-chw/src/main/res/drawable/record_btn_selector_above_twentyfr.xml index f9b917cc3e..24834b15c0 100644 --- a/opensrp-chw/src/main/res/drawable/record_btn_selector_above_twentyfr.xml +++ b/opensrp-chw/src/main/res/drawable/record_btn_selector_above_twentyfr.xml @@ -2,7 +2,7 @@ - + diff --git a/opensrp-chw/src/main/res/drawable/reports_bg_blue.xml b/opensrp-chw/src/main/res/drawable/reports_bg_blue.xml new file mode 100644 index 0000000000..15e178e9cc --- /dev/null +++ b/opensrp-chw/src/main/res/drawable/reports_bg_blue.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/drawable/reports_bg_green.xml b/opensrp-chw/src/main/res/drawable/reports_bg_green.xml new file mode 100644 index 0000000000..822d00c2bc --- /dev/null +++ b/opensrp-chw/src/main/res/drawable/reports_bg_green.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/drawable/visit_btn_selector.xml b/opensrp-chw/src/main/res/drawable/visit_btn_selector.xml index cc14d2f2a9..2e0abbdf57 100644 --- a/opensrp-chw/src/main/res/drawable/visit_btn_selector.xml +++ b/opensrp-chw/src/main/res/drawable/visit_btn_selector.xml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_all_clients_member_profile.xml b/opensrp-chw/src/main/res/layout/activity_all_clients_member_profile.xml deleted file mode 100644 index ffdc23ebe0..0000000000 --- a/opensrp-chw/src/main/res/layout/activity_all_clients_member_profile.xml +++ /dev/null @@ -1,245 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_all_male_clients.xml b/opensrp-chw/src/main/res/layout/activity_all_male_clients.xml new file mode 100644 index 0000000000..8da7a2b341 --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_all_male_clients.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/opensrp-chw/src/main/res/layout/activity_anc_member_map.xml b/opensrp-chw/src/main/res/layout/activity_anc_member_map.xml index ed22ecbe84..533bdf92f8 100644 --- a/opensrp-chw/src/main/res/layout/activity_anc_member_map.xml +++ b/opensrp-chw/src/main/res/layout/activity_anc_member_map.xml @@ -39,6 +39,7 @@ android:text="GA: 10 weeks" android:textAppearance="@style/TextAppearance.AppCompat.Small" android:textColor="@android:color/black" + android:visibility="gone" android:textSize="@dimen/register_member_village_size" /> + android:textColor="@android:color/black" + android:visibility="gone" /> + android:textSize="@dimen/register_member_village_size" + android:visibility="gone" /> @@ -83,7 +87,8 @@ android:text="ID:123456" android:textAppearance="@style/TextAppearance.AppCompat.Small" android:textColor="@android:color/black" - android:textSize="@dimen/register_member_village_size" /> + android:textSize="@dimen/register_member_village_size" + android:visibility="gone" /> diff --git a/opensrp-chw/src/main/res/layout/activity_cbhs_reports.xml b/opensrp-chw/src/main/res/layout/activity_cbhs_reports.xml new file mode 100644 index 0000000000..27f5642b4c --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_cbhs_reports.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_cdp_reports.xml b/opensrp-chw/src/main/res/layout/activity_cdp_reports.xml new file mode 100644 index 0000000000..3af8f6b6bd --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_cdp_reports.xml @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_in_app_reports.xml b/opensrp-chw/src/main/res/layout/activity_in_app_reports.xml new file mode 100644 index 0000000000..6930f94afe --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_in_app_reports.xml @@ -0,0 +1,298 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_login.xml b/opensrp-chw/src/main/res/layout/activity_login.xml index 25bf784834..de39d187da 100644 --- a/opensrp-chw/src/main/res/layout/activity_login.xml +++ b/opensrp-chw/src/main/res/layout/activity_login.xml @@ -34,7 +34,7 @@ android:layout_weight="1" android:contentDescription="@string/logo" android:scaleType="fitCenter" - android:src="@drawable/ic_logo" /> + android:src="@drawable/ic_logo_ba" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/opensrp-chw/src/main/res/layout/activity_pmtctc_details.xml b/opensrp-chw/src/main/res/layout/activity_pmtctc_details.xml new file mode 100644 index 0000000000..716de0aa28 --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_pmtctc_details.xml @@ -0,0 +1,487 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/opensrp-chw/src/main/res/layout/activity_reports_view.xml b/opensrp-chw/src/main/res/layout/activity_reports_view.xml new file mode 100644 index 0000000000..335144251f --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_reports_view.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/opensrp-chw/src/main/res/layout/activity_request_call_phone_permission.xml b/opensrp-chw/src/main/res/layout/activity_request_call_phone_permission.xml new file mode 100644 index 0000000000..cc4e7f60db --- /dev/null +++ b/opensrp-chw/src/main/res/layout/activity_request_call_phone_permission.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + +