diff --git a/opensrp-reveal/build.gradle b/opensrp-reveal/build.gradle index 9225203fef..4006b43103 100644 --- a/opensrp-reveal/build.gradle +++ b/opensrp-reveal/build.gradle @@ -8,6 +8,7 @@ buildscript { classpath 'com.android.tools.build:gradle:4.0.0' classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.8.3' classpath 'io.fabric.tools:gradle:1.31.2' + classpath 'org.smartregister:gradle-jarjar-plugin:1.0.0-SNAPSHOT' } } @@ -25,6 +26,7 @@ apply plugin: 'com.android.application' apply plugin: 'jacoco' apply plugin: 'com.github.kt3k.coveralls' apply plugin: 'io.fabric' +apply plugin: 'org.smartregister.gradle.jarjar' jacoco { toolVersion = "0.8.0" @@ -45,8 +47,8 @@ android { applicationId "org.smartregister.reveal" minSdkVersion 18 targetSdkVersion 28 - versionCode 21 - versionName "4.0.1" + versionCode 22 + versionName "5.0.0-RC1" multiDexEnabled true buildConfigField "long", "MAX_SERVER_TIME_DIFFERENCE", "1800000l" buildConfigField "boolean", "TIME_CHECK", "false" @@ -58,6 +60,7 @@ android { javaCompileOptions { annotationProcessorOptions { arguments = [eventBusIndex: 'org.smartregister.reveal.RevelEventBusIndex'] + includeCompileClasspath = true } } @@ -79,12 +82,29 @@ android { println("Digital Globe config variables is not set in your local.properties") buildConfigField "String", "DG_CONNECT_ID", "\"sample_key\"" } + + if (properties != null && properties.containsKey("oauth.client.id")) { + + buildConfigField "String", "OAUTH_CLIENT_ID", properties["oauth.client.id"] + + } else { + project.logger.error("oauth.client.id variable is not set in your local.properties") + } + + if (properties != null && properties.containsKey("oauth.client.secret")) { + + buildConfigField "String", "OAUTH_CLIENT_SECRET", properties["oauth.client.secret"] + + } else { + project.logger.error("oauth.client.secret variable is not set in your local.properties") + } } else { println("local.properties does not exist") buildConfigField "String", "MAPBOX_SDK_ACCESS_TOKEN", "\"sample_key\"" buildConfigField "String", "DG_CONNECT_ID", "\"sample_key\"" } } + dexOptions { javaMaxHeapSize "4g" } @@ -123,11 +143,11 @@ android { buildConfigField "int", "OPENMRS_UNIQUE_ID_BATCH_SIZE", '100' buildConfigField "int", "OPENMRS_UNIQUE_ID_SOURCE", '2' buildConfigField "long", "SYNC_INTERVAL_IN_MINUTES", '15' - buildConfigField "org.smartregister.reveal.util.Country", "BUILD_COUNTRY", "org.smartregister.reveal.util.Country.THAILAND_EN" + buildConfigField "org.smartregister.reveal.util.Country", "BUILD_COUNTRY", "org.smartregister.reveal.util.Country.REFAPP" buildConfigField "long", "PULL_UNIQUE_IDS_MINUTES", '15' buildConfigField "String", "ADMIN_PASSWORD_NOT_NEAR_STRUCTURES", '"AdminPass1"' buildConfigField "float", "MY_LOCATION_BUFFER", '25' - buildConfigField "boolean", "VALIDATE_FAR_STRUCTURES", 'true' + buildConfigField "boolean", "VALIDATE_FAR_STRUCTURES", 'false' buildConfigField "int", "RESOLVE_LOCATION_TIMEOUT_IN_SECONDS", '60' buildConfigField "boolean", "DISPLAY_OUTSIDE_OPERATIONAL_AREA_MASK", 'false' buildConfigField "boolean", "DISPLAY_DISTANCE_SCALE", 'true' @@ -141,6 +161,8 @@ android { packagingOptions { exclude 'META-INF/*' exclude 'LICENSE.txt' + exclude("META-INF/*.kotlin_module") + exclude "META-INF/DEPENDENCIES" } @@ -167,7 +189,7 @@ dependencies { exclude group: 'stax', module: 'stax-api' } - implementation('org.smartregister:opensrp-client-core:1.13.0-SNAPSHOT@aar') { + implementation('org.smartregister:opensrp-client-core:2.0.0-SNAPSHOT@aar') { transitive = true exclude group: 'com.google.guava', module: 'guava' exclude group: 'com.android.support', module: 'appcompat-v7' @@ -176,10 +198,10 @@ dependencies { exclude group: 'com.github.ybq', module: 'Android-SpinKit' exclude group: 'com.github.bmelnychuk', module: 'atv' exclude group: 'com.google.android.gms', module: 'play-services-vision' - exclude group: 'com.ibm.fhir', module:'fhir-model' + exclude group: 'com.ibm.fhir', module: 'fhir-model' } - testImplementation 'com.ibm.fhir:fhir-model:4.2.3' + jarJar 'com.ibm.fhir:fhir-model:4.2.3' implementation('org.smartregister:opensrp-client-configurable-views:1.1.5-SNAPSHOT@aar') { transitive = true @@ -214,6 +236,13 @@ dependencies { exclude group: 'com.android.support', module: 'appcompat-v7' } + implementation ('org.smartregister:opensrp-client-tasking:0.0.3-SNAPSHOT') { + transitive = true + exclude group: 'org.smartregister', module: 'opensrp-client-core' + exclude group: 'com.ibm.fhir', module: 'fhir-model' + exclude group: 'io.ona.kujaku', module: 'library' + } + implementation 'com.google.android:flexbox:1.0.0' implementation 'com.google.android.material:material:1.0.0' @@ -226,8 +255,10 @@ dependencies { implementation 'com.github.ybq:Android-SpinKit:1.2.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-scalebar-v8:0.3.0' - testImplementation 'junit:junit:4.12' - testImplementation group: 'org.hamcrest', name: 'hamcrest-core', version: '2.2' + // Repackaged jars will be placed here, adding them to classpath + implementation fileTree(dir: "./build/libs", include: ['*.jar']) + + testImplementation 'junit:junit:4.13' testImplementation 'org.apache.maven:maven-ant-tasks:2.1.3' testImplementation('com.squareup:fest-android:1.0.8') { exclude module: 'support-v4' } implementation 'com.mapbox.mapboxsdk:mapbox-sdk-turf:5.1.0' @@ -280,3 +311,10 @@ task javadoc(type: Javadoc) { classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) classpath += configurations.compile } + + +jarJar { + + // Dependencies and related JarJar rules + remove = ['fhir-model-4.2.3.jar': 'com.ibm.fhir.model.visitor.CopyingVisitor*'] +} \ No newline at end of file diff --git a/opensrp-reveal/src/main/AndroidManifest.xml b/opensrp-reveal/src/main/AndroidManifest.xml index dacb7ee5ac..ac367cdd51 100644 --- a/opensrp-reveal/src/main/AndroidManifest.xml +++ b/opensrp-reveal/src/main/AndroidManifest.xml @@ -83,12 +83,12 @@ - - - - + + diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/activity/RevealJsonFormActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/activity/RevealJsonFormActivity.java index 0c8c15294b..69e78f1dcf 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/activity/RevealJsonFormActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/activity/RevealJsonFormActivity.java @@ -12,15 +12,15 @@ import com.vijay.jsonwizard.constants.JsonFormConstants; import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationView; import org.smartregister.reveal.fragment.RevealJsonFormFragment; +import org.smartregister.tasking.contract.UserLocationContract; import io.ona.kujaku.utils.Constants; /** * Created by samuelgithengi on 12/13/18. */ -public class RevealJsonFormActivity extends FormConfigurationJsonFormActivity implements UserLocationView { +public class RevealJsonFormActivity extends FormConfigurationJsonFormActivity implements UserLocationContract.UserLocationView { private RevealJsonFormFragment formFragment; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/AvailableOfflineMapAdapter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/AvailableOfflineMapAdapter.java deleted file mode 100644 index 8f948966c3..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/AvailableOfflineMapAdapter.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.smartregister.reveal.adapter; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.viewholder.AvailableOfflineMapViewHolder; - -import java.util.ArrayList; -import java.util.List; - -public class AvailableOfflineMapAdapter extends RecyclerView.Adapter { - - private Context context; - - private View.OnClickListener offlineMapClickHandler; - - private List offlineMapModels; - - public AvailableOfflineMapAdapter(Context context, View.OnClickListener offlineMapClickHandler) { - this.context = context; - this.offlineMapClickHandler = offlineMapClickHandler; - this.offlineMapModels = new ArrayList<>(); - } - - - @NonNull - @Override - public AvailableOfflineMapViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { - View view = LayoutInflater.from(context).inflate(R.layout.offline_map_row, parent, false); - return new AvailableOfflineMapViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull AvailableOfflineMapViewHolder viewHolder, int position) { - OfflineMapModel offlineMapModel = offlineMapModels.get(position); - viewHolder.setOfflineMapLabel(offlineMapModel.getDownloadAreaLabel()); - viewHolder.setItemViewListener(offlineMapModel, offlineMapClickHandler); - - switch (offlineMapModel.getOfflineMapStatus()) { - case READY: - viewHolder.enableCheckBox(true); - viewHolder.displayDownloadingLabel(false); - viewHolder.checkCheckBox(false); - break; - case DOWNLOAD_STARTED: - viewHolder.enableCheckBox(false); - viewHolder.displayDownloadingLabel(true); - viewHolder.checkCheckBox(true); - break; - case SELECTED_FOR_DOWNLOAD: - viewHolder.enableCheckBox(true); - viewHolder.checkCheckBox(true); - viewHolder.displayDownloadingLabel(false); - break; - default: - break; - - } - - } - - @Override - public int getItemCount() { - return offlineMapModels.size(); - } - - public void setOfflineMapModels(List offlineMapModels) { - this.offlineMapModels = offlineMapModels; - notifyDataSetChanged(); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/DownloadedOfflineMapAdapter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/DownloadedOfflineMapAdapter.java deleted file mode 100644 index a46f4ae17e..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/DownloadedOfflineMapAdapter.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.smartregister.reveal.adapter; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import android.text.format.Formatter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; -import com.mapbox.mapboxsdk.offline.OfflineRegionStatus; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.util.Utils; -import org.smartregister.reveal.viewholder.DownloadedOfflineMapViewHolder; - -import java.util.ArrayList; -import java.util.List; - -public class DownloadedOfflineMapAdapter extends RecyclerView.Adapter { - - private Context context; - - private View.OnClickListener offlineMapClickHandler; - - private List offlineMapModels = new ArrayList<>(); - - public DownloadedOfflineMapAdapter(Context context, View.OnClickListener offlineMapClickHandler) { - this.context = context; - this.offlineMapClickHandler = offlineMapClickHandler; - - } - - @NonNull - @Override - public DownloadedOfflineMapViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) { - View view = LayoutInflater.from(context).inflate(R.layout.offline_map_row, parent, false); - return new DownloadedOfflineMapViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull DownloadedOfflineMapViewHolder viewHolder, int position) { - OfflineMapModel offlineMapModel = offlineMapModels.get(position); - viewHolder.setOfflineMapLabel(offlineMapModel.getDownloadAreaLabel()); - viewHolder.setItemViewListener(offlineMapModel, offlineMapClickHandler); - - switch (offlineMapModel.getOfflineMapStatus()) { - case READY: - case DOWNLOADED: - viewHolder.checkCheckBox(false); - break; - default: - break; - - } - - displayOfflineMapSize(offlineMapModel, viewHolder); - - } - - private void displayOfflineMapSize(OfflineMapModel offlineMapModel, DownloadedOfflineMapViewHolder viewHolder ) { - if (offlineMapModel == null || offlineMapModel.getOfflineRegion() == null) { - return; - } - - offlineMapModel.getOfflineRegion().getStatus(new OfflineRegion.OfflineRegionStatusCallback() { - @Override - public void onStatus(OfflineRegionStatus status) { - - viewHolder.displayDownloadSizeLabel(true); - - String mapDownloadSize = Formatter.formatFileSize(context, status.getCompletedResourceSize()); - String downloadDate = Utils.formatDate(offlineMapModel.getDateCreated()); - - viewHolder.setDownloadedMapSize(context.getString(R.string.offline_map_size, mapDownloadSize, downloadDate)); - - } - - @Override - public void onError(String error) { - // Do nothing - } - }); - - } - - @Override - public int getItemCount() { - return offlineMapModels.size(); - } - - public void setOfflineMapModels(List offlineMapModels) { - this.offlineMapModels = offlineMapModels; - notifyDataSetChanged(); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/TaskRegisterAdapter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/TaskRegisterAdapter.java deleted file mode 100644 index 8e4ce6e261..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/adapter/TaskRegisterAdapter.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.smartregister.reveal.adapter; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import org.apache.commons.lang3.StringUtils; -import org.smartregister.domain.Task; -import org.smartregister.reveal.R; -import org.smartregister.reveal.model.CardDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.util.CardDetailsUtil; -import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.viewholder.TaskRegisterViewHolder; - -import java.util.ArrayList; -import java.util.List; - -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_ELIGIBLE; - -/** - * Created by samuelgithengi on 3/20/19. - */ -public class TaskRegisterAdapter extends RecyclerView.Adapter { - - private List taskDetails = new ArrayList<>(); - - private Context context; - - private View.OnClickListener registerActionHandler; - - public TaskRegisterAdapter(Context context, View.OnClickListener registerActionHandler) { - this.context = context; - this.registerActionHandler = registerActionHandler; - } - - @NonNull - @Override - public TaskRegisterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { - View view = LayoutInflater.from(context).inflate(R.layout.task_register_row, parent, false); - return new TaskRegisterViewHolder(view); - } - - @Override - public void onBindViewHolder(@NonNull TaskRegisterViewHolder viewHolder, int position) { - TaskDetails task = taskDetails.get(position); - Float distance = task.getDistanceFromUser(); - String name = task.getStructureName(); - String action = null; - boolean hasIcon = false; - if (Intervention.IRS.equals(task.getTaskCode())) { - if (name == null) { - name = task.getFamilyName() != null ? task.getFamilyName() : task.getStructureName() != null ? task.getStructureName() : context.getString(R.string.unenumerated_structure); - } - action = context.getString(R.string.record_status); - } else if (Intervention.MOSQUITO_COLLECTION.equals(task.getTaskCode())) { - name = context.getString(R.string.mosquito_collection_point); - action = context.getString(R.string.record_mosquito_collection); - } else if (Intervention.LARVAL_DIPPING.equals(task.getTaskCode())) { - name = context.getString(R.string.larval_breeding_site); - action = context.getString(R.string.record_larvacide); - } else if (Intervention.BCC.equals(task.getTaskCode())) { - viewHolder.setIcon(R.drawable.ic_bcc); - name = context.getString(R.string.bcc); - action = context.getString(R.string.record_bcc); - hasIcon = true; - } else if (Intervention.CASE_CONFIRMATION.equals(task.getTaskCode()) && task.getTaskCount() == null) { - viewHolder.setIcon(R.drawable.ic_classification_details); - viewHolder.setItemViewListener(task, registerActionHandler); - name = context.getString(R.string.classification_details); - action = context.getString(R.string.view); - hasIcon = true; - } else if (Intervention.PAOT.equals(task.getTaskCode())) { - name = context.getString(R.string.card_view_paot); - if (task.getBusinessStatus() != null) { - action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); - } - } else { - name = NOT_ELIGIBLE.equals(task.getBusinessStatus()) ? context.getString(R.string.ineligible_location) : task.getFamilyName(); - if (name == null) { - name = task.getStructureName() != null ? task.getStructureName() : context.getString(R.string.unenumerated_structure); - } - if (task.getBusinessStatus() != null) { - action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); - } - } - viewHolder.setTaskName(name); - CardDetails cardDetails = new CardDetails(task.getBusinessStatus()); - if (Task.TaskStatus.COMPLETED.name().equals(task.getTaskStatus())) { - if (task.getBusinessStatus() != null) { - action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); - } - CardDetailsUtil.formatCardDetails(cardDetails); - } - viewHolder.setTaskAction(action, task, cardDetails, registerActionHandler); - viewHolder.setDistanceFromStructure(distance, task.isDistanceFromCenter()); - viewHolder.setTaskDetails(task.getBusinessStatus(), task.getTaskDetails()); - if (hasIcon) { - viewHolder.hideDistanceFromStructure(); - } else { - viewHolder.hideIcon(); - } - - if (StringUtils.isNotEmpty(task.getHouseNumber())) { - viewHolder.showHouseNumber(); - viewHolder.setHouseNumber(context.getString(R.string.numero_sign) + " " + task.getHouseNumber()); - } else { - viewHolder.hideHouseNumber(); - } - } - - @Override - public int getItemCount() { - return taskDetails.size(); - } - - public void setTaskDetails(List taskDetails) { - this.taskDetails = taskDetails; - notifyDataSetChanged(); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/application/RevealApplication.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/application/RevealApplication.java index 2da1a4e7b3..c22b5c59d8 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/application/RevealApplication.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/application/RevealApplication.java @@ -6,6 +6,7 @@ import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.evernote.android.job.JobManager; +import com.mapbox.geojson.Feature; import com.mapbox.geojson.FeatureCollection; import com.mapbox.mapboxsdk.Mapbox; import com.vijay.jsonwizard.NativeFormLibrary; @@ -39,17 +40,19 @@ import org.smartregister.repository.TaskRepository; import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.activity.LoginActivity; +import org.smartregister.reveal.config.TaskingLibraryConfiguration; import org.smartregister.reveal.job.RevealJobCreator; import org.smartregister.reveal.repository.RevealRepository; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.Constants; import org.smartregister.reveal.util.Country; import org.smartregister.reveal.util.RevealSyncConfiguration; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; import org.smartregister.reveal.view.FamilyProfileActivity; import org.smartregister.sync.ClientProcessorForJava; import org.smartregister.sync.DrishtiSyncScheduler; +import org.smartregister.tasking.TaskingLibrary; +import org.smartregister.util.AppExecutors; import org.smartregister.util.LangUtils; import org.smartregister.view.activity.DrishtiApplication; import org.smartregister.view.receiver.TimeChangedBroadcastReceiver; @@ -58,8 +61,8 @@ import java.util.Map; import io.fabric.sdk.android.Fabric; -import io.ona.kujaku.data.realm.RealmDatabase; import io.ona.kujaku.KujakuLibrary; +import io.ona.kujaku.data.realm.RealmDatabase; import timber.log.Timber; import static org.smartregister.reveal.util.Constants.CONFIGURATION.GLOBAL_CONFIGS; @@ -77,7 +80,7 @@ public class RevealApplication extends DrishtiApplication implements TimeChangedBroadcastReceiver.OnTimeChangedListener { private JsonSpecHelper jsonSpecHelper; - private String password; + private char[] password; private PlanDefinitionSearchRepository planDefinitionSearchRepository; @@ -97,6 +100,8 @@ public class RevealApplication extends DrishtiApplication implements TimeChanged private RealmDatabase realmDatabase; + private Feature operationalArea; + private boolean synced; public static synchronized RevealApplication getInstance() { @@ -134,6 +139,7 @@ public void onCreate() { LocationHelper.init(Utils.ALLOWED_LEVELS, Utils.DEFAULT_LOCATION_LEVEL); SyncStatusBroadcastReceiver.init(this); + TaskingLibrary.init(new TaskingLibraryConfiguration()); jsonSpecHelper = new JsonSpecHelper(this); serverConfigs = new HashMap<>(); @@ -158,9 +164,10 @@ public void onCreate() { */ private void forceRemoteLoginForInConsistentUsername() { AllSharedPreferences allSharedPreferences = context.allSharedPreferences(); - if (StringUtils.isNotBlank(allSharedPreferences.fetchRegisteredANM()) && StringUtils.isBlank(allSharedPreferences.fetchDefaultTeamId(allSharedPreferences.fetchRegisteredANM()))) { + String provider = allSharedPreferences.fetchRegisteredANM(); + if (StringUtils.isNotBlank(provider) && StringUtils.isBlank(allSharedPreferences.fetchDefaultTeamId(allSharedPreferences.fetchRegisteredANM()))) { allSharedPreferences.updateANMUserName(null); - allSharedPreferences.saveForceRemoteLogin(true); + allSharedPreferences.saveForceRemoteLogin(true, provider); } } @@ -177,7 +184,7 @@ public Repository getRepository() { return repository; } - public String getPassword() { + public char[] getPassword() { if (password == null) { String username = getContext().allSharedPreferences().fetchRegisteredANM(); password = getContext().userService().getGroupId(username); @@ -220,13 +227,13 @@ public void onTerminate() { @Override public void onTimeChanged() { - context.userService().forceRemoteLogin(); + context.userService().forceRemoteLogin(context.allSharedPreferences().fetchRegisteredANM()); logoutCurrentUser(); } @Override public void onTimeZoneChanged() { - context.userService().forceRemoteLogin(); + context.userService().forceRemoteLogin(context.allSharedPreferences().fetchRegisteredANM()); logoutCurrentUser(); } @@ -400,6 +407,14 @@ public void setFeatureCollection(FeatureCollection featureCollection) { this.featureCollection = featureCollection; } + public Feature getOperationalArea() { + return operationalArea; + } + + public void setOperationalArea(Feature operationalArea) { + this.operationalArea = operationalArea; + } + public boolean getSynced() { return synced; } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/config/TaskingLibraryConfiguration.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/config/TaskingLibraryConfiguration.java new file mode 100644 index 0000000000..3f59b98994 --- /dev/null +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/config/TaskingLibraryConfiguration.java @@ -0,0 +1,1018 @@ +package org.smartregister.reveal.config; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.Drawable; +import android.view.View; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.core.util.Pair; + +import net.sqlcipher.database.SQLiteDatabase; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.smartregister.CoreLibrary; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.clientandeventmodel.Obs; +import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; +import org.smartregister.domain.Client; +import org.smartregister.domain.Location; +import org.smartregister.domain.Task; +import org.smartregister.domain.db.EventClient; +import org.smartregister.family.fragment.NoMatchDialogFragment; +import org.smartregister.family.util.DBConstants; +import org.smartregister.job.DocumentConfigurationServiceJob; +import org.smartregister.job.PullUniqueIdsServiceJob; +import org.smartregister.repository.BaseRepository; +import org.smartregister.repository.EventClientRepository; +import org.smartregister.repository.TaskRepository; +import org.smartregister.reveal.BuildConfig; +import org.smartregister.reveal.R; +import org.smartregister.reveal.application.RevealApplication; +import org.smartregister.reveal.contract.StructureTasksContract; +import org.smartregister.reveal.job.LocationTaskServiceJob; +import org.smartregister.reveal.sync.RevealClientProcessor; +import org.smartregister.reveal.task.IndicatorsCalculatorTask; +import org.smartregister.tasking.util.CardDetailsUtil; +import org.smartregister.reveal.util.Constants; +import org.smartregister.reveal.util.Country; +import org.smartregister.reveal.util.FamilyConstants; +import org.smartregister.reveal.util.FamilyJsonFormUtils; +import org.smartregister.reveal.util.RevealJsonFormUtils; +import org.smartregister.reveal.util.TaskUtils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.reveal.view.ListTasksActivity; +import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.tasking.activity.FilterTasksActivity; +import org.smartregister.tasking.adapter.TaskRegisterAdapter; +import org.smartregister.tasking.contract.BaseContract; +import org.smartregister.tasking.contract.BaseFormFragmentContract; +import org.smartregister.tasking.model.BaseTaskDetails; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.model.TaskFilterParams; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.tasking.util.PreferencesUtil; +import org.smartregister.tasking.viewholder.TaskRegisterViewHolder; +import org.smartregister.util.AppExecutors; +import org.smartregister.util.JsonFormUtils; +import org.smartregister.view.activity.BaseRegisterActivity; +import org.smartregister.view.activity.DrishtiApplication; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import timber.log.Timber; + +import static android.app.Activity.RESULT_OK; +import static org.smartregister.family.util.DBConstants.KEY.FIRST_NAME; +import static org.smartregister.family.util.Utils.metadata; +import static org.smartregister.reveal.util.Constants.BEDNET_DISTRIBUTION_EVENT; +import static org.smartregister.reveal.util.Constants.BLOOD_SCREENING_EVENT; +import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_ELIGIBLE; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.BUSINESS_STATUS; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.CODE; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.FAMILY_NAME; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.FOR; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.ID; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.LATITUDE; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.LONGITUDE; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.NAME; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.NOT_SRAYED_OTHER_REASON; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.NOT_SRAYED_REASON; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.REFERENCE_REASON; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.SPRAYED_STRUCTURES; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.SPRAY_STATUS; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.STATUS; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURES_TABLE; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_ID; +import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_NAME; +import static org.smartregister.reveal.util.Constants.EventType.CASE_CONFIRMATION_EVENT; +import static org.smartregister.reveal.util.Constants.Filter.FILTER_SORT_PARAMS; +import static org.smartregister.reveal.util.Constants.Intervention.BCC; +import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; +import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; +import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; +import static org.smartregister.reveal.util.Constants.Intervention.IRS; +import static org.smartregister.reveal.util.Constants.Intervention.LARVAL_DIPPING; +import static org.smartregister.reveal.util.Constants.Intervention.MOSQUITO_COLLECTION; +import static org.smartregister.reveal.util.Constants.Intervention.PAOT; +import static org.smartregister.reveal.util.Constants.JsonForm.ENCOUNTER_TYPE; +import static org.smartregister.reveal.util.Constants.REGISTER_STRUCTURE_EVENT; +import static org.smartregister.reveal.util.FamilyConstants.DatabaseKeys.HOUSE_NUMBER; +import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY; +import static org.smartregister.util.JsonFormUtils.ENTITY_ID; + +/** + * Created by Ephraim Kigamba - nek.eam@gmail.com on 07-08-2020. + */ +public class TaskingLibraryConfiguration extends org.smartregister.tasking.util.TaskingLibraryConfiguration { + + + @NonNull + @Override + public Pair getActionDrawable(Context context, TaskDetails task) { + // The assumption is that a register structure task always exists if the structure has + // atleast one bednet distribution or blood screening task + boolean familyRegTaskMissingOrFamilyRegComplete = task.isFamilyRegistered() || !task.isFamilyRegTaskExists(); + Drawable actionBg = null; + String actionText = context.getText(R.string.view_tasks).toString(); + + if (Utils.isFocusInvestigation()) { + if (familyRegTaskMissingOrFamilyRegComplete && task.isBednetDistributed() && task.isBloodScreeningDone()) { + actionBg = context.getResources().getDrawable(R.drawable.tasks_complete_bg); + actionText = context.getText(R.string.tasks_complete).toString(); + } else if (familyRegTaskMissingOrFamilyRegComplete && !task.isBednetDistributed() && !task.isBloodScreeningDone()) { + actionBg = context.getResources().getDrawable(R.drawable.family_registered_bg); + } else if (familyRegTaskMissingOrFamilyRegComplete && task.isBednetDistributed()) { + actionBg = context.getResources().getDrawable(R.drawable.bednet_distributed_bg); + } else if (task.isBloodScreeningDone()) { + actionBg = context.getResources().getDrawable(R.drawable.blood_screening_complete_bg); + } else { + actionBg = context.getResources().getDrawable(R.drawable.no_task_complete_bg); + } + } else if (Utils.isMDA()) { + if (familyRegTaskMissingOrFamilyRegComplete && task.isMdaAdhered()) { + actionBg = context.getResources().getDrawable(R.drawable.mda_adhered_bg); + actionText = context.getText(R.string.tasks_complete).toString(); + } else if (familyRegTaskMissingOrFamilyRegComplete && task.isFullyReceived()) { + actionBg = context.getResources().getDrawable(R.drawable.mda_dispensed_bg); + } else if (familyRegTaskMissingOrFamilyRegComplete && task.isPartiallyReceived()) { + actionBg = context.getResources().getDrawable(R.drawable.mda_partially_received_bg); + } else if (familyRegTaskMissingOrFamilyRegComplete && task.isNoneReceived()) { + actionBg = context.getResources().getDrawable(R.drawable.mda_none_received_bg); + } else if (familyRegTaskMissingOrFamilyRegComplete && task.isNotEligible()) { + actionBg = context.getResources().getDrawable(R.drawable.mda_not_eligible_bg); + } else if (familyRegTaskMissingOrFamilyRegComplete) { + actionBg = context.getResources().getDrawable(R.drawable.family_registered_bg); + } else { + actionBg = context.getResources().getDrawable(R.drawable.no_task_complete_bg); + } + } + + return new Pair<>(actionBg, actionText); + } + + @Override + public int getInterventionLabel() { + String plan = PreferencesUtil.getInstance().getCurrentPlan(); + String interventionType = PreferencesUtil.getInstance().getInterventionTypeForPlan(plan); + if (interventionType.equals(Constants.Intervention.FI)) + return R.string.focus_investigation; + else if (interventionType.equals(Constants.Intervention.IRS)) + return R.string.irs; + else if (interventionType.equals(Constants.Intervention.MDA)) + return R.string.mda; + else + return R.string.irs; + } + + @NonNull + @Override + public Float getLocationBuffer() { + return Float.valueOf(Utils.getGlobalConfig(Constants.CONFIGURATION.LOCATION_BUFFER_RADIUS_IN_METRES, BuildConfig.MY_LOCATION_BUFFER + "")); + } + + @Override + public void startImmediateSync() { + LocationTaskServiceJob.scheduleJobImmediately(LocationTaskServiceJob.TAG); + PullUniqueIdsServiceJob.scheduleJobImmediately(PullUniqueIdsServiceJob.TAG); + DocumentConfigurationServiceJob.scheduleJobImmediately(DocumentConfigurationServiceJob.TAG); + } + + @Override + public boolean validateFarStructures() { + return Boolean.valueOf(Utils.getGlobalConfig(Constants.CONFIGURATION.VALIDATE_FAR_STRUCTURES, BuildConfig.VALIDATE_FAR_STRUCTURES + "")); + } + + @Override + public int getResolveLocationTimeoutInSeconds() { + return Integer.valueOf(Utils.getGlobalConfig(Constants.CONFIGURATION.RESOLVE_LOCATION_TIMEOUT_IN_SECONDS, BuildConfig.RESOLVE_LOCATION_TIMEOUT_IN_SECONDS + "")); + } + + @Override + public String getAdminPasswordNotNearStructures() { + return Utils.getGlobalConfig(Constants.CONFIGURATION.ADMIN_PASSWORD_NOT_NEAR_STRUCTURES, BuildConfig.ADMIN_PASSWORD_NOT_NEAR_STRUCTURES); + } + + @Override + public boolean isFocusInvestigation() { + return getInterventionLabel() == R.string.focus_investigation; + } + + @Override + public boolean isMDA() { + return getInterventionLabel() == R.string.mda; + } + + @Override + public String getCurrentLocationId() { + Location currentOperationalArea = Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()); + return currentOperationalArea == null ? null : currentOperationalArea.getId(); + } + + @Override + public String getCurrentOperationalAreaId() { + return PreferencesUtil.getInstance().getCurrentOperationalAreaId(); + } + + @Override + public Integer getDatabaseVersion() { + return BuildConfig.DATABASE_VERSION; + } + + @Override + public void tagEventTaskDetails(List events, SQLiteDatabase sqLiteDatabase) { + TaskUtils.getInstance().tagEventTaskDetails(events, sqLiteDatabase); + } + + @Override + public Boolean displayDistanceScale() { + return Boolean.valueOf(Utils.getGlobalConfig(Constants.CONFIGURATION.DISPLAY_DISTANCE_SCALE, BuildConfig.DISPLAY_DISTANCE_SCALE + "")); + } + + @Override + public String getFormName(@NonNull String encounterType, @Nullable String taskCode) { + String formName = null; + if (Constants.SPRAY_EVENT.equals(encounterType) || Constants.Intervention.IRS.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.NAMIBIA) { + formName = Constants.JsonForm.SPRAY_FORM_NAMIBIA; + } else if (BuildConfig.BUILD_COUNTRY == Country.BOTSWANA) { + formName = Constants.JsonForm.SPRAY_FORM_BOTSWANA; + } else if (BuildConfig.BUILD_COUNTRY == Country.ZAMBIA) { + formName = Constants.JsonForm.SPRAY_FORM_ZAMBIA; + } else if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_SPRAY_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.SPRAY_FORM_REFAPP; + } else { + formName = Constants.JsonForm.SPRAY_FORM; + } + } else if (Constants.MOSQUITO_COLLECTION_EVENT.equals(encounterType) + || Constants.Intervention.MOSQUITO_COLLECTION.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_MOSQUITO_COLLECTION_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_MOSQUITO_COLLECTION_FORM; + } else { + formName = Constants.JsonForm.MOSQUITO_COLLECTION_FORM; + } + } else if (Constants.BEDNET_DISTRIBUTION_EVENT.equals(encounterType) + || Constants.Intervention.BEDNET_DISTRIBUTION.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_BEDNET_DISTRIBUTION_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_BEDNET_DISTRIBUTION_FORM; + } else { + formName = Constants.JsonForm.BEDNET_DISTRIBUTION_FORM; + } + } else if (Constants.EventType.CASE_CONFIRMATION_EVENT.equals(encounterType) + || Constants.Intervention.CASE_CONFIRMATION.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_CASE_CONFIRMATION_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_CASE_CONFIRMATION_FORM; + } else { + formName = Constants.JsonForm.CASE_CONFIRMATION_FORM; + } + } else if (Constants.BLOOD_SCREENING_EVENT.equals(encounterType) + || Constants.Intervention.BLOOD_SCREENING.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_BLOOD_SCREENING_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_BLOOD_SCREENING_FORM; + } else { + formName = Constants.JsonForm.BLOOD_SCREENING_FORM; + } + } else if (Constants.LARVAL_DIPPING_EVENT.equals(encounterType) || Constants.Intervention.LARVAL_DIPPING.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_LARVAL_DIPPING_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_LARVAL_DIPPING_FORM; + } else { + formName = Constants.JsonForm.LARVAL_DIPPING_FORM; + } + } else if (Constants.BEHAVIOUR_CHANGE_COMMUNICATION.equals(encounterType) || Constants.Intervention.BCC.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_BEHAVIOUR_CHANGE_COMMUNICATION_FORM; + } else { + formName = Constants.JsonForm.BEHAVIOUR_CHANGE_COMMUNICATION_FORM; + } + } else if (Constants.REGISTER_STRUCTURE_EVENT.equals(encounterType)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_ADD_STRUCTURE_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.NAMIBIA) { + formName = Constants.JsonForm.NAMIBIA_ADD_STRUCTURE_FORM; + } else { + formName = Constants.JsonForm.ADD_STRUCTURE_FORM; + } + } else if (Constants.EventType.PAOT_EVENT.equals(encounterType) || Constants.Intervention.PAOT.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.THAILAND) { + formName = Constants.JsonForm.THAILAND_PAOT_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_PAOT_FORM; + } else { + formName = Constants.JsonForm.PAOT_FORM; + } + } else if (Constants.Intervention.MDA_ADHERENCE.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.ZAMBIA) { + formName = Constants.JsonForm.ZAMBIA_MDA_ADHERENCE_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_MDA_ADHERENCE_FORM; + } + } else if (Constants.Intervention.MDA_DISPENSE.equals(taskCode)) { + if (BuildConfig.BUILD_COUNTRY == Country.ZAMBIA) { + formName = Constants.JsonForm.ZAMBIA_MDA_DISPENSE_FORM; + } else if (BuildConfig.BUILD_COUNTRY == Country.REFAPP) { + formName = Constants.JsonForm.REFAPP_MDA_DISPENSE_FORM; + } + } else if (Constants.EventType.IRS_VERIFICATION.equals(encounterType) || Constants.Intervention.IRS_VERIFICATION.equals(taskCode)) { + formName = Constants.JsonForm.ZAMBIA_IRS_VERIFICATION_FORM; + } + return formName; + } + + @Override + public boolean resetTaskInfo(@NonNull SQLiteDatabase db, @NonNull BaseTaskDetails taskDetails) { + InteractorUtils interactorUtils = new InteractorUtils(RevealApplication.getInstance().getTaskRepository(), CoreLibrary.getInstance().context().getEventClientRepository(), RevealApplication.getInstance().getClientProcessor()); + return interactorUtils.archiveEventsForTask(db, taskDetails) && TaskUtils.getInstance().resetTask(taskDetails); + } + + @Override + public boolean archiveClient(String baseEntityId, boolean isFamily) { + TaskRepository taskRepository = RevealApplication.getInstance().getTaskRepository(); + EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); + ClientProcessorForJava clientProcessor = RevealApplication.getInstance().getClientProcessor(); + + taskRepository.cancelTasksForEntity(baseEntityId); + taskRepository.archiveTasksForEntity(baseEntityId); + JSONObject eventsByBaseEntityId = eventClientRepository.getEventsByBaseEntityId(baseEntityId); + JSONArray events = eventsByBaseEntityId.optJSONArray("events"); + JSONObject clientJsonObject = eventsByBaseEntityId.optJSONObject("client"); + DateTime now = new DateTime(); + if (events != null) { + for (int i = 0; i < events.length(); i++) { + try { + JSONObject event = events.getJSONObject(i); + event.put("dateVoided", now); + event.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); + } catch (JSONException e) { + Timber.e(e); + } + } + } + + boolean saved; + try { + eventClientRepository.batchInsertEvents(events, 0); + clientJsonObject.put("dateVoided", now); + clientJsonObject.put(EventClientRepository.client_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); + clientJsonObject.getJSONObject("attributes").put("dateRemoved", now); + eventClientRepository.addorUpdateClient(baseEntityId, clientJsonObject); + RevealApplication.getInstance().setSynced(false); + Event archiveEvent = FamilyJsonFormUtils.createFamilyEvent(baseEntityId, Utils.getCurrentLocationId(), + null, isFamily ? FamilyConstants.EventType.ARCHIVE_FAMILY : FamilyConstants.EventType.ARCHIVE_FAMILY_MEMBER); + archiveEvent.addObs(new Obs().withValue(now).withFieldCode("dateArchived").withFieldType("formsubmissionField")); + + JSONObject eventJson = new JSONObject(JsonFormUtils.gson.toJson(archiveEvent)); + eventJson.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); + eventClientRepository.addEvent(baseEntityId, eventJson); + + clientProcessor.processClient(Collections.singletonList(new EventClient( + JsonFormUtils.gson.fromJson(eventJson.toString(), org.smartregister.domain.Event.class), + JsonFormUtils.gson.fromJson(clientJsonObject.toString(), Client.class))), true); + saved = true; + + } catch (Exception e) { + Timber.e(e); + saved = false; + } + return saved; + } + + @Override + public String getTranslatedIRSVerificationStatus(String status) { + Context context = DrishtiApplication.getInstance().getApplicationContext(); + + if (status == null) + return context.getString(R.string.not_sprayed); + + switch (status) { + case Constants.IRSVerificationStatus.SPRAYED: + return context.getString(R.string.sprayed); + case Constants.IRSVerificationStatus.NOT_SPRAYED: + return context.getString(R.string.not_sprayed); + case Constants.IRSVerificationStatus.NOT_FOUND_OR_VISITED: + return context.getString(R.string.structure_not_found_or_visited_during_campaign); + case Constants.IRSVerificationStatus.OTHER: + return context.getString(R.string.other); + default: + return status; + } + } + + @Override + public String getTranslatedBusinessStatus(String businessStatus) { + Context context = RevealApplication.getInstance().getApplicationContext(); + + if (businessStatus == null) + return context.getString(R.string.not_eligible); + switch (businessStatus) { + case Constants.BusinessStatus.NOT_VISITED: + return context.getString(R.string.not_visited); + case Constants.BusinessStatus.NOT_SPRAYED: + return context.getString(R.string.not_sprayed); + case Constants.BusinessStatus.SPRAYED: + return context.getString(R.string.sprayed); + case Constants.BusinessStatus.NOT_SPRAYABLE: + return context.getString(R.string.not_sprayable); + case Constants.BusinessStatus.COMPLETE: + return context.getString(R.string.complete); + case Constants.BusinessStatus.INCOMPLETE: + return context.getString(R.string.incomplete); + case Constants.BusinessStatus.NOT_ELIGIBLE: + return context.getString(R.string.not_eligible); + case Constants.BusinessStatus.IN_PROGRESS: + return context.getString(R.string.in_progress); + case Constants.BusinessStatus.PARTIALLY_SPRAYED: + return context.getString(R.string.partially_sprayed); + default: + return businessStatus; + } + } + + @Override + public void formatCardDetails(CardDetails cardDetails) { + if (cardDetails == null || cardDetails.getStatus() == null) + return; + // extract status color + String status = cardDetails.getStatus(); + switch (status) { + case Constants.BusinessStatus.NOT_SPRAYED: + case Constants.BusinessStatus.INCOMPLETE: + case Constants.BusinessStatus.IN_PROGRESS: + case Constants.BusinessStatus.NONE_RECEIVED: + cardDetails.setStatusColor(R.color.unsprayed); + cardDetails.setStatusMessage(R.string.details_not_sprayed); + break; + case Constants.BusinessStatus.SPRAYED: + case Constants.BusinessStatus.COMPLETE: + case Constants.BusinessStatus.FULLY_RECEIVED: + cardDetails.setStatusColor(R.color.sprayed); + cardDetails.setStatusMessage(R.string.details_sprayed); + cardDetails.setReason(null); + break; + case Constants.BusinessStatus.NOT_SPRAYABLE: + case Constants.BusinessStatus.NOT_ELIGIBLE: + cardDetails.setStatusColor(R.color.unsprayable); + cardDetails.setStatusMessage(R.string.details_not_sprayable); + cardDetails.setReason(null); + break; + case Constants.BusinessStatus.PARTIALLY_SPRAYED: + cardDetails.setStatusColor(R.color.partially_sprayed); + cardDetails.setStatusMessage(R.string.partially_sprayed); + break; + default: + Timber.w("business status not defined :" + cardDetails.getStatus()); + break; + } + + } + + @Override + public void processServerConfigs() { + RevealApplication.getInstance().processServerConfigs(); + } + + @Override + public Map populateLabels() { + //Interventions + Map labelsMap = new HashMap<>(); + labelsMap.put(Constants.Intervention.IRS, R.string.irs); + labelsMap.put(Constants.Intervention.MOSQUITO_COLLECTION, R.string.mosquito_collection); + labelsMap.put(Constants.Intervention.LARVAL_DIPPING, R.string.larval_dipping); + labelsMap.put(Constants.Intervention.BCC, R.string.bcc_code); + labelsMap.put(Constants.Intervention.BEDNET_DISTRIBUTION, R.string.bednet_distribution); + labelsMap.put(Constants.Intervention.BLOOD_SCREENING, R.string.blood_screening); + labelsMap.put(Constants.Intervention.CASE_CONFIRMATION, R.string.case_confirmation); + labelsMap.put(Constants.Intervention.REGISTER_FAMILY, R.string.register_family); + labelsMap.put(Constants.Intervention.PAOT, R.string.paot); + labelsMap.put(Constants.Intervention.MDA_DISPENSE, R.string.mda_dispense); + labelsMap.put(Constants.Intervention.MDA_ADHERENCE, R.string.mda_adherence); + labelsMap.put(Constants.Intervention.IRS_VERIFICATION, R.string.irs_verification); + + //Intervention Types + labelsMap.put(Constants.InterventionType.OPERATIONAL_AREA, R.string.operational_area); + labelsMap.put(Constants.InterventionType.STRUCTURE, R.string.structure); + labelsMap.put(Constants.InterventionType.FAMILY, R.string.family); + labelsMap.put(Constants.InterventionType.PERSON, R.string.person); + + //Business status + labelsMap.put(Constants.BusinessStatus.NOT_VISITED, R.string.not_visited); + labelsMap.put(Constants.BusinessStatus.NOT_SPRAYED, R.string.not_sprayed); + labelsMap.put(Constants.BusinessStatus.NOT_SPRAYABLE, R.string.not_sprayable); + labelsMap.put(Constants.BusinessStatus.SPRAYED, R.string.sprayed); + + labelsMap.put(Constants.BusinessStatus.COMPLETE, R.string.complete); + labelsMap.put(Constants.BusinessStatus.INCOMPLETE, R.string.incomplete); + labelsMap.put(Constants.BusinessStatus.NOT_ELIGIBLE, R.string.not_eligible); + labelsMap.put(Constants.BusinessStatus.IN_PROGRESS, R.string.in_progress); + + return labelsMap; + } + + @Override + public void showBasicForm(BaseFormFragmentContract.View view, Context context, String formName) { + RevealJsonFormUtils jsonFormUtils = new RevealJsonFormUtils(); + JSONObject formJSON = view.getJsonFormUtils().getFormJSON(context, formName, null, null); + switch (formName) { + + case Constants.JsonForm.IRS_SA_DECISION_ZAMBIA: + case Constants.JsonForm.CB_SPRAY_AREA_ZAMBIA: + case Constants.JsonForm.MOBILIZATION_FORM_ZAMBIA: + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.SUPERVISORS, Constants.JsonForm.SUPERVISOR, + PreferencesUtil.getInstance().getCurrentDistrict()); + break; + + case Constants.JsonForm.IRS_FIELD_OFFICER_ZAMBIA: + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.FIELD_OFFICERS, Constants.JsonForm.FIELD_OFFICER, + PreferencesUtil.getInstance().getCurrentDistrict()); + break; + + case Constants.JsonForm.DAILY_SUMMARY_ZAMBIA: + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.TEAM_LEADERS, Constants.JsonForm.TEAM_LEADER, + PreferencesUtil.getInstance().getCurrentDistrict()); + + case Constants.JsonForm.TEAM_LEADER_DOS_ZAMBIA: + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.SUPERVISORS, Constants.JsonForm.SUPERVISOR, + PreferencesUtil.getInstance().getCurrentDistrict()); + + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.DATA_COLLECTORS, Constants.JsonForm.DATA_COLLECTOR, + PreferencesUtil.getInstance().getCurrentDistrict()); + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.DISTRICT_MANAGERS, Constants.JsonForm.DISTRICT_MANAGER, + PreferencesUtil.getInstance().getCurrentDistrict()); + + break; + + case Constants.JsonForm.VERIFICATION_FORM_ZAMBIA: + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.FIELD_OFFICERS, Constants.JsonForm.FIELD_OFFICER, + PreferencesUtil.getInstance().getCurrentDistrict()); + + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), + formJSON, Constants.CONFIGURATION.DATA_COLLECTORS, Constants.JsonForm.DATA_COLLECTOR, + PreferencesUtil.getInstance().getCurrentDistrict()); + + break; + default: + break; + } + + view.startForm(formJSON); + } + + @Override + public void onLocationValidated(@NonNull Context context, @NonNull BaseFormFragmentContract.View view, @NonNull BaseFormFragmentContract.Interactor interactor, @NonNull BaseTaskDetails baseTaskDetails, @NonNull Location structure) { + PreferencesUtil prefsUtil = PreferencesUtil.getInstance(); + RevealJsonFormUtils jsonFormUtils = new RevealJsonFormUtils(); + if (!Constants.Intervention.REGISTER_FAMILY.equals(baseTaskDetails.getTaskCode())) { + String formName = view.getJsonFormUtils().getFormName(null, baseTaskDetails.getTaskCode()); + if (StringUtils.isBlank(formName)) { + view.displayError(R.string.opening_form_title, R.string.form_not_found); + } else { + JSONObject formJSON = view.getJsonFormUtils().getFormJSON(context, formName, baseTaskDetails, structure); + if (Constants.Intervention.BEDNET_DISTRIBUTION.equals(baseTaskDetails.getTaskCode())) { + interactor.findNumberOfMembers(baseTaskDetails.getTaskEntity(), formJSON); + return; + } else if (Constants.Intervention.CASE_CONFIRMATION.equals(baseTaskDetails.getTaskCode())) { + interactor.findMemberDetails(baseTaskDetails.getStructureId(), formJSON); + return; + } else if (Constants.Intervention.IRS.equals(baseTaskDetails.getTaskCode()) && Country.NAMIBIA.equals(BuildConfig.BUILD_COUNTRY)) { + interactor.findSprayDetails(Constants.Intervention.IRS, structure.getId(), formJSON); + } else if (Constants.Intervention.MDA_DISPENSE.equals(baseTaskDetails.getTaskCode()) || Constants.Intervention.MDA_ADHERENCE.equals(baseTaskDetails.getTaskCode())) { + jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), formJSON, Constants.CONFIGURATION.MDA_CATCHMENT_AREAS, Constants.JsonForm.CATCHMENT_AREA, prefsUtil.getCurrentDistrict()); + view.startForm(formJSON); + } else { + view.startForm(formJSON); + } + } + } + + view.hideProgressDialog(); + } + + @Override + public String mainSelect(String mainCondition) { + String tableName = Constants.DatabaseKeys.TASK_TABLE; + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, taskRegisterMainColumns(tableName), Constants.DatabaseKeys.ID); + queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.STRUCTURES_TABLE, tableName, Constants.DatabaseKeys.FOR, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID)); + queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.SPRAYED_STRUCTURES, tableName, Constants.DatabaseKeys.FOR, Constants.DatabaseKeys.SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); + queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", + FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID, FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURE_ID)); + return queryBuilder.mainCondition(mainCondition); + } + + @Override + public String nonRegisteredStructureTasksSelect(String mainCondition) { + String tableName = Constants.Tables.TASK_TABLE; + SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); + queryBuilder.selectInitiateMainTable(tableName, taskRegisterMainColumns(tableName), Constants.DatabaseKeys.ID); + queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.STRUCTURES_TABLE, tableName, Constants.DatabaseKeys.FOR, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID)); + queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.SPRAYED_STRUCTURES, tableName, Constants.DatabaseKeys.FOR, Constants.DatabaseKeys.SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); + queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", + FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID, FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURE_ID)); + queryBuilder.mainCondition(mainCondition); + queryBuilder.addCondition(String.format(" AND %s.%s IS NULL", + FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURE_ID)); + return queryBuilder.addCondition(String.format(" AND %s.%s != '%s'", + tableName, Constants.DatabaseKeys.CODE, Constants.Intervention.BEDNET_DISTRIBUTION)); + } + + @Override + public String groupedRegisteredStructureTasksSelect(String mainCondition) { + String tableName = Constants.Tables.TASK_TABLE; + SmartRegisterQueryBuilder structureTasksQueryBuilder = new SmartRegisterQueryBuilder(); + String[] columns = ArrayUtils.add(taskRegisterMainColumns(tableName), String.format("%s.%s||' '||%s.%s as %s ", "", "", "", Constants.DatabaseKeys.LAST_NAME, ""));//FAMILY_MEMBER, FIRST_NAME, FAMILY_MEMBER, LAST_NAME, FAMILY_MEMBER_NAMES)); + structureTasksQueryBuilder.selectInitiateMainTable(tableName, columns, Constants.DatabaseKeys.ID); + structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.STRUCTURES_TABLE, tableName, Constants.DatabaseKeys.STRUCTURE_ID, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID)); + structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s COLLATE NOCASE", + FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURES_TABLE, Constants.DatabaseKeys.ID, FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.STRUCTURE_ID)); + structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s COLLATE NOCASE", + FamilyConstants.TABLE_NAME.FAMILY_MEMBER, FamilyConstants.TABLE_NAME.FAMILY, Constants.DatabaseKeys.BASE_ENTITY_ID, FamilyConstants.TABLE_NAME.FAMILY_MEMBER, DBConstants.KEY.RELATIONAL_ID)); + structureTasksQueryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", + Constants.DatabaseKeys.SPRAYED_STRUCTURES, tableName, Constants.DatabaseKeys.FOR, Constants.DatabaseKeys.SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); + structureTasksQueryBuilder.mainCondition(mainCondition); + + return String.format(" SELECT %s.* , SUM(CASE WHEN status='%s' THEN 1 ELSE 0 END ) AS %s , COUNT(_id ) AS %s, " + + "GROUP_CONCAT(%s || \"-\" || %s ) AS %s , GROUP_CONCAT(%s) as %s FROM ( ", + Constants.DatabaseKeys.GROUPED_TASKS, Task.TaskStatus.COMPLETED.toString(), Constants.DatabaseKeys.COMPLETED_TASK_COUNT, Constants.DatabaseKeys.TASK_COUNT, Constants.DatabaseKeys.CODE, Constants.DatabaseKeys.BUSINESS_STATUS, Constants.DatabaseKeys.GROUPED_STRUCTURE_TASK_CODE_AND_STATUS, "", "") + structureTasksQueryBuilder +//FAMILY_MEMBER_NAMES, FAMILY_MEMBER_NAMES) + structureTasksQueryBuilder + + String.format(" ) AS %s GROUP BY %s ", Constants.DatabaseKeys.GROUPED_TASKS, Constants.DatabaseKeys.STRUCTURE_ID); + } + + @Override + public String[] taskRegisterMainColumns(String tableName) { + return new String[]{ + tableName + "." + ID, + tableName + "." + CODE, + tableName + "." + FOR, + tableName + "." + BUSINESS_STATUS, + tableName + "." + STATUS, + tableName + "." + REFERENCE_REASON, + STRUCTURES_TABLE + "." + LATITUDE, + STRUCTURES_TABLE + "." + LONGITUDE, + STRUCTURES_TABLE + "." + NAME, + SPRAYED_STRUCTURES + "." + STRUCTURE_NAME, + SPRAYED_STRUCTURES + "." + FAMILY_NAME, + SPRAYED_STRUCTURES + "." + SPRAY_STATUS, + SPRAYED_STRUCTURES + "." + NOT_SRAYED_REASON, + SPRAYED_STRUCTURES + "." + NOT_SRAYED_OTHER_REASON, + STRUCTURES_TABLE + "." + ID + " AS " + STRUCTURE_ID, + FAMILY + "." + FIRST_NAME, + FAMILY + "." + HOUSE_NUMBER + + }; + } + + @Override + public String familyRegisterTableName() { + return metadata().familyRegister.tableName; + } + + @Override + public void saveCaseConfirmation(BaseContract.BaseInteractor baseInteractor, BaseContract.BasePresenter presenterCallBack, JSONObject jsonForm, String eventType) { + AppExecutors appExecutors = RevealApplication.getInstance().getAppExecutors(); + TaskRepository taskRepository = RevealApplication.getInstance().getTaskRepository(); + RevealClientProcessor clientProcessor = (RevealClientProcessor) RevealApplication.getInstance().getClientProcessor(); + EventClientRepository eventClientRepository = CoreLibrary.getInstance().context().getEventClientRepository(); + + PreferencesUtil prefsUtil = PreferencesUtil.getInstance(); + + appExecutors.diskIO().execute(() -> { + try { + String baseEntityId = JsonFormUtils.getFieldValue(JsonFormUtils.fields(jsonForm), Constants.JsonForm.FAMILY_MEMBER); + jsonForm.put(ENTITY_ID, baseEntityId); + org.smartregister.domain.Event event = baseInteractor.saveEvent(jsonForm, eventType, CASE_CONFIRMATION); + Client client = eventClientRepository.fetchClientByBaseEntityId(event.getBaseEntityId()); + String taskID = event.getDetails().get(Constants.Properties.TASK_IDENTIFIER); + String businessStatus = clientProcessor.calculateBusinessStatus(event); + Task task = taskRepository.getTaskByIdentifier(taskID); + task.setForEntity(baseEntityId); + task.setBusinessStatus(businessStatus); + task.setStatus(Task.TaskStatus.COMPLETED); + task.setSyncStatus(BaseRepository.TYPE_Created); + taskRepository.addOrUpdate(task); + Set removedTasks = new HashSet<>(); + for (Task bloodScreeningTask : taskRepository.getTasksByEntityAndCode(prefsUtil.getCurrentPlanId(), + Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId(), baseEntityId, BLOOD_SCREENING)) { + bloodScreeningTask.setStatus(Task.TaskStatus.CANCELLED); + bloodScreeningTask.setSyncStatus(BaseRepository.TYPE_Created); + taskRepository.addOrUpdate(bloodScreeningTask); + removedTasks.add(bloodScreeningTask); + } + RevealApplication.getInstance().setSynced(false); + clientProcessor.processClient(Collections.singletonList(new EventClient(event, client)), true); + appExecutors.mainThread().execute(() -> { + ((StructureTasksContract.Presenter) presenterCallBack).onIndexConfirmationFormSaved(taskID, Task.TaskStatus.COMPLETED, businessStatus, removedTasks); + }); + } catch (Exception e) { + Timber.e("Error saving case confirmation data"); + } + }); + } + + @Override + public String calculateBusinessStatus(@NonNull org.smartregister.domain.Event event) { + return ((RevealClientProcessor) RevealApplication.getInstance().getClientProcessor()).calculateBusinessStatus(event); + } + + @Override + public String getCurrentPlanId() { + return PreferencesUtil.getInstance().getCurrentPlanId(); + } + + @Override + public boolean getSynced() { + return RevealApplication.getInstance().getSynced(); + } + + @Override + public void setSynced(boolean synced) { + RevealApplication.getInstance().setSynced(synced); + } + + @Override + public boolean isMyLocationComponentEnabled() { + return RevealApplication.getInstance().isMyLocationComponentEnabled(); + } + + @Override + public void setMyLocationComponentEnabled(boolean myLocationComponentEnabled) { + RevealApplication.getInstance().setMyLocationComponentEnabled(myLocationComponentEnabled); + } + + @Override + public Task generateTaskFromStructureType(@NonNull Context context, @NonNull String structureId, @NonNull String structureType) { + /*TaskUtils taskUtils = TaskUtils.getInstance(); + Task task = null; + if (Constants.StructureType.RESIDENTIAL.equals(structureType) && Utils.isFocusInvestigationOrMDA()) { + task = taskUtils.generateRegisterFamilyTask(applicationContext, structure.getId()); + } else { + if (Constants.StructureType.RESIDENTIAL.equals(structureType)) { + task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), + Constants.BusinessStatus.NOT_VISITED, Constants.Intervention.IRS, R.string.irs_task_description); + } else if (Constants.StructureType.MOSQUITO_COLLECTION_POINT.equals(structureType)) { + task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), + Constants.BusinessStatus.NOT_VISITED, Constants.Intervention.MOSQUITO_COLLECTION, R.string.mosquito_collection_task_description); + } else if (Constants.StructureType.LARVAL_BREEDING_SITE.equals(structureType)) { + task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), + Constants.BusinessStatus.NOT_VISITED, Constants.Intervention.LARVAL_DIPPING, R.string.larval_dipping_task_description); + } else if (Constants.StructureType.POTENTIAL_AREA_OF_TRANSMISSION.equals(structureType)) { + task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), + Constants.BusinessStatus.NOT_VISITED, PAOT, R.string.poat_task_description); + } + }*/ + return null; + } + + @Override + public void saveLocationInterventionForm(BaseContract.BaseInteractor baseInteractor, BaseContract.BasePresenter presenterCallBack, JSONObject jsonForm) { + AppExecutors appExecutors = RevealApplication.getInstance().getAppExecutors(); + RevealClientProcessor clientProcessor = (RevealClientProcessor) RevealApplication.getInstance().getClientProcessor(); + String encounterType = null; + String interventionType = null; + try { + encounterType = jsonForm.getString(Constants.JsonForm.ENCOUNTER_TYPE); + if (encounterType.equals(Constants.SPRAY_EVENT)) { + interventionType = IRS; + } else if (encounterType.equals(Constants.MOSQUITO_COLLECTION_EVENT)) { + interventionType = MOSQUITO_COLLECTION; + } else if (encounterType.equals(Constants.LARVAL_DIPPING_EVENT)) { + interventionType = LARVAL_DIPPING; + } else if (encounterType.equals(Constants.BEDNET_DISTRIBUTION_EVENT)) { + interventionType = BEDNET_DISTRIBUTION; + } else if (encounterType.equals(Constants.BEHAVIOUR_CHANGE_COMMUNICATION)) { + interventionType = BCC; + } else if (encounterType.equals(Constants.EventType.PAOT_EVENT)) { + interventionType = PAOT; + } else if (encounterType.equals(Constants.EventType.MDA_DISPENSE)) { + interventionType = Constants.Intervention.MDA_DISPENSE; + } else if (encounterType.equals(Constants.EventType.MDA_ADHERENCE)) { + interventionType = Constants.Intervention.MDA_ADHERENCE; + } else if (encounterType.equals(Constants.EventType.IRS_VERIFICATION)) { + interventionType = Constants.Intervention.IRS_VERIFICATION; + } + } catch (JSONException e) { + Timber.e(e); + } + + final String finalInterventionType = interventionType; + final String finalEncounterType = encounterType; + Runnable runnable = new Runnable() { + @Override + public void run() { + try { + org.smartregister.domain.Event event = baseInteractor.saveEvent(jsonForm, finalEncounterType, Constants.STRUCTURE); + clientProcessor.processClient(Collections.singletonList(new EventClient(event, null)), true); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + String businessStatus = clientProcessor.calculateBusinessStatus(event); + String taskID = event.getDetails().get(Constants.Properties.TASK_IDENTIFIER); + presenterCallBack.onFormSaved(event.getBaseEntityId(), taskID, Task.TaskStatus.COMPLETED, businessStatus, finalInterventionType); + } + }); + } catch (JSONException e) { + Timber.e(e, "Error saving saving Form "); + presenterCallBack.onFormSaveFailure(finalEncounterType); + } + } + }; + + appExecutors.diskIO().execute(runnable); + } + + @Override + public void saveJsonForm(BaseContract.BaseInteractor baseInteractor, String json) { + + try { + JSONObject jsonForm = new JSONObject(json); + String encounterType = jsonForm.getString(ENCOUNTER_TYPE); + boolean refreshMapOnEventSaved = true; + switch (encounterType) { + case REGISTER_STRUCTURE_EVENT: + baseInteractor.saveRegisterStructureForm(jsonForm); + break; + case Constants.EventType.MDA_DISPENSE: + case BLOOD_SCREENING_EVENT: + case Constants.EventType.MDA_ADHERENCE: + baseInteractor.saveMemberForm(jsonForm, encounterType, BLOOD_SCREENING); + break; + + case CASE_CONFIRMATION_EVENT: + baseInteractor.saveCaseConfirmation(jsonForm, encounterType); + break; + default: + baseInteractor.saveLocationInterventionForm(jsonForm); + if (!encounterType.equals(BEDNET_DISTRIBUTION_EVENT) && !encounterType.equals(Constants.EventType.IRS_VERIFICATION)) { + refreshMapOnEventSaved = false; + } + break; + } + RevealApplication.getInstance().setRefreshMapOnEventSaved(refreshMapOnEventSaved); + } catch (Exception e) { + Timber.e(e, "Error saving Json Form data"); + } + } + + @Override + public void openFilterActivity(Activity activity, TaskFilterParams filterParams) { + Intent intent = new Intent(activity, FilterTasksActivity.class); + intent.putExtra(Constants.Filter.FILTER_SORT_PARAMS, filterParams); + activity.startActivityForResult(intent, Constants.RequestCode.REQUEST_CODE_FILTER_TASKS); + } + + @Override + public void openFamilyProfile(Activity activity, CommonPersonObjectClient family, BaseTaskDetails taskDetails) { + Intent intent = new Intent(activity, org.smartregister.family.util.Utils.metadata().profileActivity); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_BASE_ENTITY_ID, family.getCaseId()); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_HEAD, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.FAMILY_HEAD, false)); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.PRIMARY_CAREGIVER, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.PRIMARY_CAREGIVER, false)); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_NAME, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.FIRST_NAME, false)); + intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.GO_TO_DUE_PAGE, false); + + + intent.putExtra(Constants.Properties.LOCATION_UUID, taskDetails.getStructureId()); + intent.putExtra(Constants.Properties.TASK_IDENTIFIER, taskDetails.getTaskId()); + intent.putExtra(Constants.Properties.TASK_BUSINESS_STATUS, taskDetails.getBusinessStatus()); + intent.putExtra(Constants.Properties.TASK_STATUS, taskDetails.getTaskStatus()); + + activity.startActivity(intent); + } + + @Override + public void setTaskDetails(Activity activity, TaskRegisterAdapter taskAdapter, List tasks) { + taskAdapter.setTaskDetails(tasks); + if (BuildConfig.BUILD_COUNTRY == Country.ZAMBIA) { + new IndicatorsCalculatorTask(activity, tasks).execute(); + } + } + + @Override + public void showNotFoundPopup(Activity activity, String opensrpId) { + if (activity != null) { + NoMatchDialogFragment.launchDialog((BaseRegisterActivity) activity, "dialog", opensrpId); + } + + } + + @Override + public void startMapActivity(Activity activity, String searchViewText, TaskFilterParams taskFilterParams) { + Intent intent = new Intent(activity, ListTasksActivity.class); + if (taskFilterParams != null) { + taskFilterParams.setSearchPhrase(searchViewText); + intent.putExtra(FILTER_SORT_PARAMS, taskFilterParams); + } else if (StringUtils.isNotBlank(searchViewText)) { + intent.putExtra(FILTER_SORT_PARAMS, new TaskFilterParams(searchViewText)); + } + + activity.setResult(RESULT_OK, intent); + activity.finish(); + } + + @Override + public void onTaskRegisterBindViewHolder(@NonNull Context context, @NonNull TaskRegisterViewHolder viewHolder, @NonNull View.OnClickListener registerActionHandler, @NonNull TaskDetails task, int position) { + Float distance = task.getDistanceFromUser(); + String name = task.getStructureName(); + String action = null; + boolean hasIcon = false; + if (Constants.Intervention.IRS.equals(task.getTaskCode())) { + if (name == null) { + name = task.getFamilyName() != null ? task.getFamilyName() : task.getStructureName() != null ? task.getStructureName() : context.getString(R.string.unenumerated_structure); + } + action = context.getString(R.string.record_status); + } else if (Constants.Intervention.MOSQUITO_COLLECTION.equals(task.getTaskCode())) { + name = context.getString(R.string.mosquito_collection_point); + action = context.getString(R.string.record_mosquito_collection); + } else if (Constants.Intervention.LARVAL_DIPPING.equals(task.getTaskCode())) { + name = context.getString(R.string.larval_breeding_site); + action = context.getString(R.string.record_larvacide); + } else if (Constants.Intervention.BCC.equals(task.getTaskCode())) { + viewHolder.setIcon(R.drawable.ic_bcc); + name = context.getString(R.string.bcc); + action = context.getString(R.string.record_bcc); + hasIcon = true; + } else if (Constants.Intervention.CASE_CONFIRMATION.equals(task.getTaskCode()) && task.getTaskCount() == null) { + viewHolder.setIcon(R.drawable.ic_classification_details); + viewHolder.setItemViewListener(task, registerActionHandler); + name = context.getString(R.string.classification_details); + action = context.getString(R.string.view); + hasIcon = true; + } else if (Constants.Intervention.PAOT.equals(task.getTaskCode())) { + name = context.getString(R.string.card_view_paot); + if (task.getBusinessStatus() != null) { + action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); + } + } else { + name = NOT_ELIGIBLE.equals(task.getBusinessStatus()) ? context.getString(R.string.ineligible_location) : task.getFamilyName(); + if (name == null) { + name = task.getStructureName() != null ? task.getStructureName() : context.getString(R.string.unenumerated_structure); + } + if (task.getBusinessStatus() != null) { + action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); + } + } + viewHolder.setTaskName(name); + CardDetails cardDetails = new CardDetails(task.getBusinessStatus()); + if (Task.TaskStatus.COMPLETED.name().equals(task.getTaskStatus())) { + if (task.getBusinessStatus() != null) { + action = CardDetailsUtil.getTranslatedBusinessStatus(task.getBusinessStatus()).replaceAll(" ", "\n"); + } + CardDetailsUtil.formatCardDetails(cardDetails); + } + viewHolder.setTaskAction(action, task, cardDetails, registerActionHandler); + viewHolder.setDistanceFromStructure(distance, task.isDistanceFromCenter()); + viewHolder.setTaskDetails(task.getBusinessStatus(), task.getTaskDetails()); + if (hasIcon) { + viewHolder.hideDistanceFromStructure(); + } else { + viewHolder.hideIcon(); + } + + if (StringUtils.isNotEmpty(task.getHouseNumber())) { + viewHolder.showHouseNumber(); + viewHolder.setHouseNumber(context.getString(R.string.numero_sign) + " " + task.getHouseNumber()); + } else { + viewHolder.hideHouseNumber(); + } + } + + @NonNull + @Override + public org.smartregister.util.AppExecutors getAppExecutors() { + return RevealApplication.getInstance().getAppExecutors(); + } +} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/AvailableOfflineMapsContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/AvailableOfflineMapsContract.java deleted file mode 100644 index 846bbf9b2b..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/AvailableOfflineMapsContract.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.smartregister.reveal.contract; - -import org.smartregister.reveal.model.OfflineMapModel; - -import java.util.List; - -public interface AvailableOfflineMapsContract extends OfflineMapsFragmentContract { - - interface Presenter { - - void fetchAvailableOAsForMapDownLoad(List locationIds); - - void onFetchAvailableOAsForMapDownLoad(List offlineMapModels); - - void onDownloadStarted(String operationalAreaId); - - void onDownloadComplete(String operationalAreaId); - - void onDownloadStopped(String operationalAreaId); - - } - - interface View { - - void setOfflineMapModelList(List offlineMapModelList); - - void disableCheckBox(String operationalAreaId); - - void enableCheckBox(String operationalAreaId); - - void moveDownloadedOAToDownloadedList(String operationalAreaId); - - void removeOperationalAreaToDownload(String operationalAreaId); - - } - - interface Interactor { - - void fetchAvailableOAsForMapDownLoad(List locationIds); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseContract.java deleted file mode 100644 index bb49df69e5..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseContract.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.smartregister.reveal.contract; - -import androidx.annotation.NonNull; - -import com.mapbox.geojson.Feature; - -import org.json.JSONArray; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.domain.Task; - -/** - * Created by samuelgithengi on 3/25/19. - */ -public interface BaseContract { - - interface BasePresenter { - - void onFormSaved(@NonNull String structureId, - String taskID, @NonNull Task.TaskStatus taskStatus, @NonNull String businessStatus, String interventionType); - - void onStructureAdded(Feature feature, JSONArray featureCoordinates, double zoomlevel); - - void onFormSaveFailure(String eventType); - - void onFamilyFound(CommonPersonObjectClient finalFamily); - } - - interface BaseInteractor { - - void saveJsonForm(String json); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseDrawerContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseDrawerContract.java deleted file mode 100644 index 8740c95477..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseDrawerContract.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.smartregister.reveal.contract; - -import android.app.Activity; -import androidx.annotation.StringRes; -import androidx.core.util.Pair; - -import org.smartregister.domain.PlanDefinition; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * Created by samuelgithengi on 3/21/19. - */ -public interface BaseDrawerContract { - - interface DrawerActivity { - void onDrawerClosed(); - - Activity getActivity(); - } - - interface View { - - Activity getContext(); - - void initializeDrawerLayout(); - - void setPlan(String campaign); - - void setOperationalArea(String operationalArea); - - String getPlan(); - - String getOperationalArea(); - - void setDistrict(String district); - - void setFacility(String facility, String facilityLevel); - - void setOperator(); - - void unlockNavigationDrawer(); - - void lockNavigationDrawerForSelection(); - - void showOperationalAreaSelector(Pair> locationHierarchy); - - void showPlanSelector(List campaigns, String entireTreeString); - - void displayNotification(int title, @StringRes int message, Object... formatArgs); - - void openDrawerLayout(); - - Presenter getPresenter(); - - void onResume(); - - void openOfflineMapsView(); - - void checkSynced(); - } - - interface Presenter { - - void onDrawerClosed(); - - void onShowOperationalAreaSelector(); - - void onOperationalAreaSelectorClicked(ArrayList name); - - void onShowPlanSelector(); - - void onPlanSelectorClicked(ArrayList value, ArrayList name); - - void onPlansFetched(Set planDefinitionSet); - - boolean isChangedCurrentSelection(); - - void setChangedCurrentSelection(boolean changedCurrentSelection); - - View getView(); - - void onViewResumed(); - - void onShowOfflineMaps(); - - boolean isPlanAndOperationalAreaSelected(); - - void onPlanValidated(boolean isValid); - - void updateSyncStatusDisplay(boolean synced); - } - - interface Interactor { - - void fetchPlans(String jurisdictionName); - - void validateCurrentPlan(String selectedOperationalArea, String currentPlanId); - - void checkSynced(); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseFormFragmentContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseFormFragmentContract.java deleted file mode 100644 index c90dfe69b2..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/BaseFormFragmentContract.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.smartregister.reveal.contract; - -import androidx.core.util.Pair; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObject; -import org.smartregister.domain.Location; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.util.RevealJsonFormUtils; - -/** - * Created by samuelgithengi on 4/18/19. - */ -public interface BaseFormFragmentContract { - - interface Presenter extends UserLocationContract.UserLocationCallback, PasswordRequestCallback { - - void onStructureFound(Location structure, BaseTaskDetails details); - - void onFetchedMembersCount(Pair numberOfMembers, JSONObject formJSON); - - void onFetchedFamilyMembers(JSONArray familyMembers, JSONObject formJSON); - - void onFetchedSprayDetails(CommonPersonObject commonPersonObject, JSONObject formJSON); - } - - interface View extends UserLocationContract.UserLocationView { - void displayToast(String format); - - RevealJsonFormUtils getJsonFormUtils(); - - void startForm(JSONObject formJSON); - - void displayError(int title, int message); - } - - interface Interactor { - - void findNumberOfMembers(String structureId, JSONObject formJSON); - - void findMemberDetails(String structureId, JSONObject formJSON); - - void findSprayDetails(String interventionType, String structureId, JSONObject formJSON); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/CaseClassificationContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/CaseClassificationContract.java deleted file mode 100644 index e46be5da24..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/CaseClassificationContract.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.smartregister.reveal.contract; - -import org.json.JSONObject; - -public interface CaseClassificationContract { - - interface View { - void displayIndexCase(JSONObject indexCase); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/DownloadedOfflineMapsContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/DownloadedOfflineMapsContract.java deleted file mode 100644 index d7d03748c9..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/DownloadedOfflineMapsContract.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.smartregister.reveal.contract; - -import androidx.core.util.Pair; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.reveal.model.OfflineMapModel; - -import java.util.List; -import java.util.Map; - -public interface DownloadedOfflineMapsContract extends OfflineMapsFragmentContract { - - interface Presenter { - - void onDeleteDownloadMap(List offlineMapModels); - - void fetchOAsWithOfflineDownloads(Pair, Map> offlineRegionInfo); - - void onOAsWithOfflineDownloadsFetched(List downloadedOfflineMapModelList); - } - - interface View { - - void setDownloadedOfflineMapModelList(List downloadedOfflineMapModelList); - - void deleteDownloadedOfflineMaps(); - - } - - interface Interactor { - - void fetchLocationsWithOfflineMapDownloads(Pair, Map> offlineRegionInfo); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/FilterTasksContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/FilterTasksContract.java deleted file mode 100644 index 18c3ebb69b..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/FilterTasksContract.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.smartregister.reveal.contract; - -import android.content.Intent; -import androidx.annotation.StringRes; - -import com.google.android.flexbox.FlexboxLayout; - -import org.smartregister.reveal.model.TaskFilterParams; - -import java.util.List; - -/** - * Created by samuelgithengi on 12/18/19. - */ -public interface FilterTasksContract { - - interface View { - - void onFiltedSelected(int size); - - void applyFilters(Intent intent); - - FlexboxLayout getBusinessStatusLayout(); - - FlexboxLayout getTaskCodeLayout(); - - FlexboxLayout getInterventionTypeLayout(); - - void setSortBySelection(int sortBySpinner); - } - - interface Presenter { - - @StringRes - Integer getStringResource(String intervention); - - void onToggleChanged(boolean isChecked, Object filterCategory, Object filterKey); - - List getIntentionTypes(); - - List getBusinessStatusOptions(); - - void onApplyFilters(String selectedItem); - - void restoreCheckedFilters(TaskFilterParams taskFilterParams); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/ListTaskContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/ListTaskContract.java index d79e807265..fa23de7eb1 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/ListTaskContract.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/ListTaskContract.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.contract; import android.content.Context; + import androidx.annotation.NonNull; import androidx.annotation.StringRes; @@ -12,11 +13,13 @@ import org.json.JSONObject; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.domain.Task; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationView; -import org.smartregister.reveal.model.CardDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; import org.smartregister.reveal.util.RevealJsonFormUtils; +import org.smartregister.tasking.contract.BaseContract; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.tasking.contract.UserLocationContract; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.model.TaskFilterParams; import java.util.List; @@ -25,7 +28,7 @@ */ public interface ListTaskContract { - interface ListTaskView extends UserLocationView, BaseDrawerContract.DrawerActivity { + interface ListTaskView extends UserLocationContract.UserLocationView, BaseDrawerContract.DrawerActivity { void showProgressDialog(@StringRes int title, @StringRes int message); diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapDownloadCallback.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapDownloadCallback.java deleted file mode 100644 index ca5142ad95..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapDownloadCallback.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.smartregister.reveal.contract; - -import org.smartregister.reveal.model.OfflineMapModel; - -public interface OfflineMapDownloadCallback { - - void onMapDownloaded(OfflineMapModel offlineMapModel); - - void onOfflineMapDeleted(OfflineMapModel offlineMapModel); -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapsFragmentContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapsFragmentContract.java deleted file mode 100644 index 3f39c3803f..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OfflineMapsFragmentContract.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.smartregister.reveal.contract; - -public interface OfflineMapsFragmentContract { - - interface View { - - void displayToast(String message); - - void displayError(int title, String message); - - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsContract.java index ff22335514..f60eea6330 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsContract.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsContract.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.contract; import org.json.JSONObject; +import org.smartregister.tasking.contract.BaseContract; public interface OtherFormsContract { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsfragmentContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsfragmentContract.java index b054f37c0a..89e0c12aac 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsfragmentContract.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/OtherFormsfragmentContract.java @@ -2,6 +2,8 @@ import android.content.Context; +import org.smartregister.tasking.contract.BaseFormFragmentContract; + public interface OtherFormsfragmentContract { interface Presenter extends BaseFormFragmentContract.Presenter{ diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/PasswordRequestCallback.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/PasswordRequestCallback.java deleted file mode 100644 index 3ce164a295..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/PasswordRequestCallback.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.smartregister.reveal.contract; - -/** - * Created by samuelgithengi on 2/6/19. - */ -public interface PasswordRequestCallback { - - void onPasswordVerified(); -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/StructureTasksContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/StructureTasksContract.java index 7563c5806d..c60c1e56b1 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/StructureTasksContract.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/StructureTasksContract.java @@ -5,6 +5,9 @@ import org.smartregister.domain.Task; import org.smartregister.domain.Event; import org.smartregister.reveal.model.StructureTaskDetails; +import org.smartregister.tasking.contract.BaseContract; +import org.smartregister.tasking.contract.BaseFormFragmentContract; +import org.smartregister.tasking.contract.UserLocationContract; import java.util.List; import java.util.Set; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterContract.java deleted file mode 100644 index 9498b798bb..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterContract.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.smartregister.reveal.contract; - -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.domain.Task; -import org.smartregister.view.contract.BaseRegisterContract; - -import java.util.List; - -/** - * Created by samuelgithengi on 3/14/19. - */ -public interface TaskRegisterContract { - - interface Presenter extends BaseContract.BasePresenter { - void saveJsonForm(String json); - - void onFamilyFound(CommonPersonObjectClient finalFamily); - } - - interface Interactor { - - void registerViewConfigurations(List viewIdentifiers); - - void unregisterViewConfiguration(List viewIdentifiers); - - void cleanupResources(); - } - - interface View extends BaseRegisterContract.View { - void displayNotification(int title, int message); - - void openStructureProfile(CommonPersonObjectClient family, Task task, String structureId); - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterFragmentContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterFragmentContract.java deleted file mode 100644 index b2da5225de..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/TaskRegisterFragmentContract.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.smartregister.reveal.contract; - - -import android.content.Context; -import android.location.Location; -import androidx.annotation.StringRes; - -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.reveal.adapter.TaskRegisterAdapter; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.util.LocationUtils; -import org.smartregister.view.contract.BaseRegisterFragmentContract; - -import java.util.List; -import java.util.Set; - -/** - * Created by samuelgithengi on 3/18/19. - */ -public interface TaskRegisterFragmentContract { - - interface Presenter extends BaseRegisterFragmentContract.Presenter, BaseFormFragmentContract.Presenter, BaseContract.BasePresenter { - void onTasksFound(List tasks, int structuresWithinBuffer); - - void onDestroy(); - - void onDrawerClosed(); - - void onTaskSelected(TaskDetails details, boolean isActionClicked); - - @StringRes - int getInterventionLabel(); - - void onIndexCaseFound(JSONObject indexCase, boolean isLinkedToJurisdiction); - - void searchTasks(String searchText); - - void filterTasks(TaskFilterParams filterParams); - - void onFilterTasksClicked(); - - void setTaskFilterParams(TaskFilterParams filterParams); - - void onOpenMapClicked(); - - void resetTaskInfo(TaskDetails taskDetails); - - void onTaskInfoReset(); - } - - interface View extends BaseRegisterFragmentContract.View, BaseFormFragmentContract.View { - - Location getLastLocation(); - - void initializeAdapter(Set visibleColumns); - - void setTotalTasks(int structuresWithinBuffer); - - void setTaskDetails(List tasks); - - void displayNotification(int title, @StringRes int message, Object... formatArgs); - - void showProgressDialog(@StringRes int title, @StringRes int message); - - void hideProgressDialog(); - - LocationUtils getLocationUtils(); - - void setInventionType(int interventionLabel); - - void registerFamily(BaseTaskDetails taskDetails); - - void openFamilyProfile(CommonPersonObjectClient family, BaseTaskDetails taskDetails); - - void displayIndexCaseDetails(JSONObject indexCase); - - void setNumberOfFilters(int numberOfFilters); - - void clearFilter(); - - TaskRegisterAdapter getAdapter(); - - void openFilterActivity(TaskFilterParams filterParams); - - void setSearchPhrase(String searchPhrase); - - void startMapActivity(TaskFilterParams taskFilterParams); - } - - interface Interactor { - void resetTaskInfo(Context context, TaskDetails taskDetails); - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/UserLocationContract.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/UserLocationContract.java deleted file mode 100644 index fa49b117ee..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/contract/UserLocationContract.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.smartregister.reveal.contract; - -import android.location.Location; -import androidx.annotation.StringRes; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.smartregister.reveal.presenter.ValidateUserLocationPresenter; - -/** - * Created by samuelgithengi on 2/13/19. - */ -public interface UserLocationContract { - - - interface UserLocationPresenter { - - void requestUserLocation(); - - void onGetUserLocation(Location location); - - void onGetUserLocationFailed(); - - void waitForUserLocation(); - } - - interface UserLocationView { - - Location getUserCurrentLocation(); - - void showProgressDialog(@StringRes int title, @StringRes int message); - - void hideProgressDialog(); - - void requestUserLocation(); - } - - interface UserLocationCallback { - - void onLocationValidated(); - - LatLng getTargetCoordinates(); - - void requestUserPassword(); - - ValidateUserLocationPresenter getLocationPresenter(); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/AvailableOfflineMapsFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/AvailableOfflineMapsFragment.java deleted file mode 100644 index bf2de02ec1..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/AvailableOfflineMapsFragment.java +++ /dev/null @@ -1,260 +0,0 @@ -package org.smartregister.reveal.fragment; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.CheckBox; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.mapbox.geojson.Feature; - -import org.joda.time.DateTime; -import org.smartregister.domain.Location; -import org.smartregister.domain.LocationProperty; -import org.smartregister.reveal.R; -import org.smartregister.reveal.adapter.AvailableOfflineMapAdapter; -import org.smartregister.reveal.contract.AvailableOfflineMapsContract; -import org.smartregister.reveal.contract.OfflineMapDownloadCallback; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.presenter.AvailableOfflineMapsPresenter; -import org.smartregister.reveal.task.FileHttpServerTask; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.OfflineMapHelper; -import org.smartregister.util.DateTimeTypeConverter; -import org.smartregister.util.PropertiesConverter; - -import java.util.ArrayList; -import java.util.List; - -public class AvailableOfflineMapsFragment extends BaseOfflineMapsFragment implements AvailableOfflineMapsContract.View, View.OnClickListener { - - private RecyclerView offlineMapRecyclerView; - - private AvailableOfflineMapAdapter adapter; - - private AvailableOfflineMapsPresenter presenter; - - private List offlineMapModelList = new ArrayList<>(); - - private List operationalAreasToDownload = new ArrayList<>(); - - private OfflineMapDownloadCallback callback; - - private Button btnDownloadMap; - - private static Gson gson = new GsonBuilder().setDateFormat(Constants.DateFormat.EVENT_DATE_FORMAT_Z) - .registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()) - .registerTypeAdapter(LocationProperty.class, new PropertiesConverter()).create(); - - - public static AvailableOfflineMapsFragment newInstance(Bundle bundle) { - - AvailableOfflineMapsFragment fragment = new AvailableOfflineMapsFragment(); - if (bundle != null) { - fragment.setArguments(bundle); - } - fragment.setPresenter(new AvailableOfflineMapsPresenter(fragment)); - - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (presenter == null) { - presenter = new AvailableOfflineMapsPresenter(this); - } - btnDownloadMap = null; - - new FileHttpServerTask(getContext()).execute(); - - - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_offline_map, container, false); - setUpViews(view); - initializeAdapter(); - return view; - } - - private void setUpViews(View view) { - offlineMapRecyclerView = view.findViewById(R.id.offline_map_recyclerView); - - btnDownloadMap = view.findViewById(R.id.download_map); - - btnDownloadMap.setOnClickListener(this); - - } - - private void initializeAdapter() { - adapter = new AvailableOfflineMapAdapter(this.getContext(), this); - offlineMapRecyclerView.setAdapter(adapter); - if (offlineMapModelList != null) { - setOfflineMapModelList(offlineMapModelList); - } - - } - - @Override - public void setOfflineMapModelList(List offlineMapModelList) { - if (offlineMapModelList == null) { - return; - } - if (adapter == null) { - this.offlineMapModelList = offlineMapModelList; - } else { - adapter.setOfflineMapModels(offlineMapModelList); - this.offlineMapModelList = offlineMapModelList; - } - } - - public void updateOperationalAreasToDownload(View view) { - CheckBox checkBox = (CheckBox) view; - OfflineMapModel offlineMapModel = (OfflineMapModel) view.getTag(R.id.offline_map_checkbox); - - if (checkBox.isChecked()) { - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.SELECTED_FOR_DOWNLOAD); - operationalAreasToDownload.add(offlineMapModel.getLocation()); - } else { - operationalAreasToDownload.remove(offlineMapModel.getLocation()); - } - } - - @Override - public void disableCheckBox(String operationalAreaId) { - if (adapter ==null) { - return; - } - for (OfflineMapModel offlineMapModel: offlineMapModelList ) { - if (offlineMapModel.getDownloadAreaId().equals(operationalAreaId) - && offlineMapModel.getOfflineMapStatus() != OfflineMapModel.OfflineMapStatus.DOWNLOAD_STARTED){ - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.DOWNLOAD_STARTED); - } - } - - setOfflineMapModelList(offlineMapModelList); - } - - @Override - public void enableCheckBox(String operationalAreaId) { - if (adapter ==null) { - return; - } - for (OfflineMapModel offlineMapModel: offlineMapModelList ) { - if (offlineMapModel.getDownloadAreaId().equals(operationalAreaId) - && offlineMapModel.getOfflineMapStatus() != OfflineMapModel.OfflineMapStatus.DOWNLOADED){ - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.READY); - } - } - - setOfflineMapModelList(offlineMapModelList); - } - - @Override - public void moveDownloadedOAToDownloadedList(String operationalAreaId) { - List toRemoveFromAvailableList = new ArrayList<>(); - List toRemoveFromDownloadList = new ArrayList<>(); - for (OfflineMapModel offlineMapModel : offlineMapModelList) { - if (offlineMapModel.getDownloadAreaId().equals(operationalAreaId)) { - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.DOWNLOADED); - callback.onMapDownloaded(offlineMapModel); - toRemoveFromAvailableList.add(offlineMapModel); - toRemoveFromDownloadList.add(offlineMapModel.getLocation()); - setOfflineMapModelList(offlineMapModelList); - break; - } - } - - offlineMapModelList.removeAll(toRemoveFromAvailableList); - operationalAreasToDownload.removeAll(toRemoveFromDownloadList); - - } - - @Override - public void removeOperationalAreaToDownload(String operationalAreaId) { - List toRemove = new ArrayList<>(); - for (Location location: this.operationalAreasToDownload ) { - if (location.getId().equals(operationalAreaId)) { - toRemove.add(location); - } - } - - this.operationalAreasToDownload.removeAll(toRemove); - - } - - public void initiateMapDownload() { - - if (this.operationalAreasToDownload == null || this.operationalAreasToDownload.isEmpty()) { - displayToast(getString(R.string.select_offline_map_to_download)); - return; - } - - for (Location location: this.operationalAreasToDownload ) { - Feature operationalAreaFeature = Feature.fromJson(gson.toJson(location)); - String mapName = location.getId(); - currentMapDownload = mapName; - OfflineMapHelper.downloadMap(operationalAreaFeature, mapName, getActivity()); - } - } - - public void setOfflineMapDownloadCallback(OfflineMapDownloadCallback callBack) { - this.callback = callBack; - } - - @Override - protected void downloadCompleted(String mapUniqueName) { - presenter.onDownloadComplete(mapUniqueName); - } - - @Override - protected void downloadStarted(String mapUniqueName) { - presenter.onDownloadStarted(mapUniqueName); - } - - @Override - protected void mapDeletedSuccessfully(String mapUniqueName) { - // Do nothing - } - - @Override - protected void downloadStopped(String mapUniqueName) { - presenter.onDownloadStopped(mapUniqueName); - } - - public void updateOperationalAreasToDownload(OfflineMapModel offlineMapModel){ - offlineMapModelList.add(offlineMapModel); - setOfflineMapModelList(offlineMapModelList); - } - - public void setOfflineDownloadedMapNames (List offlineRegionNames) { - presenter.fetchAvailableOAsForMapDownLoad(offlineRegionNames); - } - - public void setPresenter(AvailableOfflineMapsPresenter presenter) { - this.presenter = presenter; - } - - @Override - public void onClick(View view) { - switch (view.getId()) { - case R.id.offline_map_checkbox: - updateOperationalAreasToDownload(view); - break; - case R.id.download_map: - initiateMapDownload(); - break; - default: - break; - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/BaseOfflineMapsFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/BaseOfflineMapsFragment.java deleted file mode 100644 index c4cd921223..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/BaseOfflineMapsFragment.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.smartregister.reveal.fragment; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.Bundle; -import androidx.fragment.app.Fragment; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import android.text.TextUtils; -import android.widget.Toast; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.OfflineMapsFragmentContract; - -import io.ona.kujaku.services.MapboxOfflineDownloaderService; -import io.ona.kujaku.utils.Constants; -import timber.log.Timber; - -public abstract class BaseOfflineMapsFragment extends Fragment implements OfflineMapsFragmentContract.View { - - private MapDownloadReceiver mapDownloadReceiver = new MapDownloadReceiver(); - - private String mapUniqueName; - private String resultStatus; - private String message; - private MapboxOfflineDownloaderService.SERVICE_ACTION serviceAction; - - protected String currentMapDownload; - - @Override - public void onResume() { - super.onResume(); - IntentFilter intentFilter = new IntentFilter(Constants.INTENT_ACTION_MAP_DOWNLOAD_SERVICE_STATUS_UPDATES); - LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver(mapDownloadReceiver, intentFilter); - } - - @Override - public void onPause() { - super.onPause(); - LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).unregisterReceiver(mapDownloadReceiver); - } - - @Override - public void displayToast(String message) { - Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show(); - } - - @Override - public void displayError(int title, String message) { - Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show(); - } - - public class MapDownloadReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle != null) { - Timber.i( intent.getExtras().toString()); - if (bundle.containsKey(MapboxOfflineDownloaderService.KEY_RESULT_STATUS) - && bundle.containsKey(MapboxOfflineDownloaderService.KEY_RESULT_MESSAGE) - && bundle.containsKey(MapboxOfflineDownloaderService.KEY_RESULTS_PARENT_ACTION) - && bundle.containsKey(Constants.PARCELABLE_KEY_MAP_UNIQUE_NAME)) { - - mapUniqueName = bundle.getString(Constants.PARCELABLE_KEY_MAP_UNIQUE_NAME); - resultStatus = bundle.getString(MapboxOfflineDownloaderService.KEY_RESULT_STATUS); - serviceAction = (MapboxOfflineDownloaderService.SERVICE_ACTION) bundle.get(MapboxOfflineDownloaderService.KEY_RESULTS_PARENT_ACTION); - - message = bundle.getString(MapboxOfflineDownloaderService.KEY_RESULT_MESSAGE); - - if (MapboxOfflineDownloaderService.SERVICE_ACTION_RESULT.FAILED.name().equals(resultStatus)) { - handleFailureResponse(); - } else { - handleSuccessResponse(); - } - } - } else { - Timber.i( "Broadcast message has null Extras"); - } - - } - } - - public void handleFailureResponse() { - if (!TextUtils.isEmpty(message) && - (!message.contains("MapBox Tile Count limit exceeded") - || serviceAction == MapboxOfflineDownloaderService.SERVICE_ACTION.DELETE_MAP)) { - displayError(R.id.download_map, message); - } - - } - - public void handleSuccessResponse() { - // We should disable the stop offline download button if it was stopped successfully - if (serviceAction == MapboxOfflineDownloaderService.SERVICE_ACTION.STOP_CURRENT_DOWNLOAD) { - currentMapDownload = null; - downloadStopped(mapUniqueName); - } else if (serviceAction == MapboxOfflineDownloaderService.SERVICE_ACTION.DELETE_MAP) { - mapDeletedSuccessfully(mapUniqueName); - } else { - if (!TextUtils.isEmpty(message)) { - // This is a download progress message - if (isValidDouble(message)) { - if (Double.valueOf(message) == 100d) { - currentMapDownload = null; - displayToast(getString(R.string.download_finished_successfuly)); - downloadCompleted(mapUniqueName); - // setCanStopMapDownload(false); - } else { - // setCanStopMapDownload(true); - displayToast(getString(R.string.map_download_progress, Double.valueOf(message))); - downloadStarted(mapUniqueName); - } - } else { - displayToast(message); - } - } - } - } - - protected boolean isValidDouble(String doubleString) { - String doubleRegex = "[+-]{0,1}[0-9]*.{0,1}[0-9]*"; - return (!doubleString.isEmpty() && doubleString.matches(doubleRegex)); - } - - protected abstract void downloadCompleted(String mapUniqueName); - - protected abstract void downloadStarted(String mapUniqueName); - - protected abstract void mapDeletedSuccessfully(String mapUniqueName); - - protected abstract void downloadStopped(String mapUniqueName); -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/CaseClassificationFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/CaseClassificationFragment.java deleted file mode 100644 index b413b5da86..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/CaseClassificationFragment.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.smartregister.reveal.fragment; - -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import org.json.JSONObject; -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.CaseClassificationContract; -import org.smartregister.reveal.util.Constants; -import org.smartregister.util.Utils; - -public class CaseClassificationFragment extends Fragment implements CaseClassificationContract.View { - - private TextView familyNameTextView; - private TextView villageTextView; - private TextView quarterTextView; - private TextView streetTextView; - private TextView landmarkTextView; - - private TextView surnameTextView; - private TextView firstNameTextView; - private TextView middleNameTextView; - private TextView dobTextView; - - private TextView caseNumberTextView; - private TextView caseClassificationTextView; - private TextView focusStatusTextView; - private TextView focusReasonTextView; - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.frament_case_classification, container, false); - initializeViews(rootView); - Toolbar toolbar = rootView.findViewById(R.id.toolbar); - toolbar.setTitle(R.string.return_to_register); - AppCompatActivity activity = (AppCompatActivity) getActivity(); - activity.setSupportActionBar(toolbar); - activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - return rootView; - } - - private void initializeViews(View rootView) { - familyNameTextView = rootView.findViewById(R.id.family_name); - villageTextView = rootView.findViewById(R.id.village_town); - quarterTextView = rootView.findViewById(R.id.quarter_clan); - streetTextView = rootView.findViewById(R.id.street); - landmarkTextView = rootView.findViewById(R.id.landmark); - - surnameTextView = rootView.findViewById(R.id.surname); - firstNameTextView = rootView.findViewById(R.id.first_name); - middleNameTextView = rootView.findViewById(R.id.middle_name); - dobTextView = rootView.findViewById(R.id.dob); - - caseNumberTextView = rootView.findViewById(R.id.case_number); - caseClassificationTextView = rootView.findViewById(R.id.case_classification); - focusStatusTextView = rootView.findViewById(R.id.focus_status); - focusReasonTextView = rootView.findViewById(R.id.focus_reason); - } - - @Override - public void displayIndexCase(@NonNull JSONObject indexCase) { - JSONObject details = indexCase.optJSONObject(Constants.DETAILS); - if (details == null) { - details = new JSONObject(); - } - familyNameTextView.setText(getString(R.string.family_name_format, details.optString("family_name"))); - villageTextView.setText(getString(R.string.village_town_format, details.optString("village_town"))); - quarterTextView.setText(getString(R.string.quarter_clan_format, details.optString("quarter_clan"))); - streetTextView.setText(getString(R.string.street_format, details.optString("street"))); - landmarkTextView.setText(getString(R.string.landmark_format, details.optString("landmark"))); - - surnameTextView.setText(getString(R.string.surname_format, details.optString("surname"))); - firstNameTextView.setText(getString(R.string.first_name_format, details.optString("first_name"))); - middleNameTextView.setText(getString(R.string.middle_name_format, details.optString("middle_name"))); - int age = details.optInt("age", -1); - dobTextView.setText(getString(R.string.dob_format, age == -1 ? "" : Utils.getDob(age))); - - caseNumberTextView.setText(getString(R.string.case_number_format, details.optString("case_number"))); - caseClassificationTextView.setText(getString(R.string.case_classification_format, details.optString("case_classification"))); - focusStatusTextView.setText(getString(R.string.focus_status_format, details.optString("focus_status"))); - focusReasonTextView.setText(getString(R.string.focus_reason_format, details.optString("focus_reason"))); - - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/DownloadedOfflineMapsFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/DownloadedOfflineMapsFragment.java deleted file mode 100644 index 2e9bff9af9..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/DownloadedOfflineMapsFragment.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.smartregister.reveal.fragment; - -import android.content.Context; -import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.core.content.ContextCompat; -import androidx.core.util.Pair; -import androidx.recyclerview.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.CheckBox; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.adapter.DownloadedOfflineMapAdapter; -import org.smartregister.reveal.contract.DownloadedOfflineMapsContract; -import org.smartregister.reveal.contract.OfflineMapDownloadCallback; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.presenter.DownloadedOfflineMapsPresenter; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import io.ona.kujaku.helpers.OfflineServiceHelper; - -public class DownloadedOfflineMapsFragment extends BaseOfflineMapsFragment implements DownloadedOfflineMapsContract.View, View.OnClickListener { - - private RecyclerView downloadedMapsRecyclerView; - - private DownloadedOfflineMapAdapter adapter; - - private DownloadedOfflineMapsPresenter presenter; - - private List downloadedOfflineMapModelList = new ArrayList<>(); - - private List offlineMapsTodelete = new ArrayList<>(); - - private OfflineMapDownloadCallback callback; - - public static DownloadedOfflineMapsFragment newInstance(Bundle bundle, Context context) { - - DownloadedOfflineMapsFragment fragment = new DownloadedOfflineMapsFragment(); - if (bundle != null) { - fragment.setArguments(bundle); - } - fragment.setPresenter(new DownloadedOfflineMapsPresenter(fragment, context)); - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - if (presenter == null) { - presenter = new DownloadedOfflineMapsPresenter(this, getContext()); - } - } - - @Override - protected void downloadCompleted(String mapUniqueName) { - // Do nothing - } - - @Override - protected void downloadStarted(String mapUniqueName) { - // Do nothing - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.fragment_offline_map, container, false); - setUpViews(view); - initializeAdapter(); - return view; - } - - private void setUpViews(View view) { - downloadedMapsRecyclerView = view.findViewById(R.id.offline_map_recyclerView); - - Button btnDeleteMap = view.findViewById(R.id.download_map); - btnDeleteMap.setText(getString(R.string.delete).toUpperCase()); - btnDeleteMap.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.delete_map_bg)); - - btnDeleteMap.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - presenter.onDeleteDownloadMap(offlineMapsTodelete); - } - }); - - } - - private void initializeAdapter() { - adapter = new DownloadedOfflineMapAdapter(this.getContext(), this); - downloadedMapsRecyclerView.setAdapter(adapter); - if (downloadedOfflineMapModelList != null) { - setDownloadedOfflineMapModelList(downloadedOfflineMapModelList); - } - } - - public void updateOfflineMapsTodelete(View view) { - CheckBox checkBox = (CheckBox) view; - OfflineMapModel offlineMapModel = (OfflineMapModel) view.getTag(R.id.offline_map_checkbox); - - if (checkBox.isChecked()) { - offlineMapsTodelete.add(offlineMapModel); - } else { - offlineMapsTodelete.remove(offlineMapModel); - } - } - - @Override - public void setDownloadedOfflineMapModelList(List downloadedOfflineMapModelList) { - if (downloadedOfflineMapModelList == null) { - return; - } else if (adapter == null) { - this.downloadedOfflineMapModelList = downloadedOfflineMapModelList; - } else { - adapter.setOfflineMapModels(downloadedOfflineMapModelList); - this.downloadedOfflineMapModelList = downloadedOfflineMapModelList; - } - } - - @Override - public void deleteDownloadedOfflineMaps() { - if (offlineMapsTodelete == null || offlineMapsTodelete.isEmpty()){ - displayToast(getString(R.string.select_offline_map_to_delete)); - return; - } - - for (OfflineMapModel offlineMapModel: offlineMapsTodelete) { - OfflineServiceHelper.deleteOfflineMap(getActivity(), - offlineMapModel.getDownloadAreaId(), - BuildConfig.MAPBOX_SDK_ACCESS_TOKEN); - } - } - - public void updateDownloadedMapsList(OfflineMapModel offlineMapModel){ - downloadedOfflineMapModelList.add(offlineMapModel); - setDownloadedOfflineMapModelList(downloadedOfflineMapModelList); - } - - @Override - protected void mapDeletedSuccessfully(String mapUniqueName) { - if (adapter ==null) { - return; - } - - List toRemove = new ArrayList<>(); - for (OfflineMapModel offlineMapModel: downloadedOfflineMapModelList ) { - if (offlineMapModel.getDownloadAreaId().equals(mapUniqueName)){ - toRemove.add(offlineMapModel); - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.READY); - callback.onOfflineMapDeleted(offlineMapModel); - } - } - downloadedOfflineMapModelList.removeAll(toRemove); - - setDownloadedOfflineMapModelList(downloadedOfflineMapModelList); - } - - @Override - protected void downloadStopped(String mapUniqueName) { - // Do nothing - } - - public void setOfflineMapDownloadCallback(OfflineMapDownloadCallback callBack) { - this.callback = callBack; - } - - public void setOfflineDownloadedMapNames (Pair, Map> offlineRegionInfo) { - if (offlineRegionInfo == null || offlineRegionInfo.first == null) { - return; - } - presenter.fetchOAsWithOfflineDownloads(offlineRegionInfo); - } - - public void setPresenter(DownloadedOfflineMapsPresenter presenter) { - this.presenter = presenter; - } - - @Override - public void onClick(View view) { - switch (view.getId()) { - case R.id.offline_map_checkbox: - updateOfflineMapsTodelete(view); - break; - default: - break; - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/StructureTasksFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/StructureTasksFragment.java index 98db90b1fc..a30d5e16b1 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/StructureTasksFragment.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/StructureTasksFragment.java @@ -6,12 +6,6 @@ import android.content.Intent; import android.location.Location; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.StringRes; -import com.google.android.material.tabs.TabLayout; -import androidx.fragment.app.Fragment; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -19,6 +13,14 @@ import android.widget.TextView; import android.widget.Toast; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.StringRes; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.RecyclerView; + +import com.google.android.material.tabs.TabLayout; + import org.json.JSONObject; import org.smartregister.domain.Task; import org.smartregister.reveal.R; @@ -26,10 +28,10 @@ import org.smartregister.reveal.contract.StructureTasksContract; import org.smartregister.reveal.model.StructureTaskDetails; import org.smartregister.reveal.presenter.StructureTasksPresenter; -import org.smartregister.reveal.util.AlertDialogUtils; -import org.smartregister.reveal.util.LocationUtils; -import org.smartregister.reveal.util.RevealJsonFormUtils; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.tasking.util.AlertDialogUtils; +import org.smartregister.tasking.util.LocationUtils; +import org.smartregister.tasking.util.RevealJsonFormUtils; import java.util.List; import java.util.Set; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/SummaryFormsFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/SummaryFormsFragment.java index 6b93f60e88..85a28eff9f 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/SummaryFormsFragment.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/SummaryFormsFragment.java @@ -4,22 +4,23 @@ import android.app.ProgressDialog; import android.location.Location; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + import org.json.JSONObject; import org.smartregister.reveal.R; import org.smartregister.reveal.contract.OtherFormsfragmentContract; import org.smartregister.reveal.presenter.OtherFormsFragmentPresenter; -import org.smartregister.reveal.util.LocationUtils; -import org.smartregister.reveal.util.RevealJsonFormUtils; import org.smartregister.reveal.view.SummaryFormsActivity; +import org.smartregister.tasking.util.LocationUtils; +import org.smartregister.tasking.util.RevealJsonFormUtils; public class SummaryFormsFragment extends Fragment implements OtherFormsfragmentContract.View, View.OnClickListener { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/TaskRegisterFragment.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/TaskRegisterFragment.java deleted file mode 100644 index 4c8316b70f..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/fragment/TaskRegisterFragment.java +++ /dev/null @@ -1,484 +0,0 @@ -package org.smartregister.reveal.fragment; - -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.ProgressDialog; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.IntentFilter; -import android.location.Location; -import android.os.Bundle; -import androidx.annotation.StringRes; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import androidx.cardview.widget.CardView; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.domain.Task; -import org.smartregister.family.fragment.NoMatchDialogFragment; -import org.smartregister.family.util.DBConstants; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.adapter.TaskRegisterAdapter; -import org.smartregister.reveal.contract.BaseDrawerContract; -import org.smartregister.reveal.contract.TaskRegisterFragmentContract; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.presenter.TaskRegisterFragmentPresenter; -import org.smartregister.reveal.task.IndicatorsCalculatorTask; -import org.smartregister.reveal.util.AlertDialogUtils; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.Constants.TaskRegister; -import org.smartregister.reveal.util.Country; -import org.smartregister.reveal.util.LocationUtils; -import org.smartregister.reveal.util.RevealJsonFormUtils; -import org.smartregister.reveal.util.Utils; -import org.smartregister.reveal.view.DrawerMenuView; -import org.smartregister.reveal.view.FilterTasksActivity; -import org.smartregister.reveal.view.ListTasksActivity; -import org.smartregister.reveal.view.TaskRegisterActivity; -import org.smartregister.view.activity.BaseRegisterActivity; -import org.smartregister.view.fragment.BaseRegisterFragment; - -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import io.ona.kujaku.utils.Constants; - -import static android.app.Activity.RESULT_CANCELED; -import static android.app.Activity.RESULT_OK; -import static android.content.DialogInterface.BUTTON_POSITIVE; -import static org.apache.commons.lang3.StringUtils.isEmpty; -import static org.smartregister.reveal.util.Constants.Action; -import static org.smartregister.reveal.util.Constants.Filter.FILTER_SORT_PARAMS; -import static org.smartregister.reveal.util.Constants.Intervention.TASK_RESET_INTERVENTIONS; -import static org.smartregister.reveal.util.Constants.RequestCode.REQUEST_CODE_FILTER_TASKS; - -/** - * Created by samuelgithengi on 3/11/19. - */ -public class TaskRegisterFragment extends BaseRegisterFragment implements TaskRegisterFragmentContract.View, BaseDrawerContract.DrawerActivity { - - private TaskRegisterAdapter taskAdapter; - - private BaseDrawerContract.View drawerView; - - private RevealJsonFormUtils jsonFormUtils; - private ProgressDialog progressDialog; - private TextView interventionTypeTv; - - private LocationUtils locationUtils; - - private boolean hasRequestedLocation; - - private RefreshRegisterReceiver refreshRegisterReceiver = new RefreshRegisterReceiver(); - - private CardView indicatorsCardView; - - private TextView filterTextView; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - drawerView = new DrawerMenuView(this); - progressDialog = new ProgressDialog(getContext()); - progressDialog.setCancelable(false); - } - - @Override - protected int getLayout() { - return R.layout.fragment_task_register; - } - - public void initializeAdapter(Set visibleColumns) { - taskAdapter = new TaskRegisterAdapter(getActivity(), registerActionHandler); - clientsView.setAdapter(taskAdapter); - } - - @Override - public void setupViews(View view) { - super.setupViews(view); - interventionTypeTv = view.findViewById(R.id.intervention_type); - if (getActivity() != null) { - interventionTypeTv.setText( - getActivity().getIntent().getStringExtra(TaskRegister.INTERVENTION_TYPE)); - } - view.findViewById(R.id.txt_map_label).setOnClickListener(v -> getPresenter().onOpenMapClicked()); - drawerView.initializeDrawerLayout(); - view.findViewById(R.id.drawerMenu).setOnClickListener(v -> drawerView.openDrawerLayout()); - drawerView.onResume(); - - initializeProgressIndicatorViews(view); - - filterTextView = view.findViewById(R.id.filter_text_view); - filterTextView.setOnClickListener(v -> { - getPresenter().onFilterTasksClicked(); - }); - - TaskFilterParams filterParams = (TaskFilterParams) getActivity().getIntent().getSerializableExtra(FILTER_SORT_PARAMS); - if (filterParams != null) { - getPresenter().setTaskFilterParams(filterParams); - } - } - - @Override - public void filter(String filterString, String joinTableString, String mainConditionString, boolean qrCode) { - getSearchCancelView().setVisibility(isEmpty(filterString) ? View.INVISIBLE : View.VISIBLE); - if (isEmpty(filterString)) { - org.smartregister.util.Utils.hideKeyboard(getActivity()); - } - getPresenter().searchTasks(filterString); - } - - @Override - public void startMapActivity(TaskFilterParams taskFilterParams) { - Intent intent = new Intent(getContext(), ListTasksActivity.class); - if (taskFilterParams != null) { - taskFilterParams.setSearchPhrase(getSearchView().getText().toString()); - intent.putExtra(FILTER_SORT_PARAMS, taskFilterParams); - } else if (StringUtils.isNotBlank(getSearchView().getText())) { - intent.putExtra(FILTER_SORT_PARAMS, new TaskFilterParams(getSearchView().getText().toString())); - } - getActivity().setResult(RESULT_OK, intent); - getActivity().finish(); - } - - @Override - public Location getLastLocation() { - if (getActivity() != null && getActivity().getIntent().getExtras() != null) { - return getActivity().getIntent().getExtras().getParcelable(TaskRegister.LAST_USER_LOCATION); - } else { - return null; - } - } - - @Override - protected void initializePresenter() { - presenter = new TaskRegisterFragmentPresenter(this, TaskRegister.VIEW_IDENTIFIER); - locationUtils = new LocationUtils(getContext()); - locationUtils.requestLocationUpdates(getPresenter()); - } - - @Override - public void setUniqueID(String qrCode) { - if (this.getSearchView() != null) { - this.getSearchView().setText(qrCode); - } - } - - @Override - public void setAdvancedSearchFormData(HashMap hashMap) {//not used - } - - @Override - protected String getMainCondition() { - return null;//not used - } - - @Override - protected String getDefaultSortQuery() { - return null;//not used - } - - @Override - protected void startRegistration() {////not used on reveal/ adding points done on map - } - - @Override - protected void onViewClicked(View view) { - TaskDetails details = (TaskDetails) view.getTag(R.id.task_details); - - if (TASK_RESET_INTERVENTIONS.contains(details.getTaskCode()) - && Task.TaskStatus.COMPLETED.name().equals(details.getTaskStatus())) { - displayTaskActionDialog(details, view); - } else { - getPresenter().onTaskSelected(details, view.getId() == R.id.task_action); - } - - } - - public void displayTaskActionDialog(TaskDetails details, View view) { - AlertDialogUtils.displayNotificationWithCallback(getContext(), R.string.select_task_action, - R.string.choose_action, R.string.view_details, R.string.undo, new Dialog.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (which){ - case BUTTON_POSITIVE: - getPresenter().onTaskSelected(details, view.getId() == R.id.task_action); - break; - case DialogInterface.BUTTON_NEGATIVE: - displayResetTaskInfoDialog(details); - break; - default: - break; - } - dialog.dismiss(); - } - - } ); - } - - public void displayResetTaskInfoDialog(TaskDetails details) { - AlertDialogUtils.displayNotificationWithCallback(getContext(), R.string.undo_task_title, - R.string.undo_task_msg, R.string.confirm, R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (which == BUTTON_POSITIVE) - getPresenter().resetTaskInfo(details); - dialog.dismiss(); - } - }); - } - - @Override - public void showNotFoundPopup(String opensrpId) { - if (this.getActivity() != null) { - NoMatchDialogFragment.launchDialog((BaseRegisterActivity) this.getActivity(), "dialog", opensrpId); - } - } - - private TaskRegisterFragmentPresenter getPresenter() { - return (TaskRegisterFragmentPresenter) presenter; - } - - @Override - public void setTotalPatients() { - //do nothing using @link setTotalTasks(structuresWithinBuffer) - } - - - @Override - public void setTotalTasks(int structuresWithinBuffer) { - if (isAdded() && headerTextDisplay != null) { - headerTextDisplay.setText(getResources().getQuantityString(R.plurals.structures, - taskAdapter.getItemCount(), structuresWithinBuffer, Utils.getLocationBuffer(), taskAdapter.getItemCount())); - - filterRelativeLayout.setVisibility(View.GONE); - } - } - - public void setTaskDetails(List tasks) { - taskAdapter.setTaskDetails(tasks); - if (BuildConfig.BUILD_COUNTRY == Country.ZAMBIA) { - new IndicatorsCalculatorTask(getActivity(), tasks).execute(); - } - } - - @Override - public void displayNotification(int title, int message, Object... formatArgs) { - setRefreshList(false); - AlertDialogUtils.displayNotification(getContext(), title, message, formatArgs); - } - - @Override - public void startForm(JSONObject formName) { - ((TaskRegisterActivity) getActivity()).startFormActivity(formName); - } - - @Override - public void displayError(int title, int message) { - new AlertDialog.Builder(getActivity()).setTitle(title).setMessage(message).create().show(); - } - - @Override - public void onDestroy() { - getPresenter().onDestroy(); - super.onDestroy(); - } - - @Override - public void onDrawerClosed() { - getPresenter().onDrawerClosed(); - - } - - @Override - public RevealJsonFormUtils getJsonFormUtils() { - return jsonFormUtils; - } - - @Override - public Location getUserCurrentLocation() { - return locationUtils.getLastLocation(); - } - - @Override - public void requestUserLocation() { - hasRequestedLocation = true; - locationUtils.checkLocationSettingsAndStartLocationServices(getActivity(), getPresenter()); - } - - @Override - public void displayToast(String message) { - Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show(); - } - - @Override - public LocationUtils getLocationUtils() { - return locationUtils; - } - - @Override - public void showProgressDialog(@StringRes int title, @StringRes int message) { - if (progressDialog != null) { - progressDialog.setTitle(title); - progressDialog.setMessage(getString(message)); - progressDialog.show(); - } - } - - @Override - public void hideProgressDialog() { - if (progressDialog != null) { - progressDialog.dismiss(); - } - } - - @Override - public void setInventionType(int interventionLabel) { - interventionTypeTv.setText(getString(interventionLabel)); - } - - @Override - public void registerFamily(BaseTaskDetails taskDetails) { - ((TaskRegisterActivity) getActivity()).startFamilyRegistration(taskDetails); - } - - @Override - public void openFamilyProfile(CommonPersonObjectClient family, BaseTaskDetails taskDetails) { - Intent intent = new Intent(getContext(), org.smartregister.family.util.Utils.metadata().profileActivity); - intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_BASE_ENTITY_ID, family.getCaseId()); - intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_HEAD, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.FAMILY_HEAD, false)); - intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.PRIMARY_CAREGIVER, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.PRIMARY_CAREGIVER, false)); - intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.FAMILY_NAME, org.smartregister.family.util.Utils.getValue(family.getColumnmaps(), DBConstants.KEY.FIRST_NAME, false)); - intent.putExtra(org.smartregister.family.util.Constants.INTENT_KEY.GO_TO_DUE_PAGE, false); - - - intent.putExtra(Properties.LOCATION_UUID, taskDetails.getStructureId()); - intent.putExtra(Properties.TASK_IDENTIFIER, taskDetails.getTaskId()); - intent.putExtra(Properties.TASK_BUSINESS_STATUS, taskDetails.getBusinessStatus()); - intent.putExtra(Properties.TASK_STATUS, taskDetails.getTaskStatus()); - - startActivity(intent); - - } - - @Override - public void displayIndexCaseDetails(JSONObject indexCase) { - ((TaskRegisterActivity) getActivity()).displayIndexCaseFragment(indexCase); - } - - @Override - public void setNumberOfFilters(int numberOfFilters) { - filterTextView.setText(getString(R.string.filters, numberOfFilters)); - int padding = getResources().getDimensionPixelSize(R.dimen.filter_toggle_end_margin); - filterTextView.setPadding(padding, 0, padding, 0); - } - - @Override - public void clearFilter() { - filterTextView.setText(getString(R.string.filter)); - int padding = getResources().getDimensionPixelSize(R.dimen.filter_toggle_padding); - filterTextView.setPadding(padding, 0, padding, 0); - } - - @Override - public TaskRegisterAdapter getAdapter() { - return taskAdapter; - } - - @Override - public void openFilterActivity(TaskFilterParams filterParams) { - Intent intent = new Intent(getContext(), FilterTasksActivity.class); - intent.putExtra(FILTER_SORT_PARAMS, filterParams); - getActivity().startActivityForResult(intent, REQUEST_CODE_FILTER_TASKS); - } - - @Override - public void setSearchPhrase(String searchPhrase) { - getSearchView().setText(searchPhrase); - } - - public void setJsonFormUtils(RevealJsonFormUtils jsonFormUtils) { - this.jsonFormUtils = jsonFormUtils; - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent data) { - if (requestCode == Constants.RequestCode.LOCATION_SETTINGS && hasRequestedLocation) { - if (resultCode == RESULT_OK) { - locationUtils.requestLocationUpdates(getPresenter()); - getPresenter().getLocationPresenter().waitForUserLocation(); - } else if (resultCode == RESULT_CANCELED) { - getPresenter().getLocationPresenter().onGetUserLocationFailed(); - } - hasRequestedLocation = false; - } else if (requestCode == REQUEST_CODE_FILTER_TASKS && resultCode == RESULT_OK && data.hasExtra(FILTER_SORT_PARAMS)) { - TaskFilterParams filterParams = (TaskFilterParams) data.getSerializableExtra(FILTER_SORT_PARAMS); - getPresenter().filterTasks(filterParams); - } - } - - @Override - public void onPause() { - if (getContext() != null) - LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(refreshRegisterReceiver); - setViewVisibility(indicatorsCardView, false); - super.onPause(); - } - - @Override - public void onResume() { - super.onResume(); - if (getContext() != null) { - IntentFilter filter = new IntentFilter(Action.STRUCTURE_TASK_SYNCED); - LocalBroadcastManager.getInstance(getContext()).registerReceiver(refreshRegisterReceiver, filter); - } - } - - private class RefreshRegisterReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - getPresenter().initializeQueries(getMainCondition()); - } - } - - private void initializeProgressIndicatorViews(View view) { - - LinearLayout progressIndicatorsGroupView = view.findViewById(R.id.progressIndicatorsGroupView); - progressIndicatorsGroupView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - openIndicatorsCardView(); - } - }); - - indicatorsCardView = view.findViewById(R.id.indicators_card_view); - indicatorsCardView.findViewById(R.id.btn_collapse_indicators_card_view).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - setViewVisibility(indicatorsCardView, false); - } - }); - } - - private void openIndicatorsCardView() { - - setViewVisibility(indicatorsCardView, true); - } - - - private void setViewVisibility(View view, boolean isVisible) { - view.setVisibility(isVisible ? View.VISIBLE : View.GONE); - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/AvailableOfflineMapsInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/AvailableOfflineMapsInteractor.java deleted file mode 100644 index dd82332f02..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/AvailableOfflineMapsInteractor.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.smartregister.reveal.interactor; - -import org.smartregister.domain.Location; -import org.smartregister.repository.LocationRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.AvailableOfflineMapsContract; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.util.AppExecutors; - -import java.util.ArrayList; -import java.util.List; - -public class AvailableOfflineMapsInteractor implements AvailableOfflineMapsContract.Interactor { - - private AppExecutors appExecutors; - - private LocationRepository locationRepository; - - private AvailableOfflineMapsContract.Presenter presenter; - - public AvailableOfflineMapsInteractor(AvailableOfflineMapsContract.Presenter presenter) { - this.presenter = presenter; - appExecutors = RevealApplication.getInstance().getAppExecutors(); - locationRepository = RevealApplication.getInstance().getLocationRepository(); - } - - - @Override - public void fetchAvailableOAsForMapDownLoad(final List locationIds) { - - Runnable runnable = new Runnable() { - public void run() { - List operationalAreas = locationRepository.getLocationsByIds(locationIds, false); - - appExecutors.mainThread().execute(() -> { - presenter.onFetchAvailableOAsForMapDownLoad(populateOfflineMapModelList(operationalAreas)); - }); - } - }; - - appExecutors.diskIO().execute(runnable); - - } - - public List populateOfflineMapModelList(List locations) { - List offlineMapModels = new ArrayList<>(); - for (Location location: locations) { - OfflineMapModel offlineMapModel = new OfflineMapModel(); - offlineMapModel.setLocation(location); - offlineMapModels.add(offlineMapModel); - } - - return offlineMapModels; - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseDrawerInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseDrawerInteractor.java index b13e190ce7..c1508ee43f 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseDrawerInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseDrawerInteractor.java @@ -7,9 +7,9 @@ import org.smartregister.domain.PlanDefinition; import org.smartregister.repository.PlanDefinitionSearchRepository; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseDrawerContract; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.util.AppExecutors; import java.util.Set; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseFormFragmentInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseFormFragmentInteractor.java deleted file mode 100644 index ab11546592..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseFormFragmentInteractor.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.smartregister.reveal.interactor; - -import androidx.core.util.Pair; - -import net.sqlcipher.Cursor; -import net.sqlcipher.database.SQLiteDatabase; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObject; -import org.smartregister.commonregistry.CommonRepository; -import org.smartregister.repository.EventClientRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseFormFragmentContract; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.InteractorUtils; - -import timber.log.Timber; - -import static com.vijay.jsonwizard.constants.JsonFormConstants.KEY; -import static com.vijay.jsonwizard.constants.JsonFormConstants.TEXT; -import static org.smartregister.family.util.Utils.metadata; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.BASE_ENTITY_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.FIRST_NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.LAST_NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_ID; -import static org.smartregister.reveal.util.Constants.Intervention.IRS; - -/** - * Created by samuelgithengi on 6/14/19. - */ -public class BaseFormFragmentInteractor implements BaseFormFragmentContract.Interactor { - - private BaseFormFragmentContract.Presenter presenter; - - private CommonRepository commonRepository; - - private AppExecutors appExecutors; - - private SQLiteDatabase sqLiteDatabase; - - protected EventClientRepository eventClientRepository; - - private InteractorUtils interactorUtils; - - public BaseFormFragmentInteractor(BaseFormFragmentContract.Presenter presenter) { - this.presenter = presenter; - this.commonRepository = RevealApplication.getInstance().getContext().commonrepository(metadata().familyMemberRegister.tableName); - appExecutors = RevealApplication.getInstance().getAppExecutors(); - sqLiteDatabase = RevealApplication.getInstance().getRepository().getReadableDatabase(); - eventClientRepository = RevealApplication.getInstance().getContext().getEventClientRepository(); - interactorUtils = new InteractorUtils(); - } - - @Override - public void findNumberOfMembers(String structureId, JSONObject formJSON) { - appExecutors.diskIO().execute(() -> { - Cursor cursor = null; - int numberOfMembers = 0; - int numberOfMembersSleepingOutdoors = 0; - try { - cursor = sqLiteDatabase.rawQuery( - String.format("SELECT count(*),SUM(CASE WHEN sleeps_outdoors='Yes' THEN 1 ELSE 0 END) FROM %s WHERE %s = ?", - metadata().familyMemberRegister.tableName, STRUCTURE_ID), new String[]{structureId}); - - while (cursor.moveToNext()) { - numberOfMembers = cursor.getInt(0); - numberOfMembersSleepingOutdoors = cursor.getInt(1); - } - } catch (Exception e) { - Timber.e(e, "Error find Number of members "); - } finally { - if (cursor != null) - cursor.close(); - } - int finalNumberOfMembers = numberOfMembers; - int finalNumberOfMembersSleepingOutdoors = numberOfMembersSleepingOutdoors; - appExecutors.mainThread().execute(() -> { - presenter.onFetchedMembersCount(new Pair<>(finalNumberOfMembers, finalNumberOfMembersSleepingOutdoors), formJSON); - }); - }); - - } - - @Override - public void findMemberDetails(String structureId, JSONObject formJSON) { - appExecutors.diskIO().execute(() -> { - JSONArray familyMembers = new JSONArray(); - Cursor cursor = null; - try { - cursor = sqLiteDatabase.rawQuery( - String.format("SELECT %s, %s, %s FROM %s WHERE %s = ?", BASE_ENTITY_ID, FIRST_NAME, LAST_NAME, - metadata().familyMemberRegister.tableName, STRUCTURE_ID), new String[]{structureId}); - while (cursor.moveToNext()) { - JSONObject member = new JSONObject(); - member.put(KEY, cursor.getString(cursor.getColumnIndex(BASE_ENTITY_ID))); - member.put(TEXT, String.format("%s %s", cursor.getString(cursor.getColumnIndex(FIRST_NAME)) - , cursor.getString(cursor.getColumnIndex(LAST_NAME)))); - familyMembers.put(member); - } - } catch (Exception e) { - Timber.e(e, "Error find Member Details "); - } finally { - if (cursor != null) - cursor.close(); - } - appExecutors.mainThread().execute(() -> { - presenter.onFetchedFamilyMembers(familyMembers, formJSON); - }); - }); - } - - @Override - public void findSprayDetails(String interventionType, String structureId, JSONObject formJSON) { - if (IRS.equals(interventionType)) { - - appExecutors.diskIO().execute(() -> { - CommonPersonObject commonPersonObject = interactorUtils.fetchSprayDetails(interventionType, structureId, - eventClientRepository, commonRepository); - - appExecutors.mainThread().execute(() -> { - presenter.onFetchedSprayDetails(commonPersonObject, formJSON); - }); - }); - } - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseInteractor.java deleted file mode 100644 index 4ddaf71d35..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/BaseInteractor.java +++ /dev/null @@ -1,476 +0,0 @@ -package org.smartregister.reveal.interactor; - -import android.content.Context; -import androidx.annotation.VisibleForTesting; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; -import com.mapbox.geojson.Feature; - -import net.sqlcipher.Cursor; -import net.sqlcipher.database.SQLiteDatabase; - -import org.joda.time.DateTime; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.smartregister.clientandeventmodel.Event; -import org.smartregister.commonregistry.CommonPersonObject; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.commonregistry.CommonRepository; -import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; -import org.smartregister.domain.Location; -import org.smartregister.domain.LocationProperty; -import org.smartregister.domain.Task; -import org.smartregister.domain.Client; -import org.smartregister.domain.db.EventClient; -import org.smartregister.domain.Obs; -import org.smartregister.family.util.Constants.INTENT_KEY; -import org.smartregister.repository.AllSharedPreferences; -import org.smartregister.repository.BaseRepository; -import org.smartregister.repository.EventClientRepository; -import org.smartregister.repository.StructureRepository; -import org.smartregister.repository.TaskRepository; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseContract; -import org.smartregister.reveal.contract.BaseContract.BasePresenter; -import org.smartregister.reveal.contract.StructureTasksContract; -import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.Constants.BusinessStatus; -import org.smartregister.reveal.util.Constants.EventType; -import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.util.Constants.JsonForm; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.Constants.StructureType; -import org.smartregister.reveal.util.FamilyConstants.TABLE_NAME; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.TaskUtils; -import org.smartregister.reveal.util.Utils; -import org.smartregister.reveal.widget.GeoWidgetFactory; -import org.smartregister.util.DateTimeTypeConverter; -import org.smartregister.util.JsonFormUtils; -import org.smartregister.util.PropertiesConverter; - -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import timber.log.Timber; - -import static com.cocoahero.android.geojson.Geometry.JSON_COORDINATES; -import static org.smartregister.family.util.DBConstants.KEY.BASE_ENTITY_ID; -import static org.smartregister.family.util.DBConstants.KEY.DATE_REMOVED; -import static org.smartregister.family.util.Utils.metadata; -import static org.smartregister.reveal.util.Constants.BEDNET_DISTRIBUTION_EVENT; -import static org.smartregister.reveal.util.Constants.BEHAVIOUR_CHANGE_COMMUNICATION; -import static org.smartregister.reveal.util.Constants.BLOOD_SCREENING_EVENT; -import static org.smartregister.reveal.util.Constants.DETAILS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.FOR; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURES_TABLE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.TASK_TABLE; -import static org.smartregister.reveal.util.Constants.EventType.CASE_CONFIRMATION_EVENT; -import static org.smartregister.reveal.util.Constants.Intervention.BCC; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.IRS; -import static org.smartregister.reveal.util.Constants.Intervention.LARVAL_DIPPING; -import static org.smartregister.reveal.util.Constants.Intervention.MOSQUITO_COLLECTION; -import static org.smartregister.reveal.util.Constants.Intervention.PAOT; -import static org.smartregister.reveal.util.Constants.JsonForm.ENCOUNTER_TYPE; -import static org.smartregister.reveal.util.Constants.JsonForm.LOCATION_COMPONENT_ACTIVE; -import static org.smartregister.reveal.util.Constants.JsonForm.PHYSICAL_TYPE; -import static org.smartregister.reveal.util.Constants.JsonForm.STRUCTURE_NAME; -import static org.smartregister.reveal.util.Constants.JsonForm.STRUCTURE_TYPE; -import static org.smartregister.reveal.util.Constants.LARVAL_DIPPING_EVENT; -import static org.smartregister.reveal.util.Constants.METADATA; -import static org.smartregister.reveal.util.Constants.MOSQUITO_COLLECTION_EVENT; -import static org.smartregister.reveal.util.Constants.REGISTER_STRUCTURE_EVENT; -import static org.smartregister.reveal.util.Constants.SPRAY_EVENT; -import static org.smartregister.reveal.util.Constants.STRUCTURE; -import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY_MEMBER; -import static org.smartregister.util.JsonFormUtils.ENTITY_ID; -import static org.smartregister.util.JsonFormUtils.getJSONObject; -import static org.smartregister.util.JsonFormUtils.getString; - - -/** - * Created by samuelgithengi on 3/25/19. - */ -public class BaseInteractor implements BaseContract.BaseInteractor { - - public static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()) - .registerTypeAdapter(LocationProperty.class, new PropertiesConverter()).create(); - - private RevealApplication revealApplication; - - protected TaskRepository taskRepository; - - protected StructureRepository structureRepository; - - protected BasePresenter presenterCallBack; - - protected String operationalAreaId; - - protected AppExecutors appExecutors; - - protected AllSharedPreferences sharedPreferences; - - protected EventClientRepository eventClientRepository; - - protected RevealClientProcessor clientProcessor; - - private TaskUtils taskUtils; - - private SQLiteDatabase database; - - private CommonRepository commonRepository; - - private PreferencesUtil prefsUtil; - - public BaseInteractor(BasePresenter presenterCallBack) { - revealApplication = RevealApplication.getInstance(); - this.presenterCallBack = presenterCallBack; - appExecutors = revealApplication.getAppExecutors(); - taskRepository = revealApplication.getTaskRepository(); - structureRepository = revealApplication.getStructureRepository(); - eventClientRepository = revealApplication.getContext().getEventClientRepository(); - clientProcessor = RevealClientProcessor.getInstance(revealApplication.getApplicationContext()); - sharedPreferences = revealApplication.getContext().allSharedPreferences(); - taskUtils = TaskUtils.getInstance(); - database = revealApplication.getRepository().getReadableDatabase(); - prefsUtil = PreferencesUtil.getInstance(); - } - - @VisibleForTesting - public BaseInteractor(BasePresenter presenterCallBack, CommonRepository commonRepository) { - this(presenterCallBack); - this.commonRepository = commonRepository; - } - - @Override - public void saveJsonForm(String json) { - try { - JSONObject jsonForm = new JSONObject(json); - String encounterType = jsonForm.getString(ENCOUNTER_TYPE); - boolean refreshMapOnEventSaved = true; - switch (encounterType) { - case REGISTER_STRUCTURE_EVENT: - saveRegisterStructureForm(jsonForm); - break; - case EventType.MDA_DISPENSE: - taskUtils.generateMDAAdherenceTask(RevealApplication.getInstance().getApplicationContext(), - getString(jsonForm, ENTITY_ID), getJSONObject(jsonForm, DETAILS).getString(Properties.LOCATION_ID)); - - case BLOOD_SCREENING_EVENT: - case EventType.MDA_ADHERENCE: - saveMemberForm(jsonForm, encounterType, BLOOD_SCREENING); - break; - - case CASE_CONFIRMATION_EVENT: - saveCaseConfirmation(jsonForm, encounterType); - break; - default: - saveLocationInterventionForm(jsonForm); - if (!encounterType.equals(BEDNET_DISTRIBUTION_EVENT) && !encounterType.equals(EventType.IRS_VERIFICATION)) { - refreshMapOnEventSaved = false; - } - break; - } - revealApplication.setRefreshMapOnEventSaved(refreshMapOnEventSaved); - } catch (Exception e) { - Timber.e(e, "Error saving Json Form data"); - } - } - - private org.smartregister.domain.Event saveEvent(JSONObject jsonForm, String encounterType, String bindType) throws JSONException { - String entityId = getString(jsonForm, ENTITY_ID); - JSONArray fields = JsonFormUtils.fields(jsonForm); - JSONObject metadata = getJSONObject(jsonForm, METADATA); - Event event = JsonFormUtils.createEvent(fields, metadata, Utils.getFormTag(), entityId, encounterType, bindType); - JSONObject eventJson = new JSONObject(gson.toJson(event)); - eventJson.put(DETAILS, getJSONObject(jsonForm, DETAILS)); - eventClientRepository.addEvent(entityId, eventJson); - return gson.fromJson(eventJson.toString(), org.smartregister.domain.Event.class); - } - - private void saveLocationInterventionForm(JSONObject jsonForm) { - String encounterType = null; - String interventionType = null; - try { - encounterType = jsonForm.getString(ENCOUNTER_TYPE); - if (encounterType.equals(SPRAY_EVENT)) { - interventionType = IRS; - } else if (encounterType.equals(MOSQUITO_COLLECTION_EVENT)) { - interventionType = MOSQUITO_COLLECTION; - } else if (encounterType.equals(LARVAL_DIPPING_EVENT)) { - interventionType = LARVAL_DIPPING; - } else if (encounterType.equals(BEDNET_DISTRIBUTION_EVENT)) { - interventionType = BEDNET_DISTRIBUTION; - } else if (encounterType.equals(BEHAVIOUR_CHANGE_COMMUNICATION)) { - interventionType = BCC; - } else if (encounterType.equals(EventType.PAOT_EVENT)) { - interventionType = PAOT; - } else if (encounterType.equals(EventType.MDA_DISPENSE)) { - interventionType = Intervention.MDA_DISPENSE; - } else if (encounterType.equals(EventType.MDA_ADHERENCE)) { - interventionType = Intervention.MDA_ADHERENCE; - } else if (encounterType.equals(EventType.IRS_VERIFICATION)) { - interventionType = Intervention.IRS_VERIFICATION; - } - } catch (JSONException e) { - Timber.e(e); - } - - final String finalInterventionType = interventionType; - final String finalEncounterType = encounterType; - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - org.smartregister.domain.Event event = saveEvent(jsonForm, finalEncounterType, STRUCTURE); - clientProcessor.processClient(Collections.singletonList(new EventClient(event, null)), true); - appExecutors.mainThread().execute(new Runnable() { - @Override - public void run() { - String businessStatus = clientProcessor.calculateBusinessStatus(event); - String taskID = event.getDetails().get(Properties.TASK_IDENTIFIER); - presenterCallBack.onFormSaved(event.getBaseEntityId(), taskID, Task.TaskStatus.COMPLETED, businessStatus, finalInterventionType); - } - }); - } catch (JSONException e) { - Timber.e(e, "Error saving saving Form "); - presenterCallBack.onFormSaveFailure(finalEncounterType); - } - } - }; - - appExecutors.diskIO().execute(runnable); - } - - private void saveRegisterStructureForm(JSONObject jsonForm) { - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - jsonForm.put(ENTITY_ID, UUID.randomUUID().toString()); - JSONObject eventDetails = new JSONObject(); - eventDetails.put(Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); - eventDetails.put(Properties.LOCATION_PARENT, operationalAreaId); - String planIdentifier = PreferencesUtil.getInstance().getCurrentPlanId(); - eventDetails.put(Properties.PLAN_IDENTIFIER, planIdentifier); - jsonForm.put(DETAILS, eventDetails); - org.smartregister.domain.Event event = saveEvent(jsonForm, REGISTER_STRUCTURE_EVENT, STRUCTURE); - com.cocoahero.android.geojson.Feature feature = new com.cocoahero.android.geojson.Feature(new JSONObject(event.findObs(null, false, "structure").getValue().toString())); - Date now = new Date(); - Location structure = new Location(); - structure.setId(event.getBaseEntityId()); - structure.setType(feature.getType()); - org.smartregister.domain.Geometry geometry = new org.smartregister.domain.Geometry(); - geometry.setType(org.smartregister.domain.Geometry.GeometryType.valueOf(feature.getGeometry().getType().toUpperCase())); - JsonArray coordinates = new JsonArray(); - JSONArray featureCoordinates = feature.getGeometry().toJSON().getJSONArray(JSON_COORDINATES); - coordinates.add(Double.parseDouble(featureCoordinates.get(0).toString())); - coordinates.add(Double.parseDouble(featureCoordinates.get(1).toString())); - geometry.setCoordinates(coordinates); - structure.setGeometry(geometry); - LocationProperty properties = new LocationProperty(); - String structureType = event.findObs(null, false, STRUCTURE_TYPE).getValue().toString(); - properties.setType(structureType); - properties.setEffectiveStartDate(now); - properties.setParentId(operationalAreaId); - properties.setStatus(LocationProperty.PropertyStatus.PENDING_REVIEW); - properties.setUid(UUID.randomUUID().toString()); - Obs structureNameObs = event.findObs(null, false, STRUCTURE_NAME); - if (structureNameObs != null && structureNameObs.getValue() != null) { - properties.setName(structureNameObs.getValue().toString()); - } - Obs physicalTypeObs = event.findObs(null, false, PHYSICAL_TYPE); - if (physicalTypeObs != null && physicalTypeObs.getValue() != null) { - Map customProperties = new HashMap<>(); - customProperties.put(PHYSICAL_TYPE, physicalTypeObs.getValue().toString()); - properties.setCustomProperties(customProperties); - } - structure.setProperties(properties); - structure.setSyncStatus(BaseRepository.TYPE_Created); - structureRepository.addOrUpdate(structure); - revealApplication.setSynced(false); - Context applicationContext = revealApplication.getApplicationContext(); - Task task = null; - if (StructureType.RESIDENTIAL.equals(structureType) && Utils.isFocusInvestigationOrMDA()) { - task = taskUtils.generateRegisterFamilyTask(applicationContext, structure.getId()); - } else { - if (StructureType.RESIDENTIAL.equals(structureType)) { - task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), - BusinessStatus.NOT_VISITED, Intervention.IRS, R.string.irs_task_description); - } else if (StructureType.MOSQUITO_COLLECTION_POINT.equals(structureType)) { - task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), - BusinessStatus.NOT_VISITED, Intervention.MOSQUITO_COLLECTION, R.string.mosquito_collection_task_description); - } else if (StructureType.LARVAL_BREEDING_SITE.equals(structureType)) { - task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), - BusinessStatus.NOT_VISITED, Intervention.LARVAL_DIPPING, R.string.larval_dipping_task_description); - } else if (StructureType.POTENTIAL_AREA_OF_TRANSMISSION.equals(structureType)) { - task = taskUtils.generateTask(applicationContext, structure.getId(), structure.getId(), - BusinessStatus.NOT_VISITED, PAOT, R.string.poat_task_description); - } - } - clientProcessor.processClient(Collections.singletonList(new EventClient(event, null)), true); - Task finalTask = task; - appExecutors.mainThread().execute(new Runnable() { - @Override - public void run() { - Map taskProperties = new HashMap<>(); - if (finalTask != null) { - - taskProperties.put(Properties.TASK_IDENTIFIER, finalTask.getIdentifier()); - taskProperties.put(Properties.TASK_BUSINESS_STATUS, finalTask.getBusinessStatus()); - taskProperties.put(Properties.TASK_STATUS, finalTask.getStatus().name()); - taskProperties.put(Properties.TASK_CODE, finalTask.getCode()); - } - taskProperties.put(Properties.LOCATION_UUID, structure.getProperties().getUid()); - taskProperties.put(Properties.LOCATION_VERSION, structure.getProperties().getVersion() + ""); - taskProperties.put(Properties.LOCATION_TYPE, structure.getProperties().getType()); - structure.getProperties().setCustomProperties(taskProperties); - - - Obs myLocationActiveObs = event.findObs(null, false, LOCATION_COMPONENT_ACTIVE); - - boolean myLocationActive = myLocationActiveObs != null && Boolean.valueOf(myLocationActiveObs.getValue().toString()); - revealApplication.setMyLocationComponentEnabled(myLocationActive); - - - Obs zoomObs = event.findObs(null, false, GeoWidgetFactory.ZOOM_LEVEL); - double zoomLevel = Double.parseDouble(zoomObs.getValue().toString()); - - presenterCallBack.onStructureAdded(Feature.fromJson(gson.toJson(structure)), featureCoordinates, zoomLevel); - } - }); - } catch (JSONException e) { - Timber.e(e, "Error saving new Structure"); - presenterCallBack.onFormSaveFailure(REGISTER_STRUCTURE_EVENT); - } - } - }; - - appExecutors.diskIO().execute(runnable); - } - - private void saveMemberForm(JSONObject jsonForm, String eventType, String intervention) { - Runnable runnable = new Runnable() { - @Override - public void run() { - try { - org.smartregister.domain.Event event = saveEvent(jsonForm, eventType, FAMILY_MEMBER); - Client client = eventClientRepository.fetchClientByBaseEntityId(event.getBaseEntityId()); - clientProcessor.processClient(Collections.singletonList(new EventClient(event, client)), true); - appExecutors.mainThread().execute(new Runnable() { - @Override - public void run() { - String businessStatus = clientProcessor.calculateBusinessStatus(event); - String taskID = event.getDetails().get(Properties.TASK_IDENTIFIER); - presenterCallBack.onFormSaved(event.getBaseEntityId(), taskID, Task.TaskStatus.COMPLETED, businessStatus, intervention); - } - }); - } catch (Exception e) { - Timber.e("Error saving member event form"); - } - } - }; - appExecutors.diskIO().execute(runnable); - } - - private void saveCaseConfirmation(JSONObject jsonForm, String eventType) { - appExecutors.diskIO().execute(() -> { - try { - String baseEntityId = JsonFormUtils.getFieldValue(JsonFormUtils.fields(jsonForm), JsonForm.FAMILY_MEMBER); - jsonForm.put(ENTITY_ID, baseEntityId); - org.smartregister.domain.Event event = saveEvent(jsonForm, eventType, CASE_CONFIRMATION); - Client client = eventClientRepository.fetchClientByBaseEntityId(event.getBaseEntityId()); - String taskID = event.getDetails().get(Properties.TASK_IDENTIFIER); - String businessStatus = clientProcessor.calculateBusinessStatus(event); - Task task = taskRepository.getTaskByIdentifier(taskID); - task.setForEntity(baseEntityId); - task.setBusinessStatus(businessStatus); - task.setStatus(Task.TaskStatus.COMPLETED); - task.setSyncStatus(BaseRepository.TYPE_Created); - taskRepository.addOrUpdate(task); - Set removedTasks = new HashSet<>(); - for (Task bloodScreeningTask : taskRepository.getTasksByEntityAndCode(prefsUtil.getCurrentPlanId(), - Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId(), baseEntityId, BLOOD_SCREENING)) { - bloodScreeningTask.setStatus(Task.TaskStatus.CANCELLED); - bloodScreeningTask.setSyncStatus(BaseRepository.TYPE_Created); - taskRepository.addOrUpdate(bloodScreeningTask); - removedTasks.add(bloodScreeningTask); - } - revealApplication.setSynced(false); - clientProcessor.processClient(Collections.singletonList(new EventClient(event, client)), true); - appExecutors.mainThread().execute(() -> { - ((StructureTasksContract.Presenter) presenterCallBack).onIndexConfirmationFormSaved(taskID, Task.TaskStatus.COMPLETED, businessStatus, removedTasks); - }); - } catch (Exception e) { - Timber.e("Error saving case confirmation data"); - } - }); - } - - protected String getMemberTasksSelect(String mainCondition, String[] memberColumns) { - SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); - queryBuilder.selectInitiateMainTable(STRUCTURES_TABLE, memberColumns, ID); - queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", - FAMILY_MEMBER, FAMILY_MEMBER, STRUCTURE_ID, STRUCTURES_TABLE, ID)); - queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", - TASK_TABLE, TASK_TABLE, FOR, FAMILY_MEMBER, BASE_ENTITY_ID)); - return queryBuilder.mainCondition(mainCondition); - } - - public void fetchFamilyDetails(String structureId) { - appExecutors.diskIO().execute(() -> { - Cursor cursor = null; - CommonPersonObjectClient family = null; - try { - cursor = database.rawQuery(String.format("SELECT %s FROM %S WHERE %s = ? AND %s IS NULL", - INTENT_KEY.BASE_ENTITY_ID, TABLE_NAME.FAMILY, STRUCTURE_ID, DATE_REMOVED), new String[]{structureId}); - if (cursor.moveToNext()) { - String baseEntityId = cursor.getString(0); - setCommonRepository(); - final CommonPersonObject personObject = commonRepository.findByBaseEntityId(baseEntityId); - family = new CommonPersonObjectClient(personObject.getCaseId(), - personObject.getDetails(), ""); - family.setColumnmaps(personObject.getColumnmaps()); - } - } catch (Exception e) { - Timber.e(e); - } finally { - if (cursor != null) - cursor.close(); - } - - CommonPersonObjectClient finalFamily = family; - appExecutors.mainThread().execute(() -> { - presenterCallBack.onFamilyFound(finalFamily); - }); - }); - } - - public SQLiteDatabase getDatabase() { - return database; - } - - public void setCommonRepository() { - if (commonRepository == null) { - commonRepository = revealApplication.getContext().commonrepository(metadata().familyRegister.tableName); - - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/DownloadedOfflineMapsInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/DownloadedOfflineMapsInteractor.java deleted file mode 100644 index ab1e03f996..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/DownloadedOfflineMapsInteractor.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.smartregister.reveal.interactor; - -import android.content.Context; -import androidx.core.util.Pair; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.domain.Location; -import org.smartregister.repository.LocationRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.DownloadedOfflineMapsContract; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.OfflineMapHelper; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.ona.kujaku.data.realm.RealmDatabase; -import io.ona.kujaku.data.realm.objects.MapBoxOfflineQueueTask; - -public class DownloadedOfflineMapsInteractor implements DownloadedOfflineMapsContract.Interactor { - - private AppExecutors appExecutors; - - private LocationRepository locationRepository; - - private DownloadedOfflineMapsContract.Presenter presenter; - - private RealmDatabase realmDatabase; - - private Map offlineQueueTaskMap; - - public DownloadedOfflineMapsInteractor(DownloadedOfflineMapsContract.Presenter presenter, Context context) { - this.presenter = presenter; - appExecutors = RevealApplication.getInstance().getAppExecutors(); - locationRepository = RevealApplication.getInstance().getLocationRepository(); - realmDatabase = RevealApplication.getInstance().getRealmDatabase(context); - offlineQueueTaskMap = new HashMap<>(); - } - - @Override - public void fetchLocationsWithOfflineMapDownloads(final Pair, Map> offlineRegionInfo) { - - Runnable runnable = new Runnable() { - public void run() { - if (offlineRegionInfo == null || offlineRegionInfo.first == null) { - presenter.onOAsWithOfflineDownloadsFetched(null); - return; - } - - List operationalAreas = locationRepository.getLocationsByIds(offlineRegionInfo.first); - - setOfflineQueueTaskMap(OfflineMapHelper.populateOfflineQueueTaskMap(realmDatabase)); - - List offlineMapModels = populateOfflineMapModelList(operationalAreas, offlineRegionInfo.second); - - appExecutors.mainThread().execute(new Runnable() { - @Override - public void run() { - presenter.onOAsWithOfflineDownloadsFetched(offlineMapModels); - } - }); - } - }; - - appExecutors.diskIO().execute(runnable); - - } - - public List populateOfflineMapModelList(List locations, Map offlineRegionMap) { - - List offlineMapModels = new ArrayList<>(); - for (Location location: locations) { - OfflineMapModel offlineMapModel = new OfflineMapModel(); - offlineMapModel.setLocation(location); - offlineMapModel.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.DOWNLOADED); - offlineMapModel.setOfflineRegion(offlineRegionMap.get(location.getId())); - - if (offlineQueueTaskMap.get(location.getId()) != null) { - offlineMapModel.setDateCreated(offlineQueueTaskMap.get(location.getId()).getDateCreated()); - } - - offlineMapModels.add(offlineMapModel); - } - - return offlineMapModels; - } - - public void setOfflineQueueTaskMap(Map offlineQueueTaskMap) { - this.offlineQueueTaskMap = offlineQueueTaskMap; - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/ListTaskInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/ListTaskInteractor.java index ff36a02e0a..c186989bb4 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/ListTaskInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/ListTaskInteractor.java @@ -21,24 +21,25 @@ import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.contract.ListTaskContract; -import org.smartregister.reveal.model.CardDetails; import org.smartregister.reveal.model.FamilyCardDetails; import org.smartregister.reveal.model.IRSVerificationCardDetails; import org.smartregister.reveal.model.MosquitoHarvestCardDetails; import org.smartregister.reveal.model.SprayCardDetails; import org.smartregister.reveal.model.StructureDetails; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.model.TaskDetails; import org.smartregister.reveal.presenter.ListTaskPresenter; -import org.smartregister.reveal.util.CardDetailsUtil; import org.smartregister.reveal.util.Constants; import org.smartregister.reveal.util.Constants.GeoJSON; import org.smartregister.reveal.util.FamilyConstants; import org.smartregister.reveal.util.FamilyJsonFormUtils; import org.smartregister.reveal.util.GeoJsonUtils; import org.smartregister.reveal.util.IndicatorUtils; -import org.smartregister.reveal.util.InteractorUtils; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.tasking.interactor.BaseInteractor; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.util.CardDetailsUtil; +import org.smartregister.tasking.util.InteractorUtils; import java.util.HashMap; import java.util.List; @@ -93,8 +94,8 @@ import static org.smartregister.reveal.util.Constants.Tables.PAOT_TABLE; import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY; import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY_MEMBER; -import static org.smartregister.reveal.util.Utils.getInterventionLabel; -import static org.smartregister.reveal.util.Utils.getPropertyValue; +import static org.smartregister.tasking.util.Utils.getInterventionLabel; +import static org.smartregister.tasking.util.Utils.getPropertyValue; /** * Created by samuelgithengi on 11/27/18. @@ -411,6 +412,7 @@ public void markStructureAsIneligible(Feature feature, String reasonUnligible) { details.put(Constants.Properties.TASK_STATUS, task.getStatus().name()); details.put(Constants.Properties.LOCATION_ID, feature.id()); details.put(Constants.Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); + details.put(Constants.Properties.PLAN_IDENTIFIER, task.getPlanIdentifier()); task.setBusinessStatus(NOT_ELIGIBLE); task.setStatus(Task.TaskStatus.COMPLETED); task.setLastModified(new DateTime()); diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/LoginInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/LoginInteractor.java index 499d6dab8e..0187554606 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/LoginInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/LoginInteractor.java @@ -8,7 +8,7 @@ import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.job.LocationTaskServiceJob; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; import org.smartregister.view.contract.BaseLoginContract; import java.lang.ref.WeakReference; @@ -38,8 +38,8 @@ protected void scheduleJobsImmediately() { } @Override - public void loginWithLocalFlag(WeakReference view, boolean localLogin, String userName, String password) { - if(!localLogin){ + public void loginWithLocalFlag(WeakReference view, boolean localLogin, String userName, char[] password) { + if (!localLogin) { RevealApplication.getInstance().getContext().getHttpAgent().setConnectTimeout(CoreLibrary.getInstance().getSyncConfiguration().getConnectTimeout()); RevealApplication.getInstance().getContext().getHttpAgent().setReadTimeout(CoreLibrary.getInstance().getSyncConfiguration().getReadTimeout()); } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/OtherFormsInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/OtherFormsInteractor.java index 34369901ec..1080433272 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/OtherFormsInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/OtherFormsInteractor.java @@ -1,7 +1,8 @@ package org.smartregister.reveal.interactor; -import org.smartregister.reveal.contract.BaseContract; import org.smartregister.reveal.contract.OtherFormsContract; +import org.smartregister.tasking.contract.BaseContract; +import org.smartregister.tasking.interactor.BaseInteractor; public class OtherFormsInteractor extends BaseInteractor implements OtherFormsContract.Interactor { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyOtherMemberInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyOtherMemberInteractor.java index 3ae4670683..278f9d2793 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyOtherMemberInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyOtherMemberInteractor.java @@ -8,8 +8,8 @@ import org.smartregister.reveal.contract.FamilyOtherMemberProfileContract; import org.smartregister.reveal.contract.FamilyOtherMemberProfileContract.Interactor; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.InteractorUtils; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.util.AppExecutors; import static org.smartregister.reveal.application.RevealApplication.getInstance; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractor.java index 19c4911cc1..ba0ddf7b2f 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractor.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.interactor; import android.content.Context; + import androidx.annotation.NonNull; import net.sqlcipher.database.SQLiteDatabase; @@ -23,12 +24,11 @@ import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.contract.FamilyProfileContract; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.FamilyJsonFormUtils; -import org.smartregister.reveal.util.InteractorUtils; import org.smartregister.reveal.util.TaskUtils; -import org.smartregister.reveal.util.Utils; import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.util.AppExecutors; import org.smartregister.util.JsonFormUtils; import java.util.ArrayList; @@ -77,10 +77,7 @@ public ClientProcessorForJava getClientProcessorForJava() { @Override public void generateTasks(Context applicationContext, String baseEntityId, String structureId) { appExecutors.diskIO().execute(() -> { - if (Utils.isFocusInvestigation()) - taskUtils.generateBloodScreeningTask(applicationContext, baseEntityId, structureId); - else if (Utils.isMDA()) - taskUtils.generateMDADispenseTask(applicationContext, baseEntityId, structureId); + //TODO add hook when task is generated appExecutors.mainThread().execute(() -> { presenter.onTasksGenerated(); }); @@ -146,9 +143,9 @@ public void archiveFamily(String familyBaseEntityId, String structureId) { } taskRepository.cancelTasksForEntity(structureId); taskRepository.archiveTasksForEntity(structureId); - task = taskUtils.generateRegisterFamilyTask(RevealApplication.getInstance().getApplicationContext(), structureId); db.setTransactionSuccessful(); saved = true; + //TODO retrieve task that was generated by dynamic tasking } catch (Exception e) { Timber.e(e); } finally { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractor.java index 41a0d3fd31..50f9a0ea6d 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractor.java @@ -7,14 +7,11 @@ import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.contract.FamilyRegisterContract; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.TaskUtils; -import org.smartregister.reveal.util.Utils; import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.util.AppExecutors; -import java.util.HashSet; import java.util.List; -import java.util.Set; /** * Created by samuelgithengi on 4/15/19. @@ -44,21 +41,7 @@ public ClientProcessorForJava getClientProcessorForJava() { @Override public void generateTasks(List eventClientList, String structureId, Context context) { appExecutors.diskIO().execute(() -> { - Set generatedIds = new HashSet<>(); - for (FamilyEventClient eventClient : eventClientList) { - if (eventClient.getClient().getLastName().equals("Family")) - continue; - String entityId = eventClient.getClient().getBaseEntityId(); - if (!generatedIds.contains(entityId)) { - generatedIds.add(entityId); - if (Utils.isFocusInvestigation()) - taskUtils.generateBloodScreeningTask(context, entityId, structureId); - else if (Utils.isMDA()) - taskUtils.generateMDADispenseTask(context, entityId, structureId); - } - } - if (Utils.isFocusInvestigation()) - taskUtils.generateBedNetDistributionTask(context, structureId); + //TODO add hook when task is generated appExecutors.mainThread().execute(() -> presenter.onTasksGenerated(eventClientList)); }); } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StatsFragmentInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StatsFragmentInteractor.java index 828c2d8f86..23e0e07323 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StatsFragmentInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StatsFragmentInteractor.java @@ -6,7 +6,7 @@ import org.smartregister.repository.BaseRepository; import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.contract.StatsFragmentContract; -import org.smartregister.reveal.util.AppExecutors; +import org.smartregister.util.AppExecutors; import java.util.HashMap; import java.util.Map; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StructureTasksInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StructureTasksInteractor.java index 81879bf90c..0fa3dedba3 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StructureTasksInteractor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/StructureTasksInteractor.java @@ -1,9 +1,10 @@ package org.smartregister.reveal.interactor; import android.content.Context; -import androidx.annotation.VisibleForTesting; import android.text.TextUtils; +import androidx.annotation.VisibleForTesting; + import net.sqlcipher.Cursor; import net.sqlcipher.SQLException; import net.sqlcipher.database.SQLiteDatabase; @@ -22,10 +23,11 @@ import org.smartregister.reveal.contract.StructureTasksContract; import org.smartregister.reveal.model.EventTask; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.Constants; import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.util.InteractorUtils; +import org.smartregister.tasking.interactor.BaseInteractor; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.util.AppExecutors; import java.util.ArrayList; import java.util.Collections; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterFragmentInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterFragmentInteractor.java deleted file mode 100644 index 0eb649d597..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterFragmentInteractor.java +++ /dev/null @@ -1,419 +0,0 @@ -package org.smartregister.reveal.interactor; - -import android.content.Context; -import android.location.Location; -import androidx.core.util.Pair; -import android.text.TextUtils; - -import com.google.common.annotations.VisibleForTesting; - -import net.sqlcipher.Cursor; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONObject; -import org.smartregister.cursoradapter.SmartRegisterQueryBuilder; -import org.smartregister.family.util.DBConstants; -import org.smartregister.repository.EventClientRepository.event_column; -import org.smartregister.repository.LocationRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.TaskRegisterFragmentContract; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.Constants.EventType; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.InteractorUtils; -import org.smartregister.reveal.util.Utils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import timber.log.Timber; - -import static org.smartregister.domain.Task.INACTIVE_TASK_STATUS; -import static org.smartregister.domain.Task.TaskStatus.COMPLETED; -import static org.smartregister.family.util.DBConstants.KEY.FIRST_NAME; -import static org.smartregister.family.util.DBConstants.KEY.RELATIONAL_ID; -import static org.smartregister.repository.EventClientRepository.Table.event; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.BASE_ENTITY_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.BUSINESS_STATUS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.CODE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.COMPLETED_TASK_COUNT; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.FAMILY_NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.FOR; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.GROUPED_STRUCTURE_TASK_CODE_AND_STATUS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.GROUPED_TASKS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.GROUPID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.LAST_NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.LATITUDE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.LONGITUDE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.NOT_SRAYED_OTHER_REASON; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.NOT_SRAYED_REASON; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.OTHER; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.PLAN_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.REFERENCE_REASON; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.SPRAYED_STRUCTURES; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.SPRAY_STATUS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STATUS; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURES_TABLE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_NAME; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.TASK_COUNT; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.TASK_TABLE; -import static org.smartregister.reveal.util.Constants.Intervention.BCC; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Properties.FAMILY_MEMBER_NAMES; -import static org.smartregister.reveal.util.FamilyConstants.DatabaseKeys.HOUSE_NUMBER; -import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY; -import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY_MEMBER; - -/** - * Created by samuelgithengi on 3/18/19. - */ -public class TaskRegisterFragmentInteractor extends BaseInteractor implements TaskRegisterFragmentContract.Interactor { - - private final LocationRepository locationRepository; - private final Float locationBuffer; - private InteractorUtils interactorUtils; - - - private int structuresWithinBuffer = 0; - - public TaskRegisterFragmentInteractor(TaskRegisterFragmentContract.Presenter presenter) { - this(presenter, Utils.getLocationBuffer()); - } - - @VisibleForTesting - public TaskRegisterFragmentInteractor(TaskRegisterFragmentContract.Presenter presenter, - Float locationBuffer) { - super(presenter); - this.locationBuffer = locationBuffer; - locationRepository = RevealApplication.getInstance().getLocationRepository(); - interactorUtils = new InteractorUtils(RevealApplication.getInstance().getTaskRepository(), eventClientRepository, clientProcessor); - } - - private String mainSelect(String mainCondition) { - String tableName = TASK_TABLE; - SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); - queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName), ID); - queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", - STRUCTURES_TABLE, tableName, FOR, STRUCTURES_TABLE, ID)); - queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", - SPRAYED_STRUCTURES, tableName, FOR, SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); - queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", - FAMILY, STRUCTURES_TABLE, ID, FAMILY, STRUCTURE_ID)); - return queryBuilder.mainCondition(mainCondition); - } - - private String nonRegisteredStructureTasksSelect(String mainCondition) { - String tableName = TASK_TABLE; - SmartRegisterQueryBuilder queryBuilder = new SmartRegisterQueryBuilder(); - queryBuilder.selectInitiateMainTable(tableName, mainColumns(tableName), ID); - queryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", - STRUCTURES_TABLE, tableName, FOR, STRUCTURES_TABLE, ID)); - queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", - SPRAYED_STRUCTURES, tableName, FOR, SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); - queryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", - FAMILY, STRUCTURES_TABLE, ID, FAMILY, STRUCTURE_ID)); - queryBuilder.mainCondition(mainCondition); - queryBuilder.addCondition(String.format(" AND %s.%s IS NULL", - FAMILY, STRUCTURE_ID)); - return queryBuilder.addCondition(String.format(" AND %s.%s != '%s'", - tableName, CODE, BEDNET_DISTRIBUTION)); - } - - private String groupedRegisteredStructureTasksSelect(String mainCondition) { - String tableName = TASK_TABLE; - SmartRegisterQueryBuilder structureTasksQueryBuilder = new SmartRegisterQueryBuilder(); - String[] columns = ArrayUtils.add(mainColumns(tableName), String.format("%s.%s||' '||%s.%s as %s ", FAMILY_MEMBER, FIRST_NAME, FAMILY_MEMBER, LAST_NAME, FAMILY_MEMBER_NAMES)); - structureTasksQueryBuilder.selectInitiateMainTable(tableName, columns, ID); - structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s ", - STRUCTURES_TABLE, tableName, STRUCTURE_ID, STRUCTURES_TABLE, ID)); - structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s COLLATE NOCASE", - FAMILY, STRUCTURES_TABLE, ID, FAMILY, STRUCTURE_ID)); - structureTasksQueryBuilder.customJoin(String.format(" JOIN %s ON %s.%s = %s.%s COLLATE NOCASE", - FAMILY_MEMBER, FAMILY, BASE_ENTITY_ID, FAMILY_MEMBER, RELATIONAL_ID)); - structureTasksQueryBuilder.customJoin(String.format(" LEFT JOIN %s ON %s.%s = %s.%s ", - SPRAYED_STRUCTURES, tableName, FOR, SPRAYED_STRUCTURES, DBConstants.KEY.BASE_ENTITY_ID)); - structureTasksQueryBuilder.mainCondition(mainCondition); - - return String.format(" SELECT %s.* , SUM(CASE WHEN status='%s' THEN 1 ELSE 0 END ) AS %s , COUNT(_id ) AS %s, " + - "GROUP_CONCAT(%s || \"-\" || %s ) AS %s , GROUP_CONCAT(%s) as %s FROM ( ", - GROUPED_TASKS, COMPLETED.toString(), COMPLETED_TASK_COUNT, TASK_COUNT, CODE, BUSINESS_STATUS, GROUPED_STRUCTURE_TASK_CODE_AND_STATUS, FAMILY_MEMBER_NAMES, FAMILY_MEMBER_NAMES) + structureTasksQueryBuilder + - String.format(" ) AS %s GROUP BY %s ", GROUPED_TASKS, STRUCTURE_ID); - - } - - private String bccSelect() { - return String.format("SELECT * FROM %s WHERE %s = ? AND %s = ? AND %s ='%s' AND %s NOT IN (%s)", - TASK_TABLE, FOR, PLAN_ID, CODE, BCC, STATUS, - TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))); - } - - private String indexCaseSelect() { - return String.format("SELECT * FROM %s WHERE %s = ? AND %s = ? AND %s NOT IN (%s) AND %s = ? ", - TASK_TABLE, GROUPID, PLAN_ID, STATUS, - TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?")), - CODE); - } - - - private String[] mainColumns(String tableName) { - return new String[]{ - tableName + "." + ID, - tableName + "." + CODE, - tableName + "." + FOR, - tableName + "." + BUSINESS_STATUS, - tableName + "." + STATUS, - tableName + "." + REFERENCE_REASON, - STRUCTURES_TABLE + "." + LATITUDE, - STRUCTURES_TABLE + "." + LONGITUDE, - STRUCTURES_TABLE + "." + NAME, - SPRAYED_STRUCTURES + "." + STRUCTURE_NAME, - SPRAYED_STRUCTURES + "." + FAMILY_NAME, - SPRAYED_STRUCTURES + "." + SPRAY_STATUS, - SPRAYED_STRUCTURES + "." + NOT_SRAYED_REASON, - SPRAYED_STRUCTURES + "." + NOT_SRAYED_OTHER_REASON, - STRUCTURES_TABLE + "." + ID + " AS " + STRUCTURE_ID, - FAMILY + "." + FIRST_NAME, - FAMILY + "." + HOUSE_NUMBER - - }; - } - - - public void findTasks(Pair mainCondition, Location lastLocation, Location operationalAreaCenter, String houseLabel) { - if (mainCondition == null || mainCondition.second == null || mainCondition.second.length < 3 || mainCondition.second[0] == null) { - getPresenter().onTasksFound(null, 0); - return; - } - // Fetch grouped tasks - List tasks = new ArrayList<>(); - appExecutors.diskIO().execute(() -> { - structuresWithinBuffer = 0; - if (Utils.isFocusInvestigationOrMDA()) { // perform task grouping - - tasks.addAll(queryTaskDetails(groupedRegisteredStructureTasksSelect(mainCondition.first), - mainCondition.second, lastLocation, operationalAreaCenter, houseLabel, true)); - - - tasks.addAll(queryTaskDetails(nonRegisteredStructureTasksSelect(mainCondition.first), - mainCondition.second, lastLocation, operationalAreaCenter, houseLabel, false)); - - } else { - - tasks.addAll(queryTaskDetails(mainSelect(mainCondition.first), mainCondition.second, - lastLocation, operationalAreaCenter, houseLabel, false)); - - } - - // Query BCC task - tasks.addAll(queryTaskDetails(bccSelect(), mainCondition.second, lastLocation, - operationalAreaCenter, houseLabel, false)); - - - // Query Case Confirmation task - String[] params = ArrayUtils.add(mainCondition.second, CASE_CONFIRMATION); - tasks.addAll(queryTaskDetails(indexCaseSelect(), params, lastLocation, - operationalAreaCenter, houseLabel, false)); - - Collections.sort(tasks); - appExecutors.mainThread().execute(() -> { - getPresenter().onTasksFound(tasks, structuresWithinBuffer); - }); - - }); - - } - - private List queryTaskDetails(String query, String[] params, Location lastLocation, - Location operationalAreaCenter, String houseLabel, boolean groupedTasks) { - List tasks = new ArrayList<>(); - Cursor cursor = null; - try { - cursor = getDatabase().rawQuery(query, params); - while (cursor != null && cursor.moveToNext()) { - TaskDetails taskDetails = readTaskDetails(cursor, lastLocation, operationalAreaCenter, houseLabel, groupedTasks); - //skip BCC and Case confirmation tasks in tracking tasks within buffer - if (taskDetails.getDistanceFromUser() <= locationBuffer && taskDetails.getDistanceFromUser() >= 0) { - structuresWithinBuffer += 1; - } - tasks.add(taskDetails); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return tasks; - } - - - private TaskDetails readTaskDetails(Cursor cursor, Location lastLocation, Location operationalAreaCenter, String houseLabel, boolean isGroupedTasks) { - TaskDetails task = new TaskDetails(cursor.getString(cursor.getColumnIndex(ID))); - task.setTaskCode(cursor.getString(cursor.getColumnIndex(CODE))); - task.setTaskEntity(cursor.getString(cursor.getColumnIndex(FOR))); - task.setBusinessStatus(cursor.getString(cursor.getColumnIndex(BUSINESS_STATUS))); - task.setTaskStatus(cursor.getString(cursor.getColumnIndex(STATUS))); - if (isGroupedTasks) { - task.setTaskCount(cursor.getInt(cursor.getColumnIndex(TASK_COUNT))); - task.setCompleteTaskCount(cursor.getInt(cursor.getColumnIndex(COMPLETED_TASK_COUNT))); - task.setGroupedTaskCodeStatus(cursor.getString(cursor.getColumnIndex(GROUPED_STRUCTURE_TASK_CODE_AND_STATUS))); - task.setHouseNumber(cursor.getString(cursor.getColumnIndex(HOUSE_NUMBER))); - task.setFamilyMemberNames(cursor.getString(cursor.getColumnIndex(FAMILY_MEMBER_NAMES))); - } - Location location = new Location((String) null); - - if (CASE_CONFIRMATION.equals(task.getTaskCode())) { - task.setReasonReference(cursor.getString(cursor.getColumnIndex(REFERENCE_REASON))); - } else if (!BCC.equals(task.getTaskCode())) { - location.setLatitude(cursor.getDouble(cursor.getColumnIndex(LATITUDE))); - location.setLongitude(cursor.getDouble(cursor.getColumnIndex(LONGITUDE))); - task.setLocation(location); - task.setStructureName(cursor.getString(cursor.getColumnIndex(NAME))); - if (StringUtils.isBlank(task.getStructureName())) { - task.setStructureName(cursor.getString(cursor.getColumnIndex(STRUCTURE_NAME))); - } - - task.setFamilyName(cursor.getString(cursor.getColumnIndex(FIRST_NAME))); - if (task.getFamilyName() == null) { - task.setFamilyName(cursor.getString(cursor.getColumnIndex(FAMILY_NAME))); - } - - if (task.getFamilyName() != null) - task.setFamilyName(task.getFamilyName() + " " + houseLabel); - - task.setSprayStatus(cursor.getString(cursor.getColumnIndex(SPRAY_STATUS))); - - if (Constants.BusinessStatus.NOT_SPRAYED.equals(task.getBusinessStatus())) { - String reason = cursor.getString(cursor.getColumnIndex(NOT_SRAYED_REASON)); - if (OTHER.equals(reason)) { - reason = cursor.getString(cursor.getColumnIndex(NOT_SRAYED_OTHER_REASON)); - } - task.setTaskDetails(reason); - } - } - task.setStructureId(cursor.getString(cursor.getColumnIndex(STRUCTURE_ID))); - - calculateDistance(task, location, lastLocation, operationalAreaCenter); - - return task; - } - - private void calculateDistance(TaskDetails task, Location location, Location lastLocation, Location operationalAreaCenter) { - if (BCC.equals(task.getTaskCode())) { - //set distance to -2 to always display on top of register - task.setDistanceFromUser(-2); - } else if (CASE_CONFIRMATION.equals(task.getTaskCode()) && task.getTaskCount() == null) { - //set distance to -1 to always display on top of register and below BCC - task.setDistanceFromUser(-1); - } else if (lastLocation != null) { - task.setDistanceFromUser(location.distanceTo(lastLocation)); - } else { - task.setDistanceFromUser(location.distanceTo(operationalAreaCenter)); - task.setDistanceFromCenter(true); - } - } - - - public void calculateDistanceFromUser(List tasks, Location location) { - if (tasks == null) - return; - appExecutors.diskIO().execute(() -> { - int structuresWithinBuffer = 0; - for (TaskDetails taskDetails : tasks) { - if (!BCC.equals(taskDetails.getTaskCode()) && !CASE_CONFIRMATION.equals(taskDetails.getTaskCode())) { - taskDetails.setDistanceFromUser(taskDetails.getLocation().distanceTo(location)); - taskDetails.setDistanceFromCenter(false); - } - if (taskDetails.getDistanceFromUser() <= locationBuffer) { - structuresWithinBuffer += 1; - } - } - Collections.sort(tasks); - int finalStructuresWithinBuffer = structuresWithinBuffer; - appExecutors.mainThread().execute(() -> { - getPresenter().onTasksFound(tasks, finalStructuresWithinBuffer); - }); - }); - - } - - - public void getStructure(TaskDetails taskDetails) { - appExecutors.diskIO().execute(() -> { - org.smartregister.domain.Location structure; - if (BCC.equals(taskDetails.getTaskCode())) - structure = locationRepository.getLocationById(taskDetails.getTaskEntity()); - else - structure = structureRepository.getLocationById(taskDetails.getStructureId()); - appExecutors.mainThread().execute(() -> { - getPresenter().onStructureFound(structure, taskDetails); - }); - }); - } - - private TaskRegisterFragmentContract.Presenter getPresenter() { - return (TaskRegisterFragmentContract.Presenter) presenterCallBack; - } - - public void getIndexCaseDetails(String structureId, String operationalArea, String indexCaseEventId) { - appExecutors.diskIO().execute(() -> { - JSONObject jsonEvent = null; - if (StringUtils.isNotBlank(structureId) || StringUtils.isNotBlank(operationalArea)) { - - Cursor cursor = null; - try { - String[] params; - if (structureId == null) { - params = new String[]{operationalArea, EventType.CASE_DETAILS_EVENT}; - } else { - params = new String[]{structureId, operationalArea, EventType.CASE_DETAILS_EVENT}; - } - String query = String.format("SELECT %s FROM %s WHERE %s IN (%s) AND %s = ?", event_column.json.name(), event.name(), event_column.baseEntityId.name(), - structureId == null ? "?" : "?,?", event_column.eventType.name()); - cursor = getDatabase().rawQuery(query, params); - while (cursor.moveToNext()) { - String jsonEventStr = cursor.getString(0); - - jsonEventStr = jsonEventStr.replaceAll("'", ""); - - jsonEvent = new JSONObject(jsonEventStr); - - if (cursor.getCount() == 1 || jsonEvent.optString(event_column.baseEntityId.name()).equals(indexCaseEventId)) { - break; - } - } - } catch (Exception e) { - Timber.e(e); - } finally { - if (cursor != null) { - cursor.close(); - } - } - - } - JSONObject finalJsonEvent = jsonEvent; - appExecutors.mainThread().execute(() -> { - getPresenter().onIndexCaseFound(finalJsonEvent, finalJsonEvent != null - && operationalArea.equals(finalJsonEvent.optString(Properties.BASE_ENTITY_ID))); - }); - }); - - } - - @Override - public void resetTaskInfo(Context context, TaskDetails taskDetails) { - appExecutors.diskIO().execute(() -> { - interactorUtils.resetTaskInfo(getDatabase(), taskDetails); - }); - - appExecutors.mainThread().execute(() -> { - getPresenter().onTaskInfoReset(); - }); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterInteractor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterInteractor.java deleted file mode 100644 index 8f68c91556..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/interactor/TaskRegisterInteractor.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.smartregister.reveal.interactor; - -import org.smartregister.configurableviews.ConfigurableViewsLibrary; -import org.smartregister.configurableviews.helper.ConfigurableViewsHelper; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseContract; -import org.smartregister.reveal.contract.TaskRegisterContract; -import org.smartregister.reveal.util.AppExecutors; - -import java.util.List; - -/** - * Created by samuelgithengi on 3/14/19. - */ -public class TaskRegisterInteractor extends BaseInteractor implements TaskRegisterContract.Interactor { - - private ConfigurableViewsHelper viewsHelper; - - private AppExecutors appExecutors; - - public TaskRegisterInteractor(BaseContract.BasePresenter presenterCallBack) { - super(presenterCallBack); - viewsHelper = ConfigurableViewsLibrary.getInstance().getConfigurableViewsHelper(); - appExecutors = RevealApplication.getInstance().getAppExecutors(); - } - - @Override - public void registerViewConfigurations(List viewIdentifiers) { - appExecutors.diskIO().execute(() -> { - viewsHelper.registerViewConfigurations(viewIdentifiers); - }); - } - - @Override - public void unregisterViewConfiguration(List viewIdentifiers) { - viewsHelper.unregisterViewConfiguration(viewIdentifiers); - } - - @Override - public void cleanupResources() { - viewsHelper = null; - appExecutors = null; - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/LocationTaskServiceJob.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/job/LocationTaskServiceJob.java index 02e5cff305..5824eac7fc 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/LocationTaskServiceJob.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/job/LocationTaskServiceJob.java @@ -1,13 +1,15 @@ package org.smartregister.reveal.job; import android.content.Intent; + import androidx.annotation.NonNull; import com.evernote.android.job.Job; import org.smartregister.AllConstants; import org.smartregister.job.BaseJob; -import org.smartregister.reveal.sync.LocationTaskIntentService; +import org.smartregister.tasking.sync.LocationTaskIntentService; + public class LocationTaskServiceJob extends BaseJob { public static final String TAG = "LocationTaskServiceJob"; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealJobCreator.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealJobCreator.java index 711bbef61e..cbc53ea2fb 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealJobCreator.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealJobCreator.java @@ -13,6 +13,7 @@ import org.smartregister.job.ValidateSyncDataServiceJob; import org.smartregister.reveal.sync.RevealSyncIntentService; import org.smartregister.sync.intent.DocumentConfigurationIntentService; +import org.smartregister.tasking.job.RevealSyncSettingsServiceJob; import timber.log.Timber; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealSyncSettingsServiceJob.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealSyncSettingsServiceJob.java deleted file mode 100644 index 9a7f1b53ab..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/job/RevealSyncSettingsServiceJob.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.smartregister.reveal.job; - -import android.content.Intent; -import androidx.annotation.NonNull; - -import org.smartregister.AllConstants; -import org.smartregister.job.SyncSettingsServiceJob; -import org.smartregister.reveal.sync.RevealSettingsSyncIntentService; - -/** - * @author Vincent Karuri - */ -public class RevealSyncSettingsServiceJob extends SyncSettingsServiceJob { - - public static final String TAG = "RevealSyncSettingsServiceJob"; - - @NonNull - @Override - protected Result onRunJob(@NonNull Params params) { - Intent intent = new Intent(getApplicationContext(), RevealSettingsSyncIntentService.class); - getApplicationContext().startService(intent); - return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/BaseTaskDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/BaseTaskDetails.java deleted file mode 100644 index 14099b368b..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/BaseTaskDetails.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.smartregister.reveal.model; - -import androidx.annotation.NonNull; - -/** - * Created by samuelgithengi on 4/11/19. - */ -public class BaseTaskDetails { - - private String taskId; - - private String taskCode; - - private String taskEntity; - - private String businessStatus; - - private String taskStatus; - - private String structureId; - - private String familyMemberNames; - - public BaseTaskDetails(@NonNull String taskId) { - this.taskId = taskId; - } - - public String getTaskId() { - return taskId; - } - - public void setTaskId(String taskId) { - this.taskId = taskId; - } - - public String getTaskCode() { - return taskCode; - } - - public void setTaskCode(String taskCode) { - this.taskCode = taskCode; - } - - public String getTaskEntity() { - return taskEntity; - } - - public void setTaskEntity(String taskEntity) { - this.taskEntity = taskEntity; - } - - public String getBusinessStatus() { - return businessStatus; - } - - public void setBusinessStatus(String businessStatus) { - this.businessStatus = businessStatus; - } - - public String getTaskStatus() { - return taskStatus; - } - - public void setTaskStatus(String taskStatus) { - this.taskStatus = taskStatus; - } - - public String getStructureId() { - return structureId; - } - - public void setStructureId(String structureId) { - this.structureId = structureId; - } - - public String getFamilyMemberNames() { - return familyMemberNames; - } - - public void setFamilyMemberNames(String familyMemberNames) { - this.familyMemberNames = familyMemberNames; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof BaseTaskDetails)) - return false; - BaseTaskDetails other = (BaseTaskDetails) obj; - return getTaskId().equals(other.getTaskId()); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/CardDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/CardDetails.java deleted file mode 100644 index 809f0fdf6c..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/CardDetails.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.smartregister.reveal.model; - -import org.smartregister.reveal.R; - -/** - * @author Vincent Karuri - */ - -public class CardDetails { - protected String status; - private int statusMessage; - private int statusColor = R.color.task_not_done; - private String reason; - private String comments; - - public CardDetails(String status) { - this.status = status; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public int getStatusMessage() { - return statusMessage; - } - - public void setStatusMessage(int statusMessage) { - this.statusMessage = statusMessage; - } - - public Integer getStatusColor() { - return statusColor; - } - - public void setStatusColor(Integer statusColor) { - this.statusColor = statusColor; - } - - public String getReason() { - return reason; - } - - public void setReason(String reason) { - this.reason = reason; - } - - public String getComments() { - return comments; - } - - public void setComments(String comments) { - this.comments = comments; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyCardDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyCardDetails.java index f9500c610d..41edde30e6 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyCardDetails.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyCardDetails.java @@ -1,5 +1,7 @@ package org.smartregister.reveal.model; +import org.smartregister.tasking.model.CardDetails; + public class FamilyCardDetails extends CardDetails { private String dateCreated; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyProfileModel.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyProfileModel.java index ded38d1a20..ad2f49b34f 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyProfileModel.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyProfileModel.java @@ -8,7 +8,7 @@ import org.smartregister.family.util.Utils; import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.PreferencesUtil; +import org.smartregister.tasking.util.PreferencesUtil; import org.smartregister.util.FormUtils; import static org.smartregister.reveal.util.Constants.DatabaseKeys.LAST_NAME; @@ -58,7 +58,9 @@ private void tagEventClientDetails(FamilyEventClient eventClient) { eventClient.getEvent().addDetails(Constants.Properties.LOCATION_ID, structureId); } eventClient.getEvent().addDetails(Constants.Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); - eventClient.getEvent().setLocationId(org.smartregister.reveal.util.Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()).getId()); + String planIdentifier = PreferencesUtil.getInstance().getCurrentPlanId(); + eventClient.getEvent().addDetails(Constants.Properties.PLAN_IDENTIFIER, planIdentifier); + eventClient.getEvent().setLocationId(org.smartregister.tasking.util.Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()).getId()); } public void setStructureId(String structureId) { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyRegisterModel.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyRegisterModel.java index c603a21970..88ab64d62d 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyRegisterModel.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/FamilyRegisterModel.java @@ -6,7 +6,7 @@ import org.smartregister.family.model.BaseFamilyRegisterModel; import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.PreferencesUtil; +import org.smartregister.tasking.util.PreferencesUtil; import org.smartregister.util.JsonFormUtils; import java.util.List; @@ -47,7 +47,7 @@ public List processRegistration(String jsonString) { eventClient.getEvent().addDetails(Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); String planIdentifier = PreferencesUtil.getInstance().getCurrentPlanId(); eventClient.getEvent().addDetails(Properties.PLAN_IDENTIFIER, planIdentifier); - Location operationalArea = org.smartregister.reveal.util.Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()); + Location operationalArea = org.smartregister.tasking.util.Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()); if (operationalArea != null) eventClient.getEvent().setLocationId(operationalArea.getId()); } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/IRSVerificationCardDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/IRSVerificationCardDetails.java index ebb5324caa..0fb790c0af 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/IRSVerificationCardDetails.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/IRSVerificationCardDetails.java @@ -1,5 +1,7 @@ package org.smartregister.reveal.model; +import org.smartregister.tasking.model.CardDetails; + public class IRSVerificationCardDetails extends CardDetails { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/MosquitoHarvestCardDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/MosquitoHarvestCardDetails.java index cfac0962dc..329e6212b5 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/MosquitoHarvestCardDetails.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/MosquitoHarvestCardDetails.java @@ -1,5 +1,7 @@ package org.smartregister.reveal.model; +import org.smartregister.tasking.model.CardDetails; + /** * @author Vincent Karuri */ diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/OfflineMapModel.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/OfflineMapModel.java deleted file mode 100644 index 2ef956ea39..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/OfflineMapModel.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.smartregister.reveal.model; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.domain.Location; - -import java.util.Date; - -public class OfflineMapModel { - - private Location location; - - private OfflineRegion offlineRegion; - - private Date dateCreated; - - public enum OfflineMapStatus { - READY, - DOWNLOAD_STARTED, - DOWNLOADED, - SELECTED_FOR_DOWNLOAD - } - - private OfflineMapStatus offlineMapStatus; - - public OfflineMapModel() { - setOfflineMapStatus(OfflineMapStatus.READY); - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - - public OfflineMapStatus getOfflineMapStatus() { - return offlineMapStatus; - } - - public void setOfflineMapStatus(OfflineMapStatus offlineMapStatus) { - this.offlineMapStatus = offlineMapStatus; - } - - public String getDownloadAreaLabel() { - return (location != null && location.getProperties() != null) ? location.getProperties().getName() : null; - } - - public String getDownloadAreaId() { - return location != null ? location.getId() : null; - } - - public OfflineRegion getOfflineRegion() { - return offlineRegion; - } - - public void setOfflineRegion(OfflineRegion offlineRegion) { - this.offlineRegion = offlineRegion; - } - - public Date getDateCreated() { - return dateCreated; - } - - public void setDateCreated(Date dateCreated) { - this.dateCreated = dateCreated; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/SprayCardDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/SprayCardDetails.java index c825424a8e..7a22198ea1 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/SprayCardDetails.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/SprayCardDetails.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.model; import org.smartregister.commonregistry.CommonPersonObject; +import org.smartregister.tasking.model.CardDetails; /** * @author Vincent Karuri diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/StructureTaskDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/StructureTaskDetails.java index 98dcfafa73..9ffaabb3ff 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/StructureTaskDetails.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/StructureTaskDetails.java @@ -2,6 +2,8 @@ import androidx.annotation.NonNull; +import org.smartregister.tasking.model.BaseTaskDetails; + import java.util.Date; /** diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskDetails.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskDetails.java deleted file mode 100644 index 1ee093edb6..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskDetails.java +++ /dev/null @@ -1,369 +0,0 @@ -package org.smartregister.reveal.model; - -import android.location.Location; -import androidx.annotation.NonNull; - -import org.apache.commons.lang3.StringUtils; -import org.smartregister.reveal.util.Utils; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import static org.smartregister.reveal.util.Constants.BusinessStatus.BEDNET_DISTRIBUTED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.BLOOD_SCREENING_COMPLETE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.COMPLETE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.FAMILY_REGISTERED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.FULLY_RECEIVED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NONE_RECEIVED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_ELIGIBLE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_VISITED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.PARTIALLY_RECEIVED; -import static org.smartregister.reveal.util.Constants.COMMA; -import static org.smartregister.reveal.util.Constants.HYPHEN; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_ADHERENCE; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_DISPENSE; -import static org.smartregister.reveal.util.Constants.Intervention.REGISTER_FAMILY; - -/** - * Created by samuelgithengi on 3/20/19. - */ -public class TaskDetails extends BaseTaskDetails implements Comparable, Serializable { - - private Location location; - - private String structureName; - - private String familyName; - - private float distanceFromUser; - - private String sprayStatus; - - private String taskDetails; - - private boolean distanceFromCenter; - - private Integer taskCount; - - private Integer completeTaskCount; - - private boolean familyRegistered; - - private boolean bednetDistributed; - - private boolean bloodScreeningDone; - - private String reasonReference; - - private String houseNumber; - - private boolean familyRegTaskExists; - - private boolean mdaAdhered; - - private boolean fullyReceived; - - private boolean partiallyReceived; - - private boolean noneReceived; - - private boolean notEligible; - - private String aggregateBusinessStatus; - - public TaskDetails(@NonNull String taskId) { - super(taskId); - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - - public String getStructureName() { - return structureName; - } - - public void setStructureName(String structureName) { - this.structureName = structureName; - } - - public String getFamilyName() { - return familyName; - } - - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - public float getDistanceFromUser() { - return distanceFromUser; - } - - public void setDistanceFromUser(float distanceFromUser) { - this.distanceFromUser = distanceFromUser; - } - - public String getSprayStatus() { - return sprayStatus; - } - - public void setSprayStatus(String sprayStatus) { - this.sprayStatus = sprayStatus; - } - - public String getTaskDetails() { - return taskDetails; - } - - public void setTaskDetails(String taskDetails) { - this.taskDetails = taskDetails; - } - - public boolean isDistanceFromCenter() { - return distanceFromCenter; - } - - public void setDistanceFromCenter(boolean distanceFromCenter) { - this.distanceFromCenter = distanceFromCenter; - } - - public void setTaskCount(Integer taskCount) { - this.taskCount = taskCount; - } - - public Integer getCompleteTaskCount() { - return completeTaskCount; - } - - public void setCompleteTaskCount(Integer completeTaskCount) { - this.completeTaskCount = completeTaskCount; - } - - public Integer getTaskCount() { - return taskCount; - } - - public boolean isFamilyRegistered() { - return familyRegistered; - } - - public void setFamilyRegistered(boolean familyRegistered) { - this.familyRegistered = familyRegistered; - } - - public boolean isBednetDistributed() { - return bednetDistributed; - } - - public void setBednetDistributed(boolean bednetDistributed) { - this.bednetDistributed = bednetDistributed; - } - - public boolean isBloodScreeningDone() { - return bloodScreeningDone; - } - - public void setBloodScreeningDone(boolean bloodScreeningDone) { - this.bloodScreeningDone = bloodScreeningDone; - } - - public boolean isFamilyRegTaskExists() { - return familyRegTaskExists; - } - - public void setFamilyRegTaskExists(boolean familyRegTaskExists) { - this.familyRegTaskExists = familyRegTaskExists; - } - - public boolean isMdaAdhered() { - return mdaAdhered; - } - - public void setMdaAdhered(boolean mdaAdhered) { - this.mdaAdhered = mdaAdhered; - } - - public boolean isFullyReceived() { - return fullyReceived; - } - - public void setFullyReceived(boolean fullyReceived) { - this.fullyReceived = fullyReceived; - } - - public boolean isPartiallyReceived() { - return partiallyReceived; - } - - public void setPartiallyReceived(boolean partiallyReceived) { - this.partiallyReceived = partiallyReceived; - } - - public boolean isNoneReceived() { - return noneReceived; - } - - public void setNoneReceived(boolean noneReceived) { - this.noneReceived = noneReceived; - } - - public boolean isNotEligible() { - return notEligible; - } - - public void setNotEligible(boolean notEligible) { - this.notEligible = notEligible; - } - - public void setGroupedTaskCodeStatus(String groupedTaskCodeStatusString) { - setFamilyRegistered(false); - setBednetDistributed(false); - setBloodScreeningDone(false); - setFamilyRegTaskExists(false); - if (StringUtils.isEmpty(groupedTaskCodeStatusString)) { - return; - } - String[] groupedTaskCodeStatusArray = groupedTaskCodeStatusString.split(COMMA); - String MDA_DISPENSE_TASK_COUNT = "mda_dispense_task_count"; - - Map mdaStatusMap = new HashMap<>(); - mdaStatusMap.put(FULLY_RECEIVED, 0); - mdaStatusMap.put(NONE_RECEIVED, 0); - mdaStatusMap.put(NOT_ELIGIBLE, 0); - mdaStatusMap.put(MDA_DISPENSE_TASK_COUNT, 0); - - boolean bloodScreeningExists = false; - boolean caseConfirmed = false; - for (int i = 0; i < groupedTaskCodeStatusArray.length; i++) { - String[] taskCodeStatusArray = groupedTaskCodeStatusArray[i].split(HYPHEN); - - if (taskCodeStatusArray == null || taskCodeStatusArray.length != 2) { - continue; - } - - switch (taskCodeStatusArray[0]) { - case REGISTER_FAMILY: - setFamilyRegTaskExists(true); - this.familyRegistered = COMPLETE.equals(taskCodeStatusArray[1]); - break; - case BEDNET_DISTRIBUTION: - this.bednetDistributed = COMPLETE.equals(taskCodeStatusArray[1]); - break; - case BLOOD_SCREENING: - if (!this.bloodScreeningDone) { - this.bloodScreeningDone = COMPLETE.equals(taskCodeStatusArray[1]); - } - bloodScreeningExists = true; - break; - case CASE_CONFIRMATION: - caseConfirmed = COMPLETE.equals(taskCodeStatusArray[1]); - break; - case MDA_ADHERENCE: - this.mdaAdhered = COMPLETE.equals(taskCodeStatusArray[1]); - break; - case MDA_DISPENSE: - mdaStatusMap.put(MDA_DISPENSE_TASK_COUNT, mdaStatusMap.get(MDA_DISPENSE_TASK_COUNT) + 1); - switch (taskCodeStatusArray[1]) { - case FULLY_RECEIVED: - mdaStatusMap.put(FULLY_RECEIVED, mdaStatusMap.get(FULLY_RECEIVED) + 1); - break; - case NONE_RECEIVED: - mdaStatusMap.put(NONE_RECEIVED, mdaStatusMap.get(NONE_RECEIVED) + 1); - break; - case NOT_ELIGIBLE: - mdaStatusMap.put(NOT_ELIGIBLE, mdaStatusMap.get(NOT_ELIGIBLE) + 1); - break; - } - default: - break; - } - } - - if (!bloodScreeningExists && caseConfirmed && !isBloodScreeningDone()) { - setBloodScreeningDone(true); - } - - setFullyReceived(mdaStatusMap.get(FULLY_RECEIVED) == mdaStatusMap.get(MDA_DISPENSE_TASK_COUNT)); - setNoneReceived(mdaStatusMap.get(NONE_RECEIVED) == mdaStatusMap.get(MDA_DISPENSE_TASK_COUNT)); - setNotEligible(mdaStatusMap.get(NOT_ELIGIBLE) == mdaStatusMap.get(MDA_DISPENSE_TASK_COUNT)); - setPartiallyReceived(!isFullyReceived() && (mdaStatusMap.get(FULLY_RECEIVED) > 0)); - - setAggregateBusinessStatus(calculateAggregateBusinessStatus()); - } - - /** - * @return the aggregate business status - * @see org.smartregister.reveal.viewholder.TaskRegisterViewHolder#getActionDrawable(TaskDetails task) - * Calculates the aggregate/overall business status - */ - private String calculateAggregateBusinessStatus() { - if (Utils.isFocusInvestigation()) { - if (isFamilyRegisteredOrNoTaskExists() && isBednetDistributed() && isBloodScreeningDone()) { - return COMPLETE; - } else if (isFamilyRegisteredOrNoTaskExists() && !isBednetDistributed() && !isBloodScreeningDone()) { - return FAMILY_REGISTERED; - } else if (isFamilyRegisteredOrNoTaskExists() && isBednetDistributed()) { - return BEDNET_DISTRIBUTED; - } else if (isBloodScreeningDone()) { - return BLOOD_SCREENING_COMPLETE; - } - } else if (Utils.isMDA()) { - if (isFamilyRegisteredOrNoTaskExists() && isMdaAdhered()) { - return COMPLETE; - } else if (isFamilyRegisteredOrNoTaskExists() && isFullyReceived()) { - return FULLY_RECEIVED; - } else if (isFamilyRegisteredOrNoTaskExists() && isPartiallyReceived()) { - return PARTIALLY_RECEIVED; - } else if (isFamilyRegisteredOrNoTaskExists() && isNoneReceived()) { - return NONE_RECEIVED; - } else if (isFamilyRegisteredOrNoTaskExists()) { - return FAMILY_REGISTERED; - } - } else if (isNotEligible()) { - return NOT_ELIGIBLE; - } - return NOT_VISITED; - } - - private boolean isFamilyRegisteredOrNoTaskExists() { - return isFamilyRegistered() || !isFamilyRegTaskExists(); - } - - - @Override - public int compareTo(@NonNull TaskDetails other) { - return Double.compare(distanceFromUser, other.getDistanceFromUser()); - } - - public void setReasonReference(String reasonReference) { - this.reasonReference = reasonReference; - } - - public String getReasonReference() { - return reasonReference; - } - - public String getHouseNumber() { - return houseNumber; - } - - public void setHouseNumber(String houseNumber) { - this.houseNumber = houseNumber; - } - - public String getAggregateBusinessStatus() { - return aggregateBusinessStatus; - } - - public void setAggregateBusinessStatus(String aggregateBusinessStatus) { - this.aggregateBusinessStatus = aggregateBusinessStatus; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskFilterParams.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskFilterParams.java deleted file mode 100644 index 03c57d791d..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/model/TaskFilterParams.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.smartregister.reveal.model; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Created by samuelgithengi on 12/17/19. - */ -public class TaskFilterParams implements Serializable { - - private String sortBy; - - private String searchPhrase; - - private Map> checkedFilters = new HashMap<>(); - - public TaskFilterParams(String sortBy, Map> checkedFilters) { - this.sortBy = sortBy; - this.checkedFilters = checkedFilters; - } - - public TaskFilterParams(String searchPhrase) { - setSearchPhrase(searchPhrase); - } - - public String getSortBy() { - return sortBy; - } - - public void setSortBy(String sortBy) { - this.sortBy = sortBy; - } - - public Map> getCheckedFilters() { - return checkedFilters; - } - - public String getSearchPhrase() { - return searchPhrase; - } - - public void setSearchPhrase(String searchPhrase) { - this.searchPhrase = searchPhrase; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/AvailableOfflineMapsPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/AvailableOfflineMapsPresenter.java deleted file mode 100644 index 1b2a71fa0a..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/AvailableOfflineMapsPresenter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.smartregister.reveal.presenter; - -import org.smartregister.reveal.contract.AvailableOfflineMapsContract; -import org.smartregister.reveal.interactor.AvailableOfflineMapsInteractor; -import org.smartregister.reveal.model.OfflineMapModel; - -import java.util.List; - -public class AvailableOfflineMapsPresenter implements AvailableOfflineMapsContract.Presenter { - - private AvailableOfflineMapsContract.Interactor interactor; - private AvailableOfflineMapsContract.View view; - - public AvailableOfflineMapsPresenter(AvailableOfflineMapsContract.View view) { - this.view = view; - this.interactor = new AvailableOfflineMapsInteractor(this); - } - - @Override - public void fetchAvailableOAsForMapDownLoad(List locationIds) { - interactor.fetchAvailableOAsForMapDownLoad(locationIds); - } - - @Override - public void onFetchAvailableOAsForMapDownLoad(List offlineMapModels) { - view.setOfflineMapModelList(offlineMapModels); - } - - @Override - public void onDownloadStarted(String operationalAreaId) { - view.disableCheckBox(operationalAreaId); - - } - - @Override - public void onDownloadComplete(String operationalAreaId) { - view.moveDownloadedOAToDownloadedList(operationalAreaId); - } - - @Override - public void onDownloadStopped(String operationalAreaId) { - view.removeOperationalAreaToDownload(operationalAreaId); - view.enableCheckBox(operationalAreaId); - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseDrawerPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseDrawerPresenter.java index c862cd2972..710d1ed206 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseDrawerPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseDrawerPresenter.java @@ -1,13 +1,13 @@ package org.smartregister.reveal.presenter; -import androidx.core.content.ContextCompat; -import androidx.core.util.Pair; import android.app.Activity; - import android.text.TextUtils; import android.view.View; import android.widget.TextView; +import androidx.core.content.ContextCompat; +import androidx.core.util.Pair; + import com.google.android.material.navigation.NavigationView; import com.google.gson.reflect.TypeToken; @@ -18,10 +18,10 @@ import org.smartregister.location.helper.LocationHelper; import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseDrawerContract; import org.smartregister.reveal.interactor.BaseDrawerInteractor; import org.smartregister.reveal.util.Country; -import org.smartregister.reveal.util.PreferencesUtil; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.tasking.util.PreferencesUtil; import org.smartregister.util.AssetHandler; import org.smartregister.util.Utils; @@ -165,7 +165,7 @@ public void onShowOperationalAreaSelector() { view.showOperationalAreaSelector(extractLocationHierarchy()); } else { view.displayNotification(R.string.error_fetching_location_hierarchy_title, R.string.error_fetching_location_hierarchy); - revealApplication.getContext().userService().forceRemoteLogin(); + revealApplication.getContext().userService().forceRemoteLogin(revealApplication.getContext().allSharedPreferences().fetchRegisteredANM()); } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseFormFragmentPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseFormFragmentPresenter.java deleted file mode 100644 index 402b14e835..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/BaseFormFragmentPresenter.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.smartregister.reveal.presenter; - -import android.content.Context; -import androidx.core.util.Pair; -import androidx.appcompat.app.AlertDialog; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObject; -import org.smartregister.domain.Location; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseFormFragmentContract; -import org.smartregister.reveal.interactor.BaseFormFragmentInteractor; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.repository.RevealMappingHelper; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.util.Constants.JsonForm; -import org.smartregister.reveal.util.PasswordDialogUtils; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.RevealJsonFormUtils; -import org.smartregister.reveal.util.Utils; -import org.smartregister.util.DateTimeTypeConverter; -import org.smartregister.util.JsonFormUtils; - -import java.lang.ref.WeakReference; - -import io.ona.kujaku.listeners.BaseLocationListener; -import timber.log.Timber; - -import static org.smartregister.family.util.Constants.JSON_FORM_KEY.OPTIONS; -import static org.smartregister.reveal.util.Constants.DateFormat.EVENT_DATE_FORMAT_Z; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.IRS; -import static org.smartregister.reveal.util.Constants.Intervention.LARVAL_DIPPING; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_ADHERENCE; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_DISPENSE; -import static org.smartregister.reveal.util.Constants.Intervention.MOSQUITO_COLLECTION; -import static org.smartregister.reveal.util.Constants.Intervention.REGISTER_FAMILY; -import static org.smartregister.reveal.util.Country.NAMIBIA; - -/** - * Created by samuelgithengi on 4/18/19. - */ -public class BaseFormFragmentPresenter extends BaseLocationListener implements BaseFormFragmentContract.Presenter { - - private final WeakReference view; - private AlertDialog passwordDialog; - - private ValidateUserLocationPresenter locationPresenter; - - protected RevealMappingHelper mappingHelper; - - private Location structure; - - private BaseTaskDetails taskDetails; - - private Context context; - - private BaseFormFragmentInteractor interactor; - - private PreferencesUtil prefsUtil; - - protected Gson gson = new GsonBuilder().setDateFormat(EVENT_DATE_FORMAT_Z) - .registerTypeAdapter(DateTime.class, new DateTimeTypeConverter()).create(); - - private RevealJsonFormUtils jsonFormUtils = new RevealJsonFormUtils(); - - protected BaseFormFragmentPresenter(BaseFormFragmentContract.View view, Context context) { - this.context = context; - this.view = new WeakReference<>(view); - passwordDialog = PasswordDialogUtils.initPasswordDialog(context, this); - locationPresenter = new ValidateUserLocationPresenter(view, this); - mappingHelper = new RevealMappingHelper(); - interactor = new BaseFormFragmentInteractor(this); - prefsUtil = PreferencesUtil.getInstance(); - } - - protected boolean validateFarStructures() { - return Utils.validateFarStructures(); - } - - private void validateUserLocation() { - android.location.Location location = getView().getUserCurrentLocation(); - if (location == null) { - locationPresenter.requestUserLocation(); - } else { - locationPresenter.onGetUserLocation(location); - } - } - - @Override - public void onPasswordVerified() { - onLocationValidated(); - } - - @Override - public void onLocationValidated() { - if (!Intervention.REGISTER_FAMILY.equals(getTaskDetails().getTaskCode())) { - String formName = getView().getJsonFormUtils().getFormName(null, taskDetails.getTaskCode()); - if (StringUtils.isBlank(formName)) { - getView().displayError(R.string.opening_form_title, R.string.form_not_found); - } else { - JSONObject formJSON = getView().getJsonFormUtils().getFormJSON(context, formName, taskDetails, structure); - if (Intervention.BEDNET_DISTRIBUTION.equals(taskDetails.getTaskCode())) { - interactor.findNumberOfMembers(taskDetails.getTaskEntity(), formJSON); - return; - } else if (CASE_CONFIRMATION.equals(taskDetails.getTaskCode())) { - interactor.findMemberDetails(taskDetails.getStructureId(), formJSON); - return; - } else if (IRS.equals(taskDetails.getTaskCode()) && NAMIBIA.equals(BuildConfig.BUILD_COUNTRY)) { - interactor.findSprayDetails(IRS, structure.getId(), formJSON); - } else if (MDA_DISPENSE.equals(taskDetails.getTaskCode()) || MDA_ADHERENCE.equals(taskDetails.getTaskCode())) { - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), formJSON, Constants.CONFIGURATION.MDA_CATCHMENT_AREAS, JsonForm.CATCHMENT_AREA, prefsUtil.getCurrentDistrict()); - getView().startForm(formJSON); - } else { - getView().startForm(formJSON); - } - } - } - getView().hideProgressDialog(); - } - - public void showBasicForm(String formName) { - JSONObject formJSON = getView().getJsonFormUtils().getFormJSON(context, formName, null, null); - switch (formName) { - - case JsonForm.IRS_SA_DECISION_ZAMBIA: - case JsonForm.CB_SPRAY_AREA_ZAMBIA: - case JsonForm.MOBILIZATION_FORM_ZAMBIA: - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.SUPERVISORS, JsonForm.SUPERVISOR, - PreferencesUtil.getInstance().getCurrentDistrict()); - break; - - case JsonForm.IRS_FIELD_OFFICER_ZAMBIA: - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.FIELD_OFFICERS, JsonForm.FIELD_OFFICER, - PreferencesUtil.getInstance().getCurrentDistrict()); - break; - - case JsonForm.DAILY_SUMMARY_ZAMBIA: - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.TEAM_LEADERS, JsonForm.TEAM_LEADER, - PreferencesUtil.getInstance().getCurrentDistrict()); - - case JsonForm.TEAM_LEADER_DOS_ZAMBIA: - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.SUPERVISORS, JsonForm.SUPERVISOR, - PreferencesUtil.getInstance().getCurrentDistrict()); - - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.DATA_COLLECTORS, JsonForm.DATA_COLLECTOR, - PreferencesUtil.getInstance().getCurrentDistrict()); - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.DISTRICT_MANAGERS, JsonForm.DISTRICT_MANAGER, - PreferencesUtil.getInstance().getCurrentDistrict()); - - break; - - case JsonForm.VERIFICATION_FORM_ZAMBIA: - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.FIELD_OFFICERS, JsonForm.FIELD_OFFICER, - PreferencesUtil.getInstance().getCurrentDistrict()); - - jsonFormUtils.populateServerOptions(RevealApplication.getInstance().getServerConfigs(), - formJSON, Constants.CONFIGURATION.DATA_COLLECTORS, JsonForm.DATA_COLLECTOR, - PreferencesUtil.getInstance().getCurrentDistrict()); - - break; - default: - break; - } - getView().startForm(formJSON); - } - - @Override - public LatLng getTargetCoordinates() { - android.location.Location center = mappingHelper.getCenter(gson.toJson(structure.getGeometry())); - return new LatLng(center.getLatitude(), center.getLongitude()); - } - - @Override - public void requestUserPassword() { - if (passwordDialog != null) { - passwordDialog.show(); - } - } - - @Override - public ValidateUserLocationPresenter getLocationPresenter() { - return locationPresenter; - } - - protected BaseFormFragmentContract.View getView() { - return view.get(); - } - - @Override - public void onStructureFound(Location structure, BaseTaskDetails details) { - this.structure = structure; - this.taskDetails = details; - if (IRS.equals(details.getTaskCode()) || MOSQUITO_COLLECTION.equals(details.getTaskCode()) || - LARVAL_DIPPING.equals(details.getTaskCode()) || REGISTER_FAMILY.equals(details.getTaskCode()) || - BEDNET_DISTRIBUTION.equals(details.getTaskCode()) || CASE_CONFIRMATION.equals(details.getTaskCode()) || - BLOOD_SCREENING.equals(details.getTaskCode())) { - if (validateFarStructures()) { - validateUserLocation(); - } else { - onLocationValidated(); - } - } else { - onLocationValidated(); - } - } - - @Override - public void onFetchedMembersCount(Pair numberOfMembers, JSONObject formJSON) { - try { - String jsonStr = formJSON.toString().replace(JsonForm.NUMBER_OF_FAMILY_MEMBERS, numberOfMembers.first + ""); - jsonStr = jsonStr.replace(JsonForm.NUMBER_OF_FAMILY_MEMBERS_SLEEPING_OUTDOORS, numberOfMembers.second + ""); - getView().startForm(new JSONObject(jsonStr)); - } catch (JSONException e) { - Timber.e(e, "Error updating Number of members"); - getView().startForm(formJSON); - } - getView().hideProgressDialog(); - } - - @Override - public void onFetchedFamilyMembers(JSONArray familyMembers, JSONObject formJSON) { - JSONObject familyMemberField = JsonFormUtils.getFieldJSONObject(JsonFormUtils.fields(formJSON), JsonForm.FAMILY_MEMBER); - try { - familyMemberField.put(OPTIONS, familyMembers); - } catch (JSONException e) { - Timber.e(e, "Error updating family members"); - } - getView().startForm(formJSON); - } - - @Override - public void onFetchedSprayDetails(CommonPersonObject commonPersonObject, JSONObject formJSON) { - getView().getJsonFormUtils().populateSprayForm(commonPersonObject, formJSON); - getView().startForm(formJSON); - } - - public BaseTaskDetails getTaskDetails() { - return taskDetails; - } - - public void setTaskDetails(BaseTaskDetails taskDetails) { - this.taskDetails = taskDetails; - } - - public Location getStructure() { - return structure; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/DownloadedOfflineMapsPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/DownloadedOfflineMapsPresenter.java deleted file mode 100644 index 375ba97df4..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/DownloadedOfflineMapsPresenter.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.smartregister.reveal.presenter; - -import android.content.Context; -import androidx.core.util.Pair; - -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.reveal.contract.DownloadedOfflineMapsContract; -import org.smartregister.reveal.interactor.DownloadedOfflineMapsInteractor; -import org.smartregister.reveal.model.OfflineMapModel; - -import java.util.List; -import java.util.Map; - -public class DownloadedOfflineMapsPresenter implements DownloadedOfflineMapsContract.Presenter { - - private DownloadedOfflineMapsContract.View view; - private DownloadedOfflineMapsContract.Interactor interactor; - - public DownloadedOfflineMapsPresenter(DownloadedOfflineMapsContract.View view, Context context) { - this.view = view; - this.interactor = new DownloadedOfflineMapsInteractor(this, context); - } - - @Override - public void onDeleteDownloadMap(List offlineMapModels) { - view.deleteDownloadedOfflineMaps(); - } - - @Override - public void fetchOAsWithOfflineDownloads(Pair, Map> offlineRegionInfo) { - interactor.fetchLocationsWithOfflineMapDownloads(offlineRegionInfo); - } - - @Override - public void onOAsWithOfflineDownloadsFetched(List downloadedOfflineMapModelList) { - view.setDownloadedOfflineMapModelList(downloadedOfflineMapModelList); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyOtherMemberPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyOtherMemberPresenter.java index cbd6ca66f2..d65c853a6a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyOtherMemberPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyOtherMemberPresenter.java @@ -20,8 +20,8 @@ import org.smartregister.reveal.contract.FamilyProfileContract; import org.smartregister.reveal.interactor.RevealFamilyOtherMemberInteractor; import org.smartregister.reveal.model.FamilyProfileModel; -import org.smartregister.reveal.util.AlertDialogUtils; import org.smartregister.reveal.util.FamilyJsonFormUtils; +import org.smartregister.tasking.util.AlertDialogUtils; import timber.log.Timber; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyProfilePresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyProfilePresenter.java index c7ddc3ff26..d02d91cee2 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyProfilePresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FamilyProfilePresenter.java @@ -21,14 +21,14 @@ import org.smartregister.reveal.interactor.RevealFamilyOtherMemberInteractor; import org.smartregister.reveal.interactor.RevealFamilyProfileInteractor; import org.smartregister.reveal.model.FamilyProfileModel; -import org.smartregister.reveal.util.AlertDialogUtils; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.Country; import org.smartregister.reveal.util.FamilyConstants.DatabaseKeys; import org.smartregister.reveal.util.FamilyConstants.JSON_FORM; import org.smartregister.reveal.util.FamilyJsonFormUtils; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.tasking.util.AlertDialogUtils; +import org.smartregister.tasking.util.PreferencesUtil; +import org.smartregister.util.AppExecutors; import timber.log.Timber; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FilterTasksPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FilterTasksPresenter.java deleted file mode 100644 index 4ae8755e5b..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/FilterTasksPresenter.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.smartregister.reveal.presenter; - -import android.content.Intent; -import androidx.annotation.StringRes; -import android.view.ViewGroup; -import android.widget.ToggleButton; - -import org.apache.commons.lang3.StringUtils; -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.FilterTasksContract; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.Constants.BusinessStatus; -import org.smartregister.reveal.util.Constants.Filter; -import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.util.Constants.InterventionType; -import org.smartregister.reveal.util.Utils; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Created by samuelgithengi on 12/18/19. - */ -public class FilterTasksPresenter implements FilterTasksContract.Presenter { - - - private FilterTasksContract.View view; - - private Map labelsMap; - - private Map> checkedFilters = new HashMap<>(); - - public FilterTasksPresenter(FilterTasksContract.View view) { - this.view = view; - populateLabels(); - } - - - private void populateLabels() { - labelsMap = new HashMap<>(); - //Interventions - labelsMap.put(Intervention.IRS, R.string.irs); - labelsMap.put(Intervention.MOSQUITO_COLLECTION, R.string.mosquito_collection); - labelsMap.put(Intervention.LARVAL_DIPPING, R.string.larval_dipping); - labelsMap.put(Intervention.BCC, R.string.bcc_code); - labelsMap.put(Intervention.BEDNET_DISTRIBUTION, R.string.bednet_distribution); - labelsMap.put(Intervention.BLOOD_SCREENING, R.string.blood_screening); - labelsMap.put(Intervention.CASE_CONFIRMATION, R.string.case_confirmation); - labelsMap.put(Intervention.REGISTER_FAMILY, R.string.register_family); - labelsMap.put(Intervention.PAOT, R.string.paot); - labelsMap.put(Intervention.MDA_DISPENSE, R.string.mda_dispense); - labelsMap.put(Intervention.MDA_ADHERENCE, R.string.mda_adherence); - labelsMap.put(Intervention.IRS_VERIFICATION, R.string.irs_verification); - - //Intervention Types - labelsMap.put(InterventionType.OPERATIONAL_AREA, R.string.operational_area); - labelsMap.put(InterventionType.STRUCTURE, R.string.structure); - labelsMap.put(InterventionType.FAMILY, R.string.family); - labelsMap.put(InterventionType.PERSON, R.string.person); - - //Business status - labelsMap.put(BusinessStatus.NOT_VISITED, R.string.not_visited); - labelsMap.put(BusinessStatus.NOT_SPRAYED, R.string.not_sprayed); - labelsMap.put(BusinessStatus.NOT_SPRAYABLE, R.string.not_sprayable); - labelsMap.put(BusinessStatus.SPRAYED, R.string.sprayed); - - labelsMap.put(BusinessStatus.COMPLETE, R.string.complete); - labelsMap.put(BusinessStatus.INCOMPLETE, R.string.incomplete); - labelsMap.put(BusinessStatus.NOT_ELIGIBLE, R.string.not_eligible); - labelsMap.put(BusinessStatus.IN_PROGRESS, R.string.in_progress); - } - - - @Override - public @StringRes - Integer getStringResource(String intervention) { - return labelsMap.get(intervention); - } - - @Override - public void onToggleChanged(boolean isChecked, Object filterCategory, Object filterKey) { - if (filterCategory != null) { - Set selected = checkedFilters.get(filterCategory.toString()); - if (selected == null) { - selected = new HashSet<>(); - checkedFilters.put(filterCategory.toString(), selected); - } - if (isChecked) { - selected.add(filterKey.toString()); - } else { - selected.remove(filterKey.toString()); - if (selected.isEmpty()) { - checkedFilters.remove(filterCategory.toString()); - } - } - } - view.onFiltedSelected(checkedFilters.size()); - } - - @Override - public List getIntentionTypes() { - if (Utils.isMDA()) { - return Intervention.MDA_INTERVENTIONS; - } else if (Utils.isFocusInvestigation()) { - return Intervention.FI_INTERVENTIONS; - } else - return Intervention.IRS_INTERVENTIONS; - } - - @Override - public List getBusinessStatusOptions() { - return Utils.isFocusInvestigation() ? BusinessStatus.FI_BUSINESS_STATUS : Utils.isMDA() ? BusinessStatus.MDA_BUSINESS_STATUS : BusinessStatus.IRS_BUSINESS_STATUS; - } - - @Override - public void onApplyFilters(String selectedItem) { - Intent intent = new Intent(); - intent.putExtra(Filter.FILTER_SORT_PARAMS, new TaskFilterParams(selectedItem, checkedFilters)); - view.applyFilters(intent); - } - - @Override - public void restoreCheckedFilters(TaskFilterParams taskFilterParams) { - if (taskFilterParams != null) { - checkedFilters = taskFilterParams.getCheckedFilters(); - restoreSelections(checkedFilters.get(Constants.Filter.STATUS), view.getBusinessStatusLayout()); - restoreSelections(checkedFilters.get(Constants.Filter.CODE), view.getTaskCodeLayout()); - restoreSelections(checkedFilters.get(Filter.INTERVENTION_UNIT), view.getInterventionTypeLayout()); - if (StringUtils.isNotBlank(taskFilterParams.getSortBy())) { - int index = Arrays.asList(view.getBusinessStatusLayout().getResources().getStringArray(R.array.task_sort_options)).indexOf(taskFilterParams.getSortBy()); - view.setSortBySelection(index == -1 ? 0 : index); - } - - } - } - - private void restoreSelections(Set filters, ViewGroup viewGroup) { - if (filters == null) - return; - for (String filter : filters) { - ToggleButton toggleButton = viewGroup.findViewWithTag(filter); - toggleButton.setChecked(true); - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ListTaskPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ListTaskPresenter.java index 2bef9511f4..1d9f37c7b9 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ListTaskPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ListTaskPresenter.java @@ -5,6 +5,7 @@ import android.graphics.PointF; import android.graphics.RectF; import android.location.Location; + import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; @@ -25,29 +26,30 @@ import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseDrawerContract; import org.smartregister.reveal.contract.ListTaskContract; -import org.smartregister.reveal.contract.PasswordRequestCallback; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationCallback; import org.smartregister.reveal.interactor.ListTaskInteractor; -import org.smartregister.reveal.model.CardDetails; import org.smartregister.reveal.model.FamilyCardDetails; import org.smartregister.reveal.model.IRSVerificationCardDetails; import org.smartregister.reveal.model.MosquitoHarvestCardDetails; import org.smartregister.reveal.model.SprayCardDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.repository.RevealMappingHelper; import org.smartregister.reveal.task.IndicatorsCalculatorTask; -import org.smartregister.reveal.util.AlertDialogUtils; -import org.smartregister.reveal.util.CardDetailsUtil; import org.smartregister.reveal.util.Constants.CONFIGURATION; import org.smartregister.reveal.util.Constants.Filter; import org.smartregister.reveal.util.Constants.JsonForm; import org.smartregister.reveal.util.Country; -import org.smartregister.reveal.util.PasswordDialogUtils; -import org.smartregister.reveal.util.PreferencesUtil; import org.smartregister.reveal.util.RevealJsonFormUtils; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.tasking.contract.PasswordRequestCallback; +import org.smartregister.tasking.contract.UserLocationContract; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.model.TaskFilterParams; +import org.smartregister.tasking.presenter.ValidateUserLocationPresenter; +import org.smartregister.tasking.repository.RevealMappingHelper; +import org.smartregister.tasking.util.AlertDialogUtils; +import org.smartregister.tasking.util.CardDetailsUtil; +import org.smartregister.tasking.util.PasswordDialogUtils; +import org.smartregister.tasking.util.PreferencesUtil; import org.smartregister.util.Utils; import java.util.ArrayList; @@ -98,16 +100,16 @@ import static org.smartregister.reveal.util.Constants.Properties.TASK_STATUS; import static org.smartregister.reveal.util.Constants.REGISTER_STRUCTURE_EVENT; import static org.smartregister.reveal.util.Constants.SPRAY_EVENT; -import static org.smartregister.reveal.util.Utils.formatDate; -import static org.smartregister.reveal.util.Utils.getPropertyValue; -import static org.smartregister.reveal.util.Utils.validateFarStructures; +import static org.smartregister.tasking.util.Utils.formatDate; +import static org.smartregister.tasking.util.Utils.getPropertyValue; +import static org.smartregister.tasking.util.Utils.validateFarStructures; /** * Created by samuelgithengi on 11/27/18. */ public class ListTaskPresenter implements ListTaskContract.Presenter, PasswordRequestCallback, - UserLocationCallback { + UserLocationContract.UserLocationCallback { private ListTaskView listTaskView; @@ -317,10 +319,12 @@ private void onFeatureSelectedByNormalClick(Feature feature) { listTaskInteractor.fetchInterventionDetails(code, feature.id(), false); } else if (PAOT.equals(code)) { listTaskInteractor.fetchInterventionDetails(code, feature.id(), false); - } else if (org.smartregister.reveal.util.Utils.isFocusInvestigationOrMDA()) { + } else if (org.smartregister.tasking.util.Utils.isFocusInvestigationOrMDA()) { listTaskInteractor.fetchFamilyDetails(selectedFeature.id()); } else if (IRS_VERIFICATION.equals(code) && COMPLETE.equals(businessStatus)) { listTaskInteractor.fetchInterventionDetails(IRS_VERIFICATION, feature.id(), false); + }else{ + listTaskInteractor.fetchFamilyDetails(selectedFeature.id()); } } @@ -605,7 +609,7 @@ public Feature getSelectedFeature() { @Override public int getInterventionLabel() { - return org.smartregister.reveal.util.Utils.getInterventionLabel(); + return org.smartregister.tasking.util.Utils.getInterventionLabel(); } @Override @@ -714,7 +718,7 @@ public void filterTasks(TaskFilterParams filterParams) { filterFeatureCollection = new ArrayList<>(); Set filterStatus = filterParams.getCheckedFilters().get(Filter.STATUS); Set filterTaskCode = filterParams.getCheckedFilters().get(Filter.CODE); - Set filterInterventionUnitTasks = org.smartregister.reveal.util.Utils.getInterventionUnitCodes(filterParams.getCheckedFilters().get(Filter.INTERVENTION_UNIT)); + Set filterInterventionUnitTasks = org.smartregister.tasking.util.Utils.getInterventionUnitCodes(filterParams.getCheckedFilters().get(Filter.INTERVENTION_UNIT)); Pattern pattern = Pattern.compile("~"); for (Feature feature : featureCollection.features()) { boolean matches = true; @@ -757,8 +761,8 @@ public void searchTasks(String searchPhrase) { for (Feature feature : searchFeatureCollection != null && searchPhrase.length() > this.searchPhrase.length() ? searchFeatureCollection : Utils.isEmptyCollection(filterFeatureCollection) ? getFeatureCollection().features() : filterFeatureCollection) { String structureName = feature.getStringProperty(STRUCTURE_NAME); String familyMemberNames = feature.getStringProperty(FAMILY_MEMBER_NAMES); - if (org.smartregister.reveal.util.Utils.matchesSearchPhrase(structureName, searchPhrase) || - org.smartregister.reveal.util.Utils.matchesSearchPhrase(familyMemberNames, searchPhrase)) + if (org.smartregister.tasking.util.Utils.matchesSearchPhrase(structureName, searchPhrase) || + org.smartregister.tasking.util.Utils.matchesSearchPhrase(familyMemberNames, searchPhrase)) features.add(feature); } searchFeatureCollection = features; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/OtherFormsFragmentPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/OtherFormsFragmentPresenter.java index 36d8a1232e..8b15493792 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/OtherFormsFragmentPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/OtherFormsFragmentPresenter.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.presenter; import org.smartregister.reveal.contract.OtherFormsfragmentContract; +import org.smartregister.tasking.presenter.BaseFormFragmentPresenter; public class OtherFormsFragmentPresenter extends BaseFormFragmentPresenter { diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/RevealJsonFormFragmentPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/RevealJsonFormFragmentPresenter.java index ea74ffd4c8..bc7cc14638 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/RevealJsonFormFragmentPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/RevealJsonFormFragmentPresenter.java @@ -2,9 +2,6 @@ import android.content.Intent; import android.location.Location; -import androidx.annotation.VisibleForTesting; -import androidx.core.util.Pair; -import androidx.appcompat.app.AlertDialog; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; @@ -12,6 +9,10 @@ import android.widget.LinearLayout; import android.widget.TextView; +import androidx.annotation.VisibleForTesting; +import androidx.appcompat.app.AlertDialog; +import androidx.core.util.Pair; + import com.google.gson.Gson; import com.mapbox.mapboxsdk.geometry.LatLng; import com.rengwuxian.materialedittext.MaterialEditText; @@ -26,16 +27,17 @@ import org.smartregister.reveal.R; import org.smartregister.reveal.activity.RevealJsonFormActivity; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.PasswordRequestCallback; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationCallback; import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.LocationUtils; -import org.smartregister.reveal.util.PasswordDialogUtils; -import org.smartregister.reveal.util.RevealJsonFormUtils; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; import org.smartregister.reveal.view.RevealMapView; import org.smartregister.reveal.widget.GeoWidgetFactory; import org.smartregister.reveal.widget.RevealToasterNotesFactory; +import org.smartregister.tasking.contract.PasswordRequestCallback; +import org.smartregister.tasking.contract.UserLocationContract; +import org.smartregister.tasking.presenter.ValidateUserLocationPresenter; +import org.smartregister.tasking.util.LocationUtils; +import org.smartregister.tasking.util.PasswordDialogUtils; +import org.smartregister.tasking.util.RevealJsonFormUtils; import org.smartregister.util.JsonFormUtils; import io.ona.kujaku.listeners.BaseLocationListener; @@ -43,7 +45,7 @@ /** * Created by samuelgithengi on 1/30/19. */ -public class RevealJsonFormFragmentPresenter extends JsonFormFragmentPresenter implements PasswordRequestCallback, UserLocationCallback { +public class RevealJsonFormFragmentPresenter extends JsonFormFragmentPresenter implements PasswordRequestCallback, UserLocationContract.UserLocationCallback { private JsonFormFragment formFragment; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/StructureTasksPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/StructureTasksPresenter.java index 1a54bbb708..973b1eadd0 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/StructureTasksPresenter.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/StructureTasksPresenter.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.presenter; import android.content.Context; + import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; @@ -10,18 +11,19 @@ import org.json.JSONArray; import org.json.JSONObject; import org.smartregister.commonregistry.CommonPersonObjectClient; +import org.smartregister.domain.Event; import org.smartregister.domain.Task; import org.smartregister.domain.Task.TaskStatus; -import org.smartregister.domain.Event; import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.BaseFormFragmentContract; import org.smartregister.reveal.contract.StructureTasksContract; -import org.smartregister.reveal.interactor.BaseFormFragmentInteractor; +import org.smartregister.tasking.interactor.BaseFormFragmentInteractor; import org.smartregister.reveal.interactor.StructureTasksInteractor; import org.smartregister.reveal.model.StructureTaskDetails; import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; +import org.smartregister.tasking.contract.BaseFormFragmentContract; +import org.smartregister.tasking.presenter.BaseFormFragmentPresenter; +import org.smartregister.tasking.util.PreferencesUtil; import java.lang.ref.WeakReference; import java.util.List; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterFragmentPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterFragmentPresenter.java deleted file mode 100644 index 13a73f0bd5..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterFragmentPresenter.java +++ /dev/null @@ -1,433 +0,0 @@ -package org.smartregister.reveal.presenter; - -import androidx.annotation.NonNull; -import androidx.core.util.Pair; -import android.text.TextUtils; - -import com.google.common.annotations.VisibleForTesting; -import com.mapbox.geojson.Feature; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.configurableviews.ConfigurableViewsLibrary; -import org.smartregister.configurableviews.helper.ConfigurableViewsHelper; -import org.smartregister.configurableviews.model.View; -import org.smartregister.configurableviews.model.ViewConfiguration; -import org.smartregister.domain.Location; -import org.smartregister.domain.Task; -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.TaskRegisterFragmentContract; -import org.smartregister.reveal.interactor.TaskRegisterFragmentInteractor; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -import timber.log.Timber; - -import static org.smartregister.domain.Task.INACTIVE_TASK_STATUS; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.REGISTER_FAMILY; - -/** - * Created by samuelgithengi on 3/11/19. - */ -public class TaskRegisterFragmentPresenter extends BaseFormFragmentPresenter implements TaskRegisterFragmentContract.Presenter { - - private WeakReference view; - - private String viewConfigurationIdentifier; - - private ConfigurableViewsHelper viewsHelper; - - private Set visibleColumns; - - private TaskRegisterFragmentInteractor interactor; - - private List tasks; - private android.location.Location lastLocation; - - private boolean recalculateDistance; - - private PreferencesUtil prefsUtil; - - private boolean isActionClicked = true; - - private TaskFilterParams filterParams; - - private boolean isTasksFiltered; - - private ArrayList filteredTasks; - - private int withinBuffer; - - private boolean applyFilterOnTasksFound; - - public TaskRegisterFragmentPresenter(TaskRegisterFragmentContract.View view, String viewConfigurationIdentifier) { - this(view, viewConfigurationIdentifier, null); - this.interactor = new TaskRegisterFragmentInteractor(this); - } - - @VisibleForTesting - protected TaskRegisterFragmentPresenter(TaskRegisterFragmentContract.View view, String viewConfigurationIdentifier, - TaskRegisterFragmentInteractor interactor) { - super(view, view.getContext()); - this.view = new WeakReference<>(view); - this.viewConfigurationIdentifier = viewConfigurationIdentifier; - this.interactor = interactor; - viewsHelper = ConfigurableViewsLibrary.getInstance().getConfigurableViewsHelper(); - prefsUtil = PreferencesUtil.getInstance(); - - - } - - - @Override - public void processViewConfigurations() { - if (!StringUtils.isBlank(this.viewConfigurationIdentifier)) { - ViewConfiguration viewConfiguration = viewsHelper.getViewConfiguration(this.viewConfigurationIdentifier); - if (viewConfiguration != null) { - visibleColumns = viewsHelper.getRegisterActiveColumns(this.viewConfigurationIdentifier); - } - } - } - - @Override - public void initializeQueries(String mainCondition) { - - if (getView().getAdapter() == null) { - getView().initializeAdapter(visibleColumns); - } - lastLocation = getView().getLocationUtils().getLastLocation(); - if (lastLocation == null) {//if location client has not initialized use last location passed from map - lastLocation = getView().getLastLocation(); - } - - if (!isTasksFiltered) { - getView().showProgressView(); - interactor.findTasks(getMainCondition(), lastLocation, getOperationalAreaCenter(), getView().getContext().getString(R.string.house)); - } - - } - - private android.location.Location getOperationalAreaCenter() { - Location operationalAreaLocation = Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()); - if (operationalAreaLocation == null) - return null; - return mappingHelper.getCenter(gson.toJson(operationalAreaLocation.getGeometry())); - } - - @Override - public void startSync() { - Utils.startImmediateSync(); - } - - @Override - public void searchGlobally(String uniqueId) {//do nothing, tasks not searchable globally - } - - /** - * Gets the where clause for the task register, filters by operational area and campaign - * - * @return pair of filter clause and values for filter - */ - private Pair getMainCondition() { - Location operationalArea = Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()); - String whereClause = String.format("%s.%s = ? AND %s.%s = ? AND %s.%s NOT IN (%s)", - Constants.DatabaseKeys.TASK_TABLE, Constants.DatabaseKeys.GROUPID, Constants.DatabaseKeys.TASK_TABLE, Constants.DatabaseKeys.PLAN_ID, - Constants.DatabaseKeys.TASK_TABLE, Constants.DatabaseKeys.STATUS, - TextUtils.join(",", Collections.nCopies(INACTIVE_TASK_STATUS.length, "?"))); - return new Pair<>(whereClause, ArrayUtils.addAll(new String[]{operationalArea == null ? - null : operationalArea.getId(), prefsUtil.getCurrentPlanId()}, INACTIVE_TASK_STATUS)); - } - - @Override - protected TaskRegisterFragmentContract.View getView() { - return view.get(); - } - - @Override - public void onTasksFound(List tasks, int structuresWithinBuffer) { - if (recalculateDistance) {//there was a location update when tasks were being retrieved recalculate distance and order - interactor.calculateDistanceFromUser(tasks, lastLocation); - recalculateDistance = false; - } else { - this.tasks = tasks; - if (tasks == null) { - getView().displayNotification(R.string.fetching_structure_title, - R.string.fetch_location_and_structures_failed, prefsUtil.getCurrentOperationalArea()); - getView().setTaskDetails(new ArrayList<>()); - } else if (tasks.isEmpty()) { - getView().displayNotification(R.string.fetching_structure_title, R.string.no_structures_found); - getView().setTaskDetails(tasks); - } else if (applyFilterOnTasksFound) { - filterTasks(filterParams); - getView().setSearchPhrase(filterParams.getSearchPhrase()); - applyFilterOnTasksFound = false; - } else { - getView().setTaskDetails(tasks); - } - getView().setTotalTasks(structuresWithinBuffer); - getView().hideProgressDialog(); - getView().hideProgressView(); - } - - } - - - @Override - public void onLocationChanged(android.location.Location location) { - if (!location.equals(lastLocation)) { - if (lastLocation == null && tasks == null) {//tasks not yet retrieved from db - recalculateDistance = true; - } else if (lastLocation == null || - location.distanceTo(lastLocation) >= Constants.REFRESH_MAP_MINIMUM_DISTANCE) { - interactor.calculateDistanceFromUser(tasks, location); - } - lastLocation = location; - } - - } - - @Override - public void onDestroy() { - getView().getLocationUtils().stopLocationClient(); - } - - @Override - public void onDrawerClosed() { - getView().showProgressDialog(R.string.fetching_structures_title, R.string.fetching_structures_message); - interactor.findTasks(getMainCondition(), lastLocation, getOperationalAreaCenter(), getView().getContext().getString(R.string.house)); - getView().setInventionType(getInterventionLabel()); - } - - @Override - public void onTaskSelected(TaskDetails details, boolean isActionClicked) { - this.isActionClicked = isActionClicked; - if (details != null) { - setTaskDetails(details); - if (CASE_CONFIRMATION.equals(details.getTaskCode())) { - interactor.getIndexCaseDetails(details.getStructureId(), - Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId(), details.getReasonReference()); - } else if (Task.TaskStatus.COMPLETED.name().equals(details.getTaskStatus()) - && - (BLOOD_SCREENING.equals(details.getTaskCode()) || - BEDNET_DISTRIBUTION.equals(details.getTaskCode()) || - REGISTER_FAMILY.equals(details.getTaskCode())) || - (details.getTaskCount() != null && details.getTaskCount() > 1)) { // structures with grouped tasks should display the family profile - setTaskDetails(details); - interactor.fetchFamilyDetails(details.getStructureId()); - } else { - getView().showProgressDialog(R.string.opening_form_title, R.string.opening_form_message); - interactor.getStructure(details); - } - } - } - - @Override - public int getInterventionLabel() { - return Utils.getInterventionLabel(); - } - - /** - * Called by interactor when the index event has been queried. If Event is not found an errror is displayed. - * If task confirmation is not competed and event was linked to a household and button was selected, then family profile is opened, - * otherwise the index case details are displayed - * - * @param indexCase the index case details event JSON - * @param isLinkedToJurisdiction if index case was linked to FI, false if linked to structure - */ - @Override - public void onIndexCaseFound(JSONObject indexCase, boolean isLinkedToJurisdiction) { - if (indexCase == null) { - getView().displayError(R.string.classification_details, R.string.index_case_not_found); - } else { - if (isActionClicked && !isLinkedToJurisdiction - && getTaskDetails().getTaskStatus().equals(Task.TaskStatus.READY.name())) { - interactor.fetchFamilyDetails(getTaskDetails().getStructureId()); - } else { - getView().displayIndexCaseDetails(indexCase); - } - } - } - - @Override - public void searchTasks(String searchText) { - Timber.d("searching task matching %s", searchText); - if (StringUtils.isBlank(searchText)) { - setTasks(getActiveTasks(), this.withinBuffer); - } else { - List filteredTasks = new ArrayList<>(); - int withinBuffer = 0; - for (TaskDetails task : getActiveTasks()) { - if (Utils.matchesSearchPhrase(task.getFamilyName(), searchText) || - Utils.matchesSearchPhrase(task.getStructureName(), searchText) || - Utils.matchesSearchPhrase(task.getHouseNumber(), searchText) || - Utils.matchesSearchPhrase(task.getFamilyMemberNames(), searchText)) { - filteredTasks.add(task); - if (task.getDistanceFromUser() > 0 && task.getDistanceFromUser() <= Utils.getLocationBuffer()) - withinBuffer++; - } - } - setTasks(filteredTasks, withinBuffer); - } - } - - private void setTasks(List filteredTasks, int withinBuffer) { - getView().setTaskDetails(filteredTasks); - getView().setTotalTasks(withinBuffer); - } - - @Override - public void filterTasks(TaskFilterParams filterParams) { - this.filterParams = filterParams; - if (filterParams.getCheckedFilters() == null || filterParams.getCheckedFilters().isEmpty()) { - applyEmptyFilter(); - return; - } - filteredTasks = new ArrayList<>(); - Set filterStatus = filterParams.getCheckedFilters().get(Constants.Filter.STATUS); - Set filterTaskCode = filterParams.getCheckedFilters().get(Constants.Filter.CODE); - Set filterInterventionUnitTasks = Utils.getInterventionUnitCodes(filterParams.getCheckedFilters().get(Constants.Filter.INTERVENTION_UNIT)); - getView().setNumberOfFilters(filterParams.getCheckedFilters().size()); - Pattern pattern = Pattern.compile("~"); - withinBuffer = 0; - for (TaskDetails taskDetails : tasks) { - if (matchesTask(taskDetails, pattern, filterStatus, filterTaskCode, filterInterventionUnitTasks)) { - filteredTasks.add(taskDetails); - if (taskDetails.getDistanceFromUser() > 0 && taskDetails.getDistanceFromUser() <= Utils.getLocationBuffer()) - withinBuffer++; - } - } - if (StringUtils.isNotBlank(filterParams.getSortBy())) { - sortTasks(filteredTasks, filterParams.getSortBy()); - } - setTasks(filteredTasks, withinBuffer); - getView().setSearchPhrase(""); - getView().hideProgressDialog(); - getView().hideProgressView(); - isTasksFiltered = true; - } - - private void applyEmptyFilter() { - isTasksFiltered = false; - getView().clearFilter(); - filteredTasks = null; - if (StringUtils.isNotBlank(filterParams.getSortBy())) { - sortTasks(tasks, filterParams.getSortBy()); - getView().setTaskDetails(tasks); - } - } - - private boolean matchesTask(TaskDetails taskDetails, Pattern pattern, Set filterStatus, Set filterTaskCode, Set filterInterventionUnitTasks) { - boolean matches = true; - if (filterStatus != null) { - matches = StringUtils.isBlank(taskDetails.getAggregateBusinessStatus()) ? filterStatus.contains(taskDetails.getBusinessStatus()) : filterStatus.contains(taskDetails.getAggregateBusinessStatus()); - } - if (matches && filterTaskCode != null) { - matches = matchesTaskCodeFilterList(taskDetails.getTaskCode(), filterTaskCode, pattern); - } - if (matches && filterInterventionUnitTasks != null) { - matches = matchesTaskCodeFilterList(taskDetails.getTaskCode(), filterInterventionUnitTasks, pattern); - } - return matches; - } - - private void sortTasks(List filteredTasks, String sortBy) { - int sortType = Arrays.asList(getView().getContext().getResources().getStringArray(R.array.task_sort_options)).indexOf(sortBy); - if (sortType == 0) {// sort by distance default sort - Collections.sort(filteredTasks); - } else if (sortType == 1) {// sort by business status - Collections.sort(filteredTasks, (task, task2) -> { - String status = StringUtils.isBlank(task.getAggregateBusinessStatus()) ? task.getBusinessStatus() : task.getAggregateBusinessStatus(); - String status2 = StringUtils.isBlank(task2.getAggregateBusinessStatus()) ? task2.getBusinessStatus() : task2.getAggregateBusinessStatus(); - return status.compareTo(status2); - }); - } else if (sortType == 2) {// sort by task type - Collections.sort(filteredTasks, (task, task2) -> task.getTaskCode().compareTo(task2.getTaskCode())); - } - } - - @Override - public void onFilterTasksClicked() { - getView().openFilterActivity(filterParams); - } - - @Override - public void setTaskFilterParams(TaskFilterParams filterParams) { - this.filterParams = filterParams; - applyFilterOnTasksFound = true; - } - - @Override - public void onOpenMapClicked() { - getView().startMapActivity(filterParams); - } - - @Override - public void resetTaskInfo(TaskDetails taskDetails) { - interactor.resetTaskInfo(getView().getContext(), taskDetails); - } - - @Override - public void onTaskInfoReset() { - // refresh task list - getView().showProgressView(); - interactor.findTasks(getMainCondition(), lastLocation, getOperationalAreaCenter(), getView().getContext().getString(R.string.house)); - } - - private boolean matchesTaskCodeFilterList(String value, Set filterList, Pattern pattern) { - String[] array = pattern.split(value); - return CollectionUtils.containsAny(Arrays.asList(array), filterList); - } - - @Override - public void onLocationValidated() { - if (Constants.Intervention.REGISTER_FAMILY.equals(getTaskDetails().getTaskCode())) { - getView().registerFamily(getTaskDetails()); - } - super.onLocationValidated(); - } - - @Override - public void onFormSaved(@NonNull String structureId, String taskID, @NonNull Task.TaskStatus taskStatus, @NonNull String businessStatus, String interventionType) { - getView().hideProgressDialog(); - } - - @Override - public void onStructureAdded(Feature feature, JSONArray featureCoordinates, double zoomlevel) { - //not used - } - - @Override - public void onFormSaveFailure(String eventType) { - getView().hideProgressDialog(); - } - - @Override - public void onFamilyFound(CommonPersonObjectClient family) { - if (family == null) - getView().displayNotification(R.string.fetch_family_failed, R.string.failed_to_find_family); - else - getView().openFamilyProfile(family, getTaskDetails()); - } - - private List getActiveTasks() { - return isTasksFiltered && filteredTasks != null ? filteredTasks : tasks; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterPresenter.java deleted file mode 100644 index 0684374c67..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/TaskRegisterPresenter.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.smartregister.reveal.presenter; - -import androidx.annotation.NonNull; - -import com.mapbox.geojson.Feature; - -import org.json.JSONArray; -import org.smartregister.commonregistry.CommonPersonObjectClient; -import org.smartregister.domain.Task; -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.TaskRegisterContract; -import org.smartregister.reveal.interactor.TaskRegisterInteractor; -import org.smartregister.view.contract.BaseRegisterContract; - -import java.util.List; - -/** - * Created by samuelgithengi on 3/11/19. - */ -public class TaskRegisterPresenter implements TaskRegisterContract.Presenter, BaseRegisterContract.Presenter { - - private TaskRegisterInteractor taskRegisterInteractor; - - private BaseRegisterContract.View view; - - public TaskRegisterPresenter(BaseRegisterContract.View view) { - this.view = view; - taskRegisterInteractor = new TaskRegisterInteractor(this); - } - - @Override - public void registerViewConfigurations(List viewIdentifiers) { - taskRegisterInteractor.registerViewConfigurations(viewIdentifiers); - } - - @Override - public void unregisterViewConfiguration(List viewIdentifiers) { - taskRegisterInteractor.unregisterViewConfiguration(viewIdentifiers); - } - - @Override - public void onDestroy(boolean isChangingConfiguration) { - taskRegisterInteractor.cleanupResources(); - } - - @Override - public void updateInitials() {//do nothing - } - - @Override - public void saveJsonForm(String json) { - view.showProgressDialog(R.string.saving_dialog_title); - taskRegisterInteractor.saveJsonForm(json); - } - - @Override - public void onFamilyFound(CommonPersonObjectClient finalFamily) {//not used - } - - @Override - public void onFormSaved(@NonNull String structureId, String taskID, @NonNull Task.TaskStatus taskStatus, @NonNull String businessStatus, String interventionType) { - view.hideProgressDialog();//register will refresh on resume - } - - @Override - public void onStructureAdded(Feature feature, JSONArray featureCoordinates, double zoomlevel) { - view.hideProgressDialog();//register will refresh on resume - } - - @Override - public void onFormSaveFailure(String eventType) { - view.hideProgressDialog();//register will refresh on resume - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ValidateUserLocationPresenter.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ValidateUserLocationPresenter.java deleted file mode 100644 index d9192959ee..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/presenter/ValidateUserLocationPresenter.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.smartregister.reveal.presenter; - -import android.location.Location; -import android.os.SystemClock; - -import com.mapbox.mapboxsdk.geometry.LatLng; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.UserLocationContract; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationCallback; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationView; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.Utils; - -import java.util.Timer; -import java.util.TimerTask; - -import timber.log.Timber; - -/** - * Created by samuelgithengi on 2/13/19. - */ -public class ValidateUserLocationPresenter implements UserLocationContract.UserLocationPresenter { - - private UserLocationView locationView; - - private UserLocationCallback callback; - - private long resolutionStarted; - - private AppExecutors appExecutors; - - protected ValidateUserLocationPresenter(UserLocationView locationView, UserLocationCallback callback) { - this.locationView = locationView; - this.callback = callback; - appExecutors = RevealApplication.getInstance().getAppExecutors(); - } - - @Override - public void requestUserLocation() { - locationView.requestUserLocation(); - } - - @Override - public void onGetUserLocation(Location location) { - locationView.hideProgressDialog(); - double offset = callback.getTargetCoordinates().distanceTo( - new LatLng(location.getLatitude(), location.getLongitude())); - if (offset > Utils.getLocationBuffer()) { - callback.requestUserPassword(); - } else { - callback.onLocationValidated(); - } - } - - @Override - public void onGetUserLocationFailed() { - locationView.hideProgressDialog(); - callback.requestUserPassword(); - } - - @Override - public void waitForUserLocation() { - resolutionStarted = SystemClock.elapsedRealtime(); - waitForUserLocation(0); - } - - - private void waitForUserLocation(long elapsedTimeInMillis) { - Location location = locationView.getUserCurrentLocation(); - Timber.d("user location: " + location); - if (location == null) { - if (elapsedTimeInMillis / 1000 >= Utils.getResolveLocationTimeoutInSeconds()) { - appExecutors.mainThread().execute(() -> onGetUserLocationFailed()); - } else { - if (elapsedTimeInMillis == 0) {//first try running in main thread ; show progress dialog. - locationView.showProgressDialog(R.string.narrowing_location_title, R.string.narrowing_location_message); - } - new Timer().schedule(new TimerTask() { - @Override - public void run() { - waitForUserLocation(SystemClock.elapsedRealtime() - resolutionStarted); - } - }, 2000); - } - } else { - appExecutors.mainThread().execute(() -> onGetUserLocation(location)); - - } - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealMappingHelper.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealMappingHelper.java deleted file mode 100644 index 898e7822f3..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealMappingHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.smartregister.reveal.repository; - -import android.location.Location; -import androidx.annotation.NonNull; - -import com.mapbox.geojson.Feature; -import com.mapbox.geojson.Geometry; -import com.mapbox.geojson.gson.GeometryGeoJson; -import com.mapbox.turf.TurfMeasurement; - -import org.smartregister.repository.helper.MappingHelper; - -/** - * Created by samuelgithengi on 3/19/19. - */ -public class RevealMappingHelper implements MappingHelper { - /** - * Generates the center from the {@link Geometry} of a given {@link Feature} for {@link Geometry} - * of types {@link com.mapbox.geojson.MultiPolygon}, {@link com.mapbox.geojson.Polygon} and - * {@link com.mapbox.geojson.MultiPoint} - * - * @param geometry the geometry of structure - * @return center - */ - @Override - public Location getCenter(@NonNull String geometry) { - double[] bbox = TurfMeasurement.bbox(GeometryGeoJson.fromJson(geometry)); - Location center = new Location((String) null); - center.setLongitude((bbox[2] + bbox[0]) / 2); - center.setLatitude((bbox[3] + bbox[1]) / 2); - return center; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealRepository.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealRepository.java index a8e4de0ef4..3c7bfed99f 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealRepository.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/repository/RevealRepository.java @@ -27,7 +27,7 @@ import org.smartregister.reveal.util.Constants.DatabaseKeys; import org.smartregister.reveal.util.Country; import org.smartregister.reveal.util.FamilyConstants.EventType; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; import org.smartregister.util.DatabaseMigrationUtils; import org.smartregister.util.RecreateECUtil; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/server/FileHTTPServer.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/server/FileHTTPServer.java deleted file mode 100644 index 268b901e90..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/server/FileHTTPServer.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.smartregister.reveal.server; - -import android.content.Context; - -import org.apache.commons.lang3.StringUtils; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.util.Utils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Locale; - -import timber.log.Timber; - -/** - * A minimal HTTP server that serves a mapbox style json file - */ -public class FileHTTPServer { - public static final int PORT = 9783; - - private static final String DEFAULT_STYLE_JSON_FILE = "map-download-style.json"; - private static final String DEFAULT_DG_ID_PLACEHOLDER = "DIGITAL_GLOBE_ID"; - private String styleJson; - - private final FileHTTPServer.ServerThread server; - private final ServerSocket socket; - - public FileHTTPServer(Context context, String styleJsonFile, String digitalGlobeIdPlaceHolder) throws IOException { - socket = createBoundSocket(PORT); - String dgIdPlaceHolder; - if (socket == null) { - throw new IOException("Could not find an available port"); - } - server = new ServerThread(socket); - - dgIdPlaceHolder = StringUtils.isNotBlank(digitalGlobeIdPlaceHolder) ? digitalGlobeIdPlaceHolder : DEFAULT_DG_ID_PLACEHOLDER; - styleJson = StringUtils.isNotBlank(styleJsonFile) ? styleJsonFile : DEFAULT_STYLE_JSON_FILE; - - styleJson = Utils.readAssetContents(context, styleJsonFile); - styleJson = styleJson.replace(dgIdPlaceHolder, BuildConfig.DG_CONNECT_ID); - } - - public void start() { - server.start(); - } - - public boolean isStarted() { - return server.isAlive(); - } - - /** - * Permanently closes all sockets. - */ - public void destroy() { - try { - socket.close(); - } catch (IOException e) { - Timber.w(e); - } - server.interrupt(); - } - - /** - * Binds a ServerSocket to given port. - */ - protected static ServerSocket createBoundSocket(int port) throws IOException { - try { - return new ServerSocket(port); - } catch (IOException e) { - e.printStackTrace(); - } - Timber.e("Port %d not available", port); - return null; - } - - class ServerThread extends Thread { - private final ServerSocket socket; - - ServerThread(ServerSocket socket) { - this.socket = socket; - } - - public void run() { - try { - socket.setReuseAddress(true); - Timber.i("Ready for requests on port %d", socket.getLocalPort()); - while (!isInterrupted()) { - Socket connection = socket.accept(); - Timber.i("Accepted a client connection"); - new ResponseThread(connection).start(); - } - Timber.i("Server thread interrupted"); - } catch (IOException e) { - Timber.i("Server thread stopped: %s", e.getMessage()); - } - } - } - - class ResponseThread extends Thread { - private final Socket connection; - - ResponseThread(Socket connection) { - this.connection = connection; - } - - public void run() { - try (Socket connection = this.connection) { - InputStreamReader reader = new InputStreamReader(connection.getInputStream()); - String request = new BufferedReader(reader).readLine(); - Timber.i("Received request: %s", request); - if (request == null) { - return; - } - long start = System.currentTimeMillis(); - FileHTTPServer.Response response = getResponse(request); - if (response == null) { - Timber.i("%s: Style file not found", request); - return; - } - sendResponse(connection, response); - long finish = System.currentTimeMillis(); - Timber.i("%s: Served %d bytes in %d ms", request, response.data.length, finish - start); - } catch (IOException e) { - Timber.e(e, "Unable to read request from socket"); - } - } - - protected FileHTTPServer.Response getResponse(String request) { - if (request.startsWith("GET /")) { - return new FileHTTPServer.Response(styleJson.getBytes(), "text/plain"); - } else { - Timber.w("Ignoring request: %s", request); - return null; - } - - } - - protected void sendResponse(Socket connection, FileHTTPServer.Response response) { - String headers = String.format( - Locale.US, - "HTTP/1.0 200\r\n" + - "Content-Type: %s\r\n" + - "Content-Length: %d\r\n" + - "\r\n", - response.contentType, - response.data.length - ); - - try (OutputStream output = connection.getOutputStream()) { - output.write(headers.getBytes()); - output.write(response.data); - output.flush(); - } catch (IOException e) { - Timber.e(e, "Unable to write response to socket"); - } - } - } - - public static class Response { - private byte[] data; - private String contentType; - - public Response(byte[] data, String contentType) { - this.data = data; - this.contentType = contentType; - } - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/LocationTaskIntentService.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/LocationTaskIntentService.java deleted file mode 100644 index 4c8ec9351e..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/LocationTaskIntentService.java +++ /dev/null @@ -1,196 +0,0 @@ -package org.smartregister.reveal.sync; - -import android.app.IntentService; -import android.content.Intent; -import androidx.annotation.Nullable; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import org.smartregister.domain.FetchStatus; -import org.smartregister.domain.Location; -import org.smartregister.domain.Task; -import org.smartregister.domain.db.EventClient; -import org.smartregister.job.SyncServiceJob; -import org.smartregister.receiver.SyncStatusBroadcastReceiver; -import org.smartregister.repository.BaseRepository; -import org.smartregister.repository.EventClientRepository; -import org.smartregister.repository.TaskRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.job.RevealSyncSettingsServiceJob; -import org.smartregister.reveal.util.AppExecutors; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; -import org.smartregister.sync.helper.LocationServiceHelper; -import org.smartregister.sync.helper.PlanIntentServiceHelper; -import org.smartregister.sync.helper.TaskServiceHelper; -import org.smartregister.util.NetworkUtils; -import org.smartregister.util.SyncUtils; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.smartregister.reveal.util.Constants.Action.STRUCTURE_TASK_SYNCED; -import static org.smartregister.reveal.util.FamilyConstants.TABLE_NAME.FAMILY_MEMBER; - -public class LocationTaskIntentService extends IntentService { - - private static final String TAG = "LocationTaskIntentService"; - - private SyncUtils syncUtils; - - public LocationTaskIntentService() { - super(TAG); - } - - @Override - protected void onHandleIntent(@Nullable Intent intent) { - if (!NetworkUtils.isNetworkAvailable()) { - sendSyncStatusBroadcastMessage(FetchStatus.noConnection); - return; - } - if (!syncUtils.verifyAuthorization()) { - syncUtils.logoutUser(); - return; - - } - sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); - - doSync(); - - (new AppExecutors()).mainThread().execute(new Runnable() { - @Override - public void run() { - RevealSyncSettingsServiceJob.scheduleJobImmediately(RevealSyncSettingsServiceJob.TAG); - } - }); - } - - private void sendSyncStatusBroadcastMessage(FetchStatus fetchStatus) { - Intent intent = new Intent(); - intent.setAction(SyncStatusBroadcastReceiver.ACTION_SYNC_STATUS); - intent.putExtra(SyncStatusBroadcastReceiver.EXTRA_FETCH_STATUS, fetchStatus); - sendBroadcast(intent); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - syncUtils = new SyncUtils(getBaseContext()); - return super.onStartCommand(intent, flags, startId); - } - - - private void doSync() { - sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); - LocationServiceHelper locationServiceHelper = new LocationServiceHelper( - RevealApplication.getInstance().getLocationRepository(), - RevealApplication.getInstance().getLocationTagRepository(), - RevealApplication.getInstance().getStructureRepository()); - TaskServiceHelper taskServiceHelper = TaskServiceHelper.getInstance(); - PlanIntentServiceHelper planServiceHelper = PlanIntentServiceHelper.getInstance(); - - - List syncedStructures = locationServiceHelper.fetchLocationsStructures(); - - sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); - planServiceHelper.syncPlans(); - - sendSyncStatusBroadcastMessage(FetchStatus.fetchStarted); - List synchedTasks = taskServiceHelper.syncTasks(); - - TaskRepository taskRepository = RevealApplication.getInstance().getContext().getTaskRepository(); - taskRepository.updateTaskStructureIdFromStructure(syncedStructures); - taskRepository.updateTaskStructureIdsFromExistingStructures(); - taskRepository.updateTaskStructureIdsFromExistingClients(FAMILY_MEMBER); - - if (hasChangesInCurrentOperationalArea(syncedStructures, synchedTasks)) { - Intent intent = new Intent(STRUCTURE_TASK_SYNCED); - LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent); - } - - clientProcessEvents(extractStructureIds(syncedStructures, synchedTasks)); - - if (!org.smartregister.util.Utils.isEmptyCollection(syncedStructures) - || !org.smartregister.util.Utils.isEmptyCollection(synchedTasks)) { - doSync(); - } - - new AppExecutors().mainThread().execute(new Runnable() { - @Override - public void run() { - SyncServiceJob.scheduleJobImmediately(SyncServiceJob.TAG); - } - }); - - } - - /** - * Checks if there a synched structure or task on the currently opened operational area - * - * @param syncedStructures the list of synced structures - * @param synchedTasks the list of synced tasks - * @return true if there is a synched structure or task on the currently opened operational area; otherwise returns false - */ - private boolean hasChangesInCurrentOperationalArea(List syncedStructures, List synchedTasks) { - Location operationalAreaLocation = Utils.getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()); - String operationalAreaLocationId; - if (operationalAreaLocation == null) { - return false; - } else { - operationalAreaLocationId = operationalAreaLocation.getId(); - } - if (syncedStructures != null) { - for (Location structure : syncedStructures) { - if (operationalAreaLocationId.equals(structure.getProperties().getParentId())) { - return true; - } - } - } - if (synchedTasks != null) { - for (Task task : synchedTasks) { - if (operationalAreaLocationId.equals(task.getGroupIdentifier())) { - return true; - } - } - } - return false; - } - - /** - * Extracts a set of Structures ids from syched structures and tasks - * - * @param syncedStructures the list of synced structures - * @param synchedTasks the list of synced tasks - * @return a set of baseEntityIds - */ - private Set extractStructureIds(List syncedStructures, List synchedTasks) { - Set structureIds = new HashSet<>(); - if (!org.smartregister.util.Utils.isEmptyCollection(syncedStructures)) { - for (Location structure : syncedStructures) { - structureIds.add(structure.getId()); - } - } - if (!org.smartregister.util.Utils.isEmptyCollection(synchedTasks)) { - for (Task task : synchedTasks) { - structureIds.add(task.getForEntity()); - } - } - return structureIds; - } - - /** - * Clients Processes events of a set of structure baseEntityIds that have the task status TYPE_Task_Unprocessed - * - * @param syncedStructuresIds the set of structure baseEntityIds to client process - */ - private void clientProcessEvents(Set syncedStructuresIds) { - if (org.smartregister.util.Utils.isEmptyCollection(syncedStructuresIds)) - return; - EventClientRepository ecRepository = RevealApplication.getInstance().getContext().getEventClientRepository(); - List eventClients = ecRepository.getEventsByBaseEntityIdsAndSyncStatus(BaseRepository.TYPE_Task_Unprocessed, new ArrayList<>(syncedStructuresIds)); - if (!eventClients.isEmpty()) { - RevealClientProcessor.getInstance(getApplicationContext()).processClient(eventClients); - } - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealClientProcessor.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealClientProcessor.java index 8cc6bfa166..1ef1c1f50b 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealClientProcessor.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealClientProcessor.java @@ -2,18 +2,19 @@ import android.content.Context; import android.content.Intent; + import androidx.annotation.NonNull; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; +import org.smartregister.domain.Client; +import org.smartregister.domain.Event; import org.smartregister.domain.Location; import org.smartregister.domain.LocationProperty.PropertyStatus; +import org.smartregister.domain.Obs; import org.smartregister.domain.Task; -import org.smartregister.domain.Client; -import org.smartregister.domain.Event; import org.smartregister.domain.db.EventClient; -import org.smartregister.domain.Obs; import org.smartregister.domain.jsonmapping.ClientClassification; import org.smartregister.repository.BaseRepository; import org.smartregister.repository.EventClientRepository; @@ -25,9 +26,9 @@ import org.smartregister.reveal.util.Constants.JsonForm; import org.smartregister.reveal.util.Constants.StructureType; import org.smartregister.reveal.util.FamilyConstants.EventType; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.Utils; import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.tasking.util.PreferencesUtil; import java.util.ArrayList; import java.util.List; @@ -86,6 +87,7 @@ public synchronized void processClient(List eventClientList) { processClient(eventClientList, false); } + @Override public void processClient(List eventClients, boolean localEvents) { ClientClassification clientClassification = assetJsonToJava("ec_client_classification.json", ClientClassification.class); if (clientClassification == null) { @@ -140,6 +142,10 @@ public void processClient(List eventClients, boolean localEvents) { operationalAreaLocationId.equals(operationalAreaId)) { hasSyncedEventsInTarget = true; } + + if (localEvents) { + processPlanEvaluation(eventClient); + } } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealSettingsSyncIntentService.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealSettingsSyncIntentService.java deleted file mode 100644 index 97d4698ba8..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/sync/RevealSettingsSyncIntentService.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.smartregister.reveal.sync; - -import android.content.Intent; -import android.os.Bundle; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import org.smartregister.AllConstants; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.sync.intent.SettingsSyncIntentService; - -import static org.smartregister.reveal.util.Constants.Action.STRUCTURE_TASK_SYNCED; -import static org.smartregister.reveal.util.Constants.CONFIGURATION.UPDATE_LOCATION_BUFFER_RADIUS; - -/** - * @author Vincent Karuri - */ -public class RevealSettingsSyncIntentService extends SettingsSyncIntentService { - @Override - protected void onHandleIntent(Intent intent) { - super.onHandleIntent(intent); - Bundle data = intent.getExtras(); - if (data != null && data.getInt(AllConstants.INTENT_KEY.SYNC_TOTAL_RECORDS, 0) > 0) { - RevealApplication.getInstance().processServerConfigs(); - // broadcast sync event - Intent refreshGeoWidgetIntent = new Intent(STRUCTURE_TASK_SYNCED); - refreshGeoWidgetIntent.putExtra(UPDATE_LOCATION_BUFFER_RADIUS, true); - LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(refreshGeoWidgetIntent); - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/task/FileHttpServerTask.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/task/FileHttpServerTask.java deleted file mode 100644 index 3f31c61d29..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/task/FileHttpServerTask.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.smartregister.reveal.task; - -import android.content.Context; -import android.os.AsyncTask; - -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.OfflineMapHelper; - -/** - * Created by Richard Kareko on 2/4/20. - */ - -public class FileHttpServerTask extends AsyncTask { - private Context context; - - public FileHttpServerTask(Context context) { - this.context = context; - } - - @Override - protected Void doInBackground(Void... params) { - OfflineMapHelper.initializeFileHTTPServer(context, Constants.DG_ID_PLACEHOLDER); - return null; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/task/IndicatorsCalculatorTask.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/task/IndicatorsCalculatorTask.java index 39449085fc..482ded6fdd 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/task/IndicatorsCalculatorTask.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/task/IndicatorsCalculatorTask.java @@ -8,9 +8,9 @@ import org.smartregister.reporting.view.TableView; import org.smartregister.reveal.R; import org.smartregister.reveal.model.IndicatorDetails; -import org.smartregister.reveal.model.TaskDetails; import org.smartregister.reveal.util.IndicatorUtils; import org.smartregister.reveal.view.ListTasksActivity; +import org.smartregister.tasking.model.TaskDetails; import java.util.Arrays; import java.util.List; @@ -81,7 +81,7 @@ protected void onPostExecute(IndicatorDetails indicatorDetails) { //Show or hide depending on plan - ((View) progressIndicator.getParent()).setVisibility(org.smartregister.reveal.util.Utils.getInterventionLabel() == R.string.irs ? View.VISIBLE : View.GONE); + ((View) progressIndicator.getParent()).setVisibility(org.smartregister.tasking.util.Utils.getInterventionLabel() == R.string.irs ? View.VISIBLE : View.GONE); if (activity instanceof ListTasksActivity) ((ListTasksActivity) activity).positionMyLocationAndLayerSwitcher(); diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AlertDialogUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AlertDialogUtils.java deleted file mode 100644 index 93f671caa4..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AlertDialogUtils.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.smartregister.reveal.util; - -import android.content.Context; -import android.content.DialogInterface; -import androidx.appcompat.app.AlertDialog; - -import org.smartregister.reveal.R; - -/** - * Created by samuelgithengi on 3/22/19. - */ -public class AlertDialogUtils { - - - public static AlertDialog displayNotification(Context context, int title, int message, Object... formatArgs) { - if (formatArgs.length == 0) - return new AlertDialog.Builder(context).setMessage(message).setTitle(title).setPositiveButton(R.string.ok, null).show(); - else - return new AlertDialog.Builder(context).setMessage(context.getString(message, formatArgs)).setTitle(title).setPositiveButton(R.string.ok, null).show(); - } - - - public static AlertDialog displayNotification(Context context, String message) { - return new AlertDialog.Builder(context).setMessage(message).setTitle(R.string.fetch_structures_title).setPositiveButton(R.string.ok, null).show(); - } - - public static AlertDialog displayNotificationWithCallback(Context context, int title, int message, int positiveBtnTitle, int negativeBtnTitle, DialogInterface.OnClickListener onClickListener, Object... formatArgs) { - AlertDialog alert; - - if (formatArgs.length == 0) - alert = new AlertDialog.Builder(context).setMessage(message).setTitle(title).setPositiveButton(positiveBtnTitle, onClickListener).setNegativeButton(negativeBtnTitle, onClickListener).show(); - else - alert = new AlertDialog.Builder(context).setMessage(context.getString(message, formatArgs)).setTitle(title).setPositiveButton(positiveBtnTitle, onClickListener).setNegativeButton(negativeBtnTitle, onClickListener).show(); - - return alert; - } - - - public static AlertDialog displayNotificationWithCallback(Context context, int title, int message, int positiveBtnTitle, int negativeBtnTitle, Integer neutralBtnTitle, DialogInterface.OnClickListener onClickListener, Object... formatArgs) { - AlertDialog alert; - - if (formatArgs.length == 0) - alert = new AlertDialog.Builder(context).setMessage(message).setTitle(title).setPositiveButton(positiveBtnTitle, onClickListener).setNegativeButton(negativeBtnTitle, onClickListener).setNeutralButton(neutralBtnTitle, onClickListener).show(); - else - alert = new AlertDialog.Builder(context).setMessage(context.getString(message, formatArgs)).setTitle(title).setPositiveButton(positiveBtnTitle, onClickListener).setNegativeButton(negativeBtnTitle, onClickListener).setNeutralButton(neutralBtnTitle, onClickListener).show(); - - return alert; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AppExecutors.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AppExecutors.java deleted file mode 100644 index 0b83ac9069..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/AppExecutors.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.smartregister.reveal.util; - -import android.os.Handler; -import android.os.Looper; -import androidx.annotation.NonNull; - -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; - -/** - * Created by samuelgithengi on 11/29/18. - *

- * Global executor pools for the whole application. - *

- * Grouping tasks like this avoids the effects of task starvation (e.g. disk reads don't wait behind - * webservice requests). - */ -public class AppExecutors { - - private static final int THREAD_COUNT = 3; - - private final Executor diskIO; - - private final Executor networkIO; - - private final Executor mainThread; - - public AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) { - this.diskIO = diskIO; - this.networkIO = networkIO; - this.mainThread = mainThread; - } - - public AppExecutors() { - this(new DiskIOThreadExecutor(), Executors.newFixedThreadPool(THREAD_COUNT), - new MainThreadExecutor()); - } - - public Executor diskIO() { - return diskIO; - } - - public Executor networkIO() { - return networkIO; - } - - public Executor mainThread() { - return mainThread; - } - - private static class MainThreadExecutor implements Executor { - private Handler mainThreadHandler = new Handler(Looper.getMainLooper()); - - @Override - public void execute(@NonNull Runnable command) { - mainThreadHandler.post(command); - } - } - - /** - * Executor that runs a task on a new background thread. - */ - private static class DiskIOThreadExecutor implements Executor { - - private final Executor mDiskIO; - - public DiskIOThreadExecutor() { - mDiskIO = Executors.newSingleThreadExecutor(); - } - - @Override - public void execute(@NonNull Runnable command) { - mDiskIO.execute(command); - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/CardDetailsUtil.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/CardDetailsUtil.java index 6f1cf6471a..324352c6b2 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/CardDetailsUtil.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/CardDetailsUtil.java @@ -1,7 +1,6 @@ package org.smartregister.reveal.util; import android.app.Activity; -import android.content.Context; import android.content.res.Resources; import android.text.TextUtils; import android.view.View; @@ -11,25 +10,13 @@ import org.smartregister.AllConstants; import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.model.CardDetails; import org.smartregister.reveal.model.FamilyCardDetails; import org.smartregister.reveal.model.IRSVerificationCardDetails; import org.smartregister.reveal.model.MosquitoHarvestCardDetails; import org.smartregister.reveal.model.SprayCardDetails; -import org.smartregister.reveal.util.Constants.BusinessStatus; import timber.log.Timber; -import static org.smartregister.reveal.util.Constants.BusinessStatus.COMPLETE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.INCOMPLETE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.IN_PROGRESS; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_ELIGIBLE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_SPRAYABLE; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_SPRAYED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_VISITED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.PARTIALLY_SPRAYED; -import static org.smartregister.reveal.util.Constants.BusinessStatus.SPRAYED; import static org.smartregister.reveal.util.Constants.Intervention.LARVAL_DIPPING; import static org.smartregister.reveal.util.Constants.Intervention.MOSQUITO_COLLECTION; import static org.smartregister.reveal.util.Constants.Intervention.PAOT; @@ -37,43 +24,7 @@ /** * Created by samuelgithengi on 3/22/19. */ -public class CardDetailsUtil { - - public static void formatCardDetails(CardDetails cardDetails) { - if (cardDetails == null || cardDetails.getStatus() == null) - return; - // extract status color - String status = cardDetails.getStatus(); - switch (status) { - case BusinessStatus.NOT_SPRAYED: - case BusinessStatus.INCOMPLETE: - case BusinessStatus.IN_PROGRESS: - case BusinessStatus.NONE_RECEIVED: - cardDetails.setStatusColor(R.color.unsprayed); - cardDetails.setStatusMessage(R.string.details_not_sprayed); - break; - case BusinessStatus.SPRAYED: - case BusinessStatus.COMPLETE: - case BusinessStatus.FULLY_RECEIVED: - cardDetails.setStatusColor(R.color.sprayed); - cardDetails.setStatusMessage(R.string.details_sprayed); - cardDetails.setReason(null); - break; - case BusinessStatus.NOT_SPRAYABLE: - case BusinessStatus.NOT_ELIGIBLE: - cardDetails.setStatusColor(R.color.unsprayable); - cardDetails.setStatusMessage(R.string.details_not_sprayable); - cardDetails.setReason(null); - break; - case PARTIALLY_SPRAYED: - cardDetails.setStatusColor(R.color.partially_sprayed); - cardDetails.setStatusMessage(R.string.partially_sprayed); - break; - default: - Timber.w("business status not defined :" + cardDetails.getStatus()); - break; - } - } +public class CardDetailsUtil extends org.smartregister.tasking.util.CardDetailsUtil { public void populateSprayCardTextViews(SprayCardDetails sprayCardDetails, Activity activity) { try { @@ -212,68 +163,5 @@ public void populateFamilyCard(FamilyCardDetails familyCardDetails, Activity act } } - /** - * Takes in a business status and returns the translated value according to locale set. - * - * @param businessStatus Business status of the task attached to a structure - * @return status Translated status according to locale set - */ - public static String getTranslatedBusinessStatus(String businessStatus) { - Context context = RevealApplication.getInstance().getApplicationContext(); - - if (businessStatus == null) - return context.getString(R.string.not_eligible); - switch (businessStatus) { - case NOT_VISITED: - return context.getString(R.string.not_visited); - case NOT_SPRAYED: - return context.getString(R.string.not_sprayed); - case SPRAYED: - return context.getString(R.string.sprayed); - case NOT_SPRAYABLE: - return context.getString(R.string.not_sprayable); - case COMPLETE: - return context.getString(R.string.complete); - case INCOMPLETE: - return context.getString(R.string.incomplete); - case NOT_ELIGIBLE: - return context.getString(R.string.not_eligible); - case IN_PROGRESS: - return context.getString(R.string.in_progress); - case PARTIALLY_SPRAYED: - return context.getString(R.string.partially_sprayed); - default: - return businessStatus; - } - - } - - /** - * Takes in a IRS intervention status and returns the translated value . - * - * @param status Status of the IRS Verification type - * @return status Translated status - */ - public static String getTranslatedIRSVerificationStatus(String status) { - Context context = RevealApplication.getInstance().getApplicationContext(); - - if (status == null) - return context.getString(R.string.not_sprayed); - switch (status) { - case Constants.IRSVerificationStatus.SPRAYED: - return context.getString(R.string.sprayed); - case Constants.IRSVerificationStatus.NOT_SPRAYED: - return context.getString(R.string.not_sprayed); - case Constants.IRSVerificationStatus.NOT_FOUND_OR_VISITED: - return context.getString(R.string.structure_not_found_or_visited_during_campaign); - case Constants.IRSVerificationStatus.OTHER: - return context.getString(R.string.other); - default: - return status; - } - - - } - } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/FamilyJsonFormUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/FamilyJsonFormUtils.java index 0cc6e3ed17..b48fd090c4 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/FamilyJsonFormUtils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/FamilyJsonFormUtils.java @@ -284,7 +284,7 @@ public static Event createFamilyEvent(String baseEntityId, String locationId, Ma (Event) new Event().withBaseEntityId(baseEntityId).withEventDate(new Date()).withEventType(eventType) .withLocationId(locationId).withEntityType(familyMetadata.familyMemberRegister.tableName) .withFormSubmissionId(UUID.randomUUID().toString()).withDateCreated(new Date()); - org.smartregister.reveal.util.Utils.tagEventMetadata(updateMemberNameEvent, org.smartregister.reveal.util.Utils.getFormTag()); + org.smartregister.tasking.util.Utils.tagEventMetadata(updateMemberNameEvent, org.smartregister.tasking.util.Utils.getFormTag()); updateMemberNameEvent.setDetails(details); return updateMemberNameEvent; } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/GeoJsonUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/GeoJsonUtils.java index e668f0699b..66de9b7600 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/GeoJsonUtils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/GeoJsonUtils.java @@ -5,6 +5,7 @@ import org.smartregister.domain.Location; import org.smartregister.domain.Task; import org.smartregister.reveal.model.StructureDetails; +import org.smartregister.tasking.util.Utils; import java.util.HashMap; import java.util.List; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/IndicatorUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/IndicatorUtils.java index 69670c355a..176912386a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/IndicatorUtils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/IndicatorUtils.java @@ -5,7 +5,7 @@ import org.smartregister.domain.Task; import org.smartregister.reveal.R; import org.smartregister.reveal.model.IndicatorDetails; -import org.smartregister.reveal.model.TaskDetails; +import org.smartregister.tasking.model.TaskDetails; import java.util.ArrayList; import java.util.HashMap; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/InteractorUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/InteractorUtils.java deleted file mode 100644 index 1d4161db41..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/InteractorUtils.java +++ /dev/null @@ -1,222 +0,0 @@ -package org.smartregister.reveal.util; - -import android.database.Cursor; - -import net.sqlcipher.database.SQLiteDatabase; - -import org.joda.time.DateTime; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.smartregister.clientandeventmodel.Event; -import org.smartregister.clientandeventmodel.Obs; -import org.smartregister.commonregistry.CommonPersonObject; -import org.smartregister.commonregistry.CommonRepository; -import org.smartregister.domain.Client; -import org.smartregister.domain.db.EventClient; -import org.smartregister.repository.BaseRepository; -import org.smartregister.repository.EventClientRepository; -import org.smartregister.repository.TaskRepository; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.FamilyConstants.EventType; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import timber.log.Timber; - -import static org.smartregister.reveal.util.Constants.BEHAVIOUR_CHANGE_COMMUNICATION; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.BASE_ENTITY_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.CASE_CONFIRMATION_FIELD; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.EVENT_TASK_TABLE; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.EVENT_TYPE_FIELD; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.FORM_SUBMISSION_ID; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.SPRAYED_STRUCTURES; -import static org.smartregister.reveal.util.Constants.DatabaseKeys.TASK_ID; -import static org.smartregister.reveal.util.Constants.Intervention.BCC; -import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.IRS; -import static org.smartregister.util.JsonFormUtils.gson; - -public class InteractorUtils { - - private TaskRepository taskRepository; - - private EventClientRepository eventClientRepository; - - private RevealClientProcessor clientProcessor; - - private RevealJsonFormUtils jsonFormUtils; - - public InteractorUtils(TaskRepository taskRepository, EventClientRepository eventClientRepository, RevealClientProcessor clientProcessor) { - this.taskRepository = taskRepository; - this.eventClientRepository = eventClientRepository; - this.clientProcessor = clientProcessor; - jsonFormUtils = new RevealJsonFormUtils(); - } - - - public InteractorUtils() { - } - - public CommonPersonObject fetchSprayDetails(String interventionType, String structureId, EventClientRepository eventClientRepository, CommonRepository commonRepository) { - CommonPersonObject commonPersonObject = null; - if (IRS.equals(interventionType)) { - Cursor cursor = null; - try { - cursor = eventClientRepository.getWritableDatabase().rawQuery( - String.format("select s.*, id as _id from %s s where %s = ?", SPRAYED_STRUCTURES, Constants.DatabaseKeys.BASE_ENTITY_ID), new String[]{structureId}); - if (cursor.moveToFirst()) { - commonPersonObject = commonRepository.getCommonPersonObjectFromCursor(cursor); - } - } catch (Exception e) { - Timber.e(e); - } finally { - if (cursor != null) { - cursor.close(); - } - } - } - return commonPersonObject; - } - - - public boolean archiveClient(String baseEntityId, boolean isFamily) { - taskRepository.cancelTasksForEntity(baseEntityId); - taskRepository.archiveTasksForEntity(baseEntityId); - JSONObject eventsByBaseEntityId = eventClientRepository.getEventsByBaseEntityId(baseEntityId); - JSONArray events = eventsByBaseEntityId.optJSONArray("events"); - JSONObject clientJsonObject = eventsByBaseEntityId.optJSONObject("client"); - DateTime now = new DateTime(); - if (events != null) { - for (int i = 0; i < events.length(); i++) { - try { - JSONObject event = events.getJSONObject(i); - event.put("dateVoided", now); - event.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); - } catch (JSONException e) { - Timber.e(e); - } - } - } - - boolean saved; - try { - eventClientRepository.batchInsertEvents(events, 0); - clientJsonObject.put("dateVoided", now); - clientJsonObject.put(EventClientRepository.client_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); - clientJsonObject.getJSONObject("attributes").put("dateRemoved", now); - eventClientRepository.addorUpdateClient(baseEntityId, clientJsonObject); - RevealApplication.getInstance().setSynced(false); - Event archiveEvent = FamilyJsonFormUtils.createFamilyEvent(baseEntityId, Utils.getCurrentLocationId(), - null, isFamily ? EventType.ARCHIVE_FAMILY : EventType.ARCHIVE_FAMILY_MEMBER); - archiveEvent.addObs(new Obs().withValue(now).withFieldCode("dateArchived").withFieldType("formsubmissionField")); - - JSONObject eventJson = new JSONObject(gson.toJson(archiveEvent)); - eventJson.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); - eventClientRepository.addEvent(baseEntityId, eventJson); - - clientProcessor.processClient(Collections.singletonList(new EventClient( - gson.fromJson(eventJson.toString(), org.smartregister.domain.Event.class), - gson.fromJson(clientJsonObject.toString(), Client.class))), true); - saved = true; - - } catch (JSONException e) { - Timber.e(e); - saved = false; - } - return saved; - } - - public boolean archiveEventsForTask(SQLiteDatabase db, BaseTaskDetails taskDetails) { - boolean archived = true; - - if (taskDetails == null) { - return false; - } - List formSubmissionIds = getFormSubmissionIdsFromEventTask(db, taskDetails); - List eventClients = eventClientRepository.fetchEventClients(formSubmissionIds); - DateTime now = new DateTime(); - JSONArray taskEvents = new JSONArray(); - - try { - - JSONArray eventClientJsonArray = new JSONArray(gson.toJson(eventClients)); - - for (int i = 0; i < eventClientJsonArray.length(); i++) { - JSONObject eventJson = eventClientJsonArray.getJSONObject(i).getJSONObject("event"); - eventJson.put("dateVoided", now); - eventJson.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); - taskEvents.put(eventJson); - } - eventClientRepository.batchInsertEvents(taskEvents, 0); - - - Event resetTaskEvent = RevealJsonFormUtils.createTaskEvent(taskDetails.getTaskEntity(), Utils.getCurrentLocationId(), - null, Constants.TASK_RESET_EVENT, Constants.STRUCTURE); - JSONObject eventJson = new JSONObject(gson.toJson(resetTaskEvent)); - eventJson.put(EventClientRepository.event_column.syncStatus.name(), BaseRepository.TYPE_Unsynced); - - eventJson = jsonFormUtils.populateFormDetails(eventJson.toString(), taskDetails.getTaskEntity(), taskDetails.getStructureId(), taskDetails.getTaskId(), taskDetails.getBusinessStatus(), taskDetails.getTaskStatus(), null, null); - eventClientRepository.addEvent(taskDetails.getTaskEntity(), eventJson); - - - } catch (Exception e) { - Timber.e(e); - archived = false; - } - - return archived; - } - - public List getFormSubmissionIdsFromEventTask(SQLiteDatabase db, BaseTaskDetails taskDetails) { - List formSubmissionIds = new ArrayList<>(); - Cursor cursor = null; - String query; - - try { - - if (CASE_CONFIRMATION.equals(taskDetails.getTaskCode()) || BCC.equals(taskDetails.getTaskCode())) { - String eventTypeField= null; - - if (CASE_CONFIRMATION.equals(taskDetails.getTaskCode())) { - eventTypeField = CASE_CONFIRMATION_FIELD; - } else if(BCC.equals(taskDetails.getTaskCode())) { - eventTypeField = BEHAVIOUR_CHANGE_COMMUNICATION; - } - - query = String.format("select %s from event where baseEntityId = ? and %s = ?", - FORM_SUBMISSION_ID, EVENT_TYPE_FIELD); - cursor = db.rawQuery(query, new String[]{taskDetails.getTaskEntity(), eventTypeField}); - - while (cursor.moveToNext()) { - formSubmissionIds.add(cursor.getString(cursor.getColumnIndex(FORM_SUBMISSION_ID))); - } - - } else { - query = String.format("select %s from %s where %s = ?", - BASE_ENTITY_ID, EVENT_TASK_TABLE, TASK_ID); - cursor = db.rawQuery(query, new String[]{taskDetails.getTaskId()}); - - while (cursor.moveToNext()) { - formSubmissionIds.add(cursor.getString(cursor.getColumnIndex(BASE_ENTITY_ID))); - } - } - - } finally { - if (cursor != null) { - cursor.close(); - } - } - - return formSubmissionIds; - } - - public boolean resetTaskInfo(SQLiteDatabase db, BaseTaskDetails taskDetails) { - return archiveEventsForTask(db, taskDetails) && TaskUtils.getInstance().resetTask(taskDetails); - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/LocationUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/LocationUtils.java deleted file mode 100644 index d54c40b114..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/LocationUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.smartregister.reveal.util; - -import android.app.Activity; -import android.content.Context; -import android.content.IntentSender; -import android.location.Location; - -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.api.Status; -import com.google.android.gms.location.LocationSettingsResult; -import com.google.android.gms.location.LocationSettingsStatusCodes; - -import io.ona.kujaku.interfaces.ILocationClient; -import io.ona.kujaku.listeners.BaseLocationListener; -import io.ona.kujaku.location.clients.GoogleLocationClient; -import io.ona.kujaku.utils.Constants; -import io.ona.kujaku.utils.LocationSettingsHelper; -import timber.log.Timber; - -/** - * Created by samuelgithengi on 3/20/19. - */ -public class LocationUtils { - - private ILocationClient locationClient; - - public LocationUtils(Context context) { - locationClient = new GoogleLocationClient(context); - } - - public LocationUtils(ILocationClient locationClient) { - this.locationClient = locationClient; - } - - public void requestLocationUpdates(BaseLocationListener locationListener) { - locationClient.requestLocationUpdates(locationListener); - } - - public Location getLastLocation() { - return locationClient.getLastLocation(); - } - - /** - * Stop the location client and unregister from receiving updates - */ - public void stopLocationClient() { - if (locationClient != null) { - locationClient.close(); - } - } - - - public void checkLocationSettingsAndStartLocationServices(Context context, BaseLocationListener locationListener) { - if (context instanceof Activity) { - Activity activity = (Activity) context; - - LocationSettingsHelper.checkLocationEnabled(activity, new ResultCallback() { - @Override - public void onResult(LocationSettingsResult result) { - final Status status = result.getStatus(); - - switch (status.getStatusCode()) { - case LocationSettingsStatusCodes.SUCCESS: - Timber.i("All location settings are satisfied."); - requestLocationUpdates(locationListener); - break; - case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: - Timber.i("Location settings are not satisfied. Show the user a dialog to upgrade location settings"); - - try { - status.startResolutionForResult(activity, Constants.RequestCode.LOCATION_SETTINGS); - } catch (IntentSender.SendIntentException e) { - Timber.i("PendingIntent unable to execute request."); - } - break; - case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: - Timber.e("Location settings are inadequate, and cannot be fixed here. Dialog cannot be created."); - break; - - default: - Timber.e("Unknown status code returned after checking location settings"); - break; - } - } - }); - } else { - Timber.e("KujakuMapView is not started in an Activity and can therefore not start location services"); - } - } - - /** - * Clear location client - */ - public void destroy() { - stopLocationClient(); - locationClient = null; - } - - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/OfflineMapHelper.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/OfflineMapHelper.java deleted file mode 100644 index 8c0e79a601..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/OfflineMapHelper.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.smartregister.reveal.util; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.core.util.Pair; - -import com.mapbox.geojson.Feature; -import com.mapbox.mapboxsdk.geometry.LatLng; -import com.mapbox.mapboxsdk.offline.OfflineRegion; -import com.mapbox.turf.TurfMeasurement; - -import org.json.JSONException; -import org.json.JSONObject; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.server.FileHTTPServer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.ona.kujaku.data.realm.RealmDatabase; -import io.ona.kujaku.data.realm.objects.MapBoxOfflineQueueTask; -import io.ona.kujaku.downloaders.MapBoxOfflineResourcesDownloader; -import io.ona.kujaku.helpers.OfflineServiceHelper; -import timber.log.Timber; - -import static io.ona.kujaku.data.MapBoxDownloadTask.MAP_NAME; -import static org.smartregister.reveal.util.Constants.Map.DOWNLOAD_MAX_ZOOM; -import static org.smartregister.reveal.util.Constants.Map.DOWNLOAD_MIN_ZOOM; - -/** - * Created by Richard Kareko on 1/30/20. - */ - -public class OfflineMapHelper { - - @NonNull - public static Pair, Map> getOfflineRegionInfo (final OfflineRegion[] offlineRegions) { - List offlineRegionNames = new ArrayList<>(); - Map modelMap = new HashMap<>(); - - for(int position = 0; position < offlineRegions.length; position++) { - - byte[] metadataBytes = offlineRegions[position].getMetadata(); - try { - JSONObject jsonObject = new JSONObject(new String(metadataBytes)); - if (jsonObject.has(MapBoxOfflineResourcesDownloader.METADATA_JSON_FIELD_REGION_NAME)) { - String regionName = jsonObject.getString(MapBoxOfflineResourcesDownloader.METADATA_JSON_FIELD_REGION_NAME); - offlineRegionNames.add(regionName); - modelMap.put(regionName, offlineRegions[position]); - } - - } catch (JSONException e) { - Timber.e(e); - } - - } - - return new Pair(offlineRegionNames, modelMap); - } - - public static Map populateOfflineQueueTaskMap(RealmDatabase realmDatabase) { - Map offlineQueueTaskMap = new HashMap<>(); - - List offlineQueueTasks = realmDatabase.getTasks(); - - if (offlineQueueTasks == null){ - return offlineQueueTaskMap; - } - - for (MapBoxOfflineQueueTask offlineQueueTask: offlineQueueTasks) { - - try { - if (MapBoxOfflineQueueTask.TASK_TYPE_DOWNLOAD.equals(offlineQueueTask.getTaskType()) - && MapBoxOfflineQueueTask.TASK_STATUS_DONE == offlineQueueTask.getTaskStatus()) { - offlineQueueTaskMap.put(offlineQueueTask.getTask().get(MAP_NAME).toString(), offlineQueueTask); - } - } catch (JSONException e) { - e.printStackTrace(); - } - } - - return offlineQueueTaskMap; - } - - public static void downloadMap(final Feature operationalAreaFeature, final String mapName, final Context context) { - Runnable runnable = new Runnable() { - public void run() { - double[] bbox = TurfMeasurement.bbox(operationalAreaFeature.geometry()); - - double minX = bbox[0]; - double minY = bbox[1]; - double maxX = bbox[2]; - double maxY = bbox[3]; - - double topLeftLat = maxY; - double topLeftLng = minX; - double bottomRightLat = minY; - double bottomRightLng = maxX; - double topRightLat = maxY; - double topRightLng = maxX; - double bottomLeftLat = minY; - double bottomLeftLng = minX; - - String mapboxStyle = context.getString(R.string.localhost_url, FileHTTPServer.PORT); - - LatLng topLeftBound = new LatLng(topLeftLat, topLeftLng); - LatLng topRightBound = new LatLng(topRightLat, topRightLng); - LatLng bottomRightBound = new LatLng(bottomRightLat, bottomRightLng); - LatLng bottomLeftBound = new LatLng(bottomLeftLat, bottomLeftLng); - - double maxZoom = DOWNLOAD_MAX_ZOOM; - double minZoom = DOWNLOAD_MIN_ZOOM; - - OfflineServiceHelper.ZoomRange zoomRange = new OfflineServiceHelper.ZoomRange(minZoom, maxZoom); - - OfflineServiceHelper.requestOfflineMapDownload(context - , mapName - , mapboxStyle - , BuildConfig.MAPBOX_SDK_ACCESS_TOKEN - , topLeftBound - , topRightBound - , bottomRightBound - , bottomLeftBound - , zoomRange - ); - } - }; - - RevealApplication.getInstance().getAppExecutors().diskIO().execute(runnable); - } - - public static void initializeFileHTTPServer(Context context, String digitalGlobeIdPlaceholder) { - try { - FileHTTPServer httpServer = new FileHTTPServer(context, context.getString(R.string.reveal_offline_map_download_style), digitalGlobeIdPlaceholder); - httpServer.start(); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PasswordDialogUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PasswordDialogUtils.java deleted file mode 100644 index 5b7f6fdead..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PasswordDialogUtils.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.smartregister.reveal.util; - -import android.content.Context; -import android.content.DialogInterface; -import androidx.appcompat.app.AlertDialog; -import android.text.method.HideReturnsTransformationMethod; -import android.text.method.PasswordTransformationMethod; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.EditText; -import android.widget.Toast; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.PasswordRequestCallback; - -/** - * Created by samuelgithengi on 2/6/19. - */ -public class PasswordDialogUtils { - - public static AlertDialog initPasswordDialog(Context context, PasswordRequestCallback callback) { - if (context == null) { - return null; - } - LayoutInflater inflater = LayoutInflater.from(context); - View dialogView = inflater.inflate(R.layout.dialog_request_password, null); - - AlertDialog passwordDialog = new AlertDialog.Builder(context) - .setTitle(R.string.request_password_title) - .setView(dialogView) - .setNegativeButton(R.string.cancel, null) - .setPositiveButton(R.string.ok, null) - .setCancelable(false) - .create(); - - final EditText adminPassEditText = dialogView.findViewById(R.id.admin_pass); - ((CheckBox) dialogView.findViewById(R.id.show_password_checkbox)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) - adminPassEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); - else - adminPassEditText.setTransformationMethod(PasswordTransformationMethod.getInstance()); - } - }); - - passwordDialog.setOnShowListener(new DialogInterface.OnShowListener() { - @Override - public void onShow(DialogInterface dialogInterface) { - - passwordDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!adminPassEditText.getText().toString().equals(Utils.getAdminPasswordNotNearStructures())) { - Toast.makeText(context, R.string.wrong_admin_password, Toast.LENGTH_LONG).show(); - adminPassEditText.setError(context.getString(R.string.wrong_admin_password)); - } else { - adminPassEditText.setError(null); - adminPassEditText.setText(null); - passwordDialog.dismiss(); - callback.onPasswordVerified(); - } - } - }); - - passwordDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - adminPassEditText.setText(null); - adminPassEditText.setError(null); - passwordDialog.dismiss(); - } - }); - } - }); - return passwordDialog; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PreferencesUtil.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PreferencesUtil.java deleted file mode 100644 index cc665c597f..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/PreferencesUtil.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.smartregister.reveal.util; - -import org.apache.commons.lang3.StringUtils; -import org.smartregister.repository.AllSharedPreferences; -import org.smartregister.reveal.application.RevealApplication; - -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_DISTRICT; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_FACILITY; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_OPERATIONAL_AREA; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_OPERATIONAL_AREA_ID; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_PLAN; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_PLAN_ID; -import static org.smartregister.reveal.util.Constants.Preferences.CURRENT_PROVINCE; -import static org.smartregister.reveal.util.Constants.Preferences.FACILITY_LEVEL; - -/** - * Created by samuelgithengi on 11/29/18. - */ -public class PreferencesUtil { - - private AllSharedPreferences allSharedPreferences; - - private static PreferencesUtil instance; - - private PreferencesUtil(AllSharedPreferences allSharedPreferences) { - this.allSharedPreferences = allSharedPreferences; - } - - - public static PreferencesUtil getInstance() { - if (instance == null) { - instance = new PreferencesUtil(RevealApplication.getInstance().getContext().allSharedPreferences()); - } - return instance; - } - - public void setCurrentFacility(String facility) { - allSharedPreferences.savePreference(CURRENT_FACILITY, facility); - } - - public String getCurrentFacility() { - return allSharedPreferences.getPreference(CURRENT_FACILITY); - } - - public void setCurrentOperationalArea(String operationalArea) { - allSharedPreferences.savePreference(CURRENT_OPERATIONAL_AREA, operationalArea); - if (StringUtils.isNotBlank(operationalArea)) { - allSharedPreferences.savePreference(CURRENT_OPERATIONAL_AREA_ID, Utils.getCurrentLocationId()); - } - } - - public String getCurrentOperationalArea() { - return allSharedPreferences.getPreference(CURRENT_OPERATIONAL_AREA); - } - - public String getCurrentOperationalAreaId() { - return allSharedPreferences.getPreference(CURRENT_OPERATIONAL_AREA_ID); - } - - public void setCurrentDistrict(String district) { - allSharedPreferences.savePreference(CURRENT_DISTRICT, district); - } - - public String getCurrentDistrict() { - return allSharedPreferences.getPreference(CURRENT_DISTRICT); - } - - public void setCurrentProvince(String province) { - allSharedPreferences.savePreference(CURRENT_PROVINCE, province); - } - - public String getCurrentProvince() { - return allSharedPreferences.getPreference(CURRENT_PROVINCE); - } - - public void setCurrentPlan(String campaign) { - allSharedPreferences.savePreference(CURRENT_PLAN, campaign); - } - - public String getCurrentPlan() { - return allSharedPreferences.getPreference(CURRENT_PLAN); - } - - public void setCurrentPlanId(String campaignId) { - allSharedPreferences.savePreference(CURRENT_PLAN_ID, campaignId); - } - - public String getCurrentPlanId() { - return allSharedPreferences.getPreference(CURRENT_PLAN_ID); - } - - public String getPreferenceValue(String key) { - return allSharedPreferences.getPreference(key); - } - - public void setCurrentFacilityLevel(String facilityLevel) { - allSharedPreferences.savePreference(FACILITY_LEVEL, facilityLevel); - } - - - public String getCurrentFacilityLevel() { - return allSharedPreferences.getPreference(FACILITY_LEVEL); - } - - public void setInterventionTypeForPlan(String planId, String interventionType) { - allSharedPreferences.savePreference(planId, interventionType); - } - - public String getInterventionTypeForPlan(String planId) { - return allSharedPreferences.getPreference(planId); - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealJsonFormUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealJsonFormUtils.java index 3ee7d10841..2b4df36b7a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealJsonFormUtils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealJsonFormUtils.java @@ -1,233 +1,51 @@ package org.smartregister.reveal.util; import android.app.Activity; -import android.content.Context; import android.content.Intent; -import androidx.core.util.Pair; - -import com.mapbox.geojson.Feature; -import com.vijay.jsonwizard.constants.JsonFormConstants; -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.commonregistry.CommonPersonObject; -import org.smartregister.domain.Event; -import org.smartregister.domain.Location; -import org.smartregister.domain.Obs; import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.activity.RevealJsonFormActivity; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.model.MosquitoHarvestCardDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.util.Constants.CONFIGURATION; import org.smartregister.reveal.util.Constants.Intervention; import org.smartregister.reveal.util.Constants.JsonForm; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.util.JsonFormUtils; - -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import timber.log.Timber; - -import static com.vijay.jsonwizard.constants.JsonFormConstants.CHECK_BOX; -import static com.vijay.jsonwizard.constants.JsonFormConstants.KEY; -import static com.vijay.jsonwizard.constants.JsonFormConstants.KEYS; -import static com.vijay.jsonwizard.constants.JsonFormConstants.TYPE; -import static com.vijay.jsonwizard.constants.JsonFormConstants.VALUE; -import static com.vijay.jsonwizard.constants.JsonFormConstants.VALUES; -import static org.smartregister.AllConstants.JSON_FILE_EXTENSION; -import static org.smartregister.AllConstants.OPTIONS; -import static org.smartregister.AllConstants.TEXT; +import static org.smartregister.reveal.util.Constants.JSON_FORM_PARAM_JSON; +import static org.smartregister.reveal.util.Constants.SPRAY_EVENT; +import static org.smartregister.reveal.util.Constants.MOSQUITO_COLLECTION_EVENT; import static org.smartregister.reveal.util.Constants.BEDNET_DISTRIBUTION_EVENT; -import static org.smartregister.reveal.util.Constants.BEHAVIOUR_CHANGE_COMMUNICATION; import static org.smartregister.reveal.util.Constants.BLOOD_SCREENING_EVENT; -import static org.smartregister.reveal.util.Constants.DETAILS; -import static org.smartregister.reveal.util.Constants.ENTITY_ID; -import static org.smartregister.reveal.util.Constants.EventType.CASE_CONFIRMATION_EVENT; -import static org.smartregister.reveal.util.Constants.EventType.IRS_VERIFICATION; -import static org.smartregister.reveal.util.Constants.JSON_FORM_PARAM_JSON; -import static org.smartregister.reveal.util.Constants.JsonForm.JSON_FORM_FOLDER; import static org.smartregister.reveal.util.Constants.LARVAL_DIPPING_EVENT; -import static org.smartregister.reveal.util.Constants.MOSQUITO_COLLECTION_EVENT; import static org.smartregister.reveal.util.Constants.REGISTER_STRUCTURE_EVENT; -import static org.smartregister.reveal.util.Constants.RequestCode.REQUEST_CODE_GET_JSON; -import static org.smartregister.reveal.util.Constants.SPRAY_EVENT; -import static org.smartregister.reveal.util.Utils.getPropertyValue; +import static org.smartregister.reveal.util.Constants.Intervention.IRS_VERIFICATION; +import static org.smartregister.reveal.util.Constants.BEHAVIOUR_CHANGE_COMMUNICATION; +import static org.smartregister.reveal.util.Constants.EventType.CASE_CONFIRMATION_EVENT; +import org.smartregister.reveal.model.MosquitoHarvestCardDetails; +import timber.log.Timber; + +import static com.vijay.jsonwizard.constants.JsonFormConstants.VALUE; /** - * Created by samuelgithengi on 3/22/19. + * Created by Ephraim Kigamba - nek.eam@gmail.com on 04-08-2020. */ -public class RevealJsonFormUtils { - - private Set nonEditablefields; - - public RevealJsonFormUtils() { - nonEditablefields = new HashSet<>(Arrays.asList(JsonForm.HOUSEHOLD_ACCESSIBLE, - JsonForm.ABLE_TO_SPRAY_FIRST, JsonForm.MOP_UP_VISIT)); - } - - public JSONObject getFormJSON(Context context, String formName, Feature feature, String sprayStatus, String familyHead) { - - String taskBusinessStatus = getPropertyValue(feature, Properties.TASK_BUSINESS_STATUS); - String taskIdentifier = getPropertyValue(feature, Properties.TASK_IDENTIFIER); - String taskStatus = getPropertyValue(feature, Properties.TASK_STATUS); +public class RevealJsonFormUtils extends org.smartregister.tasking.util.RevealJsonFormUtils { - String structureId = feature.id(); - String structureUUID = getPropertyValue(feature, Properties.LOCATION_UUID); - String structureVersion = getPropertyValue(feature, Properties.LOCATION_VERSION); - String structureType = getPropertyValue(feature, Properties.LOCATION_TYPE); - String formString = getFormString(context, formName, structureType); - try { - JSONObject formJson = populateFormDetails(formString, structureId, structureId, taskIdentifier, - taskBusinessStatus, taskStatus, structureUUID, - structureVersion == null ? null : Integer.valueOf(structureVersion)); - - populateFormFields(formJson, structureType, sprayStatus, familyHead); - return formJson; - } catch (Exception e) { - Timber.e(e, "error launching form" + formName); - } - return null; - } - - public JSONObject getFormJSON(Context context, String formName, BaseTaskDetails task, Location structure) { - - String taskBusinessStatus = ""; - String taskIdentifier = ""; - String taskStatus = ""; - String entityId = ""; - if (task != null) { - taskBusinessStatus = task.getBusinessStatus(); - taskIdentifier = task.getTaskId(); - taskStatus = task.getTaskStatus(); - - entityId = task.getTaskEntity(); - } - - String structureId = ""; - String structureUUID = ""; - int structureVersion = 0; - String structureType = ""; - if (structure != null) { - structureId = structure.getId(); - structureUUID = structure.getProperties().getUid(); - structureVersion = structure.getProperties().getVersion(); - structureType = structure.getProperties().getType(); - } - - String sprayStatus = null; - String familyHead = null; - - if (task instanceof TaskDetails) { - sprayStatus = ((TaskDetails) task).getSprayStatus(); - familyHead = ((TaskDetails) task).getFamilyName(); - } - - String formString = getFormString(context, formName, structureType); + public void populatePAOTForm(MosquitoHarvestCardDetails cardDetails, JSONObject formJson) { + if (formJson == null) + return; try { - JSONObject formJson = populateFormDetails(formString, entityId, structureId, taskIdentifier, - taskBusinessStatus, taskStatus, structureUUID, structureVersion); - populateFormFields(formJson, structureType, sprayStatus, familyHead); - return formJson; + populateField(formJson, Constants.JsonForm.PAOT_STATUS, cardDetails.getStatus(), Constants.CONFIGURATION.VALUE); + populateField(formJson, Constants.JsonForm.PAOT_COMMENTS, cardDetails.getComments(), VALUE); + populateField(formJson, Constants.JsonForm.LAST_UPDATED_DATE, cardDetails.getStartDate(), VALUE); } catch (JSONException e) { - Timber.e(e, "error launching form" + formName); - } - return null; - } - - public String getFormString(Context context, String formName, String structureType) { - String formString = null; - try { - FormUtils formUtils = new FormUtils(); - String formattedFormName = formName.replace(JSON_FORM_FOLDER, "").replace(JSON_FILE_EXTENSION, ""); - JSONObject formStringObj = formUtils.getFormJsonFromRepositoryOrAssets(context, formattedFormName); - if (formStringObj == null) { - return null; - } - formString = formStringObj.toString(); - if ((JsonForm.SPRAY_FORM.equals(formName) || JsonForm.SPRAY_FORM_BOTSWANA.equals(formName) - || JsonForm.SPRAY_FORM_NAMIBIA.equals(formName))) { - String structType = structureType; - if (StringUtils.isBlank(structureType)) { - structType = Constants.StructureType.NON_RESIDENTIAL; - } - formString = formString.replace(JsonForm.STRUCTURE_PROPERTIES_TYPE, structType); - } - - } catch (Exception e) { Timber.e(e); } - return formString; } - public JSONObject populateFormDetails(String formString, String entityId, String structureId, String taskIdentifier, - String taskBusinessStatus, String taskStatus, String structureUUID, - Integer structureVersion) throws JSONException { - - JSONObject formJson = new JSONObject(formString); - formJson.put(ENTITY_ID, entityId); - JSONObject formData = new JSONObject(); - formData.put(Properties.TASK_IDENTIFIER, taskIdentifier); - formData.put(Properties.TASK_BUSINESS_STATUS, taskBusinessStatus); - formData.put(Properties.TASK_STATUS, taskStatus); - formData.put(Properties.LOCATION_ID, structureId); - formData.put(Properties.LOCATION_UUID, structureUUID); - formData.put(Properties.LOCATION_VERSION, structureVersion); - formData.put(Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); - formData.put(Properties.FORM_VERSION, formJson.optString("form_version")); - String planIdentifier = PreferencesUtil.getInstance().getCurrentPlanId(); - formData.put(Properties.PLAN_IDENTIFIER, planIdentifier); - formJson.put(DETAILS, formData); - return formJson; - } - - - private void populateFormFields(JSONObject formJson, String structureType, String sprayStatus, String familyHead) throws JSONException { - - JSONArray fields = org.smartregister.util.JsonFormUtils.fields(formJson); - if (StringUtils.isNotBlank(structureType) || StringUtils.isNotBlank(sprayStatus) || StringUtils.isNotBlank(familyHead)) { - for (int i = 0; i < fields.length(); i++) { - JSONObject field = fields.getJSONObject(i); - String key = field.getString(KEY); - if (key.equalsIgnoreCase(JsonForm.STRUCTURE_TYPE)) - field.put(org.smartregister.util.JsonFormUtils.VALUE, structureType); - else if (key.equalsIgnoreCase(JsonForm.SPRAY_STATUS)) - field.put(org.smartregister.util.JsonFormUtils.VALUE, sprayStatus); - else if (key.equalsIgnoreCase(JsonForm.HEAD_OF_HOUSEHOLD)) - field.put(org.smartregister.util.JsonFormUtils.VALUE, familyHead); - } - } - - } - - - public void startJsonForm(JSONObject form, Activity context) { - startJsonForm(form, context, REQUEST_CODE_GET_JSON); - } - - public void startJsonForm(JSONObject form, Activity context, int requestCode) { - Intent intent = new Intent(context, RevealJsonFormActivity.class); - try { - intent.putExtra(JSON_FORM_PARAM_JSON, form.toString()); - context.startActivityForResult(intent, requestCode); - } catch (Exception e) { - Timber.e(e); - } - } - + @Override public String getFormName(String encounterType, String taskCode) { String formName = null; if (SPRAY_EVENT.equals(encounterType) || Intervention.IRS.equals(taskCode)) { @@ -328,125 +146,20 @@ public String getFormName(String encounterType, String taskCode) { return formName; } + @Override public String getFormName(String encounterType) { return getFormName(encounterType, null); } - public void populatePAOTForm(MosquitoHarvestCardDetails cardDetails, JSONObject formJson) { - if (formJson == null) - return; + @Override + public void startJsonForm(JSONObject form, Activity context, int requestCode) { + Intent intent = new Intent(context, RevealJsonFormActivity.class); try { - populateField(formJson, JsonForm.PAOT_STATUS, cardDetails.getStatus(), VALUE); - populateField(formJson, JsonForm.PAOT_COMMENTS, cardDetails.getComments(), VALUE); - populateField(formJson, JsonForm.LAST_UPDATED_DATE, cardDetails.getStartDate(), VALUE); - } catch (JSONException e) { + intent.putExtra(JSON_FORM_PARAM_JSON, form.toString()); + context.startActivityForResult(intent, requestCode); + } catch (Exception e) { Timber.e(e); } } - public void populateField(JSONObject formJson, String key, String value, String fieldToPopulate) throws JSONException { - JSONObject field = JsonFormUtils.getFieldJSONObject(JsonFormUtils.fields(formJson), key); - if (field != null) { - field.put(fieldToPopulate, value); - } - } - - public void populateSprayForm(CommonPersonObject commonPersonObject, JSONObject formJson) { - if (commonPersonObject == null || commonPersonObject.getDetails() == null) - return; - JSONArray fields = JsonFormUtils.fields(formJson); - for (int i = 0; i < fields.length(); i++) { - try { - JSONObject field = fields.getJSONObject(i); - String key = field.getString(KEY); - if (commonPersonObject.getDetails().containsKey(key)) { - String value = commonPersonObject.getDetails().get(key); - field.put(VALUE, value); - if (nonEditablefields.contains(key) && "Yes".equalsIgnoreCase(value)) { - field.put(JsonFormConstants.READ_ONLY, true); - field.remove(JsonFormConstants.RELEVANCE); - } - } - } catch (JSONException e) { - Timber.e(e); - } - - } - } - - public void populateForm(Event event, JSONObject formJSON) { - if (event == null) - return; - JSONArray fields = JsonFormUtils.fields(formJSON); - for (int i = 0; i < fields.length(); i++) { - try { - JSONObject field = fields.getJSONObject(i); - String key = field.getString(KEY); - Obs obs = event.findObs(null, false, key); - if (obs != null && obs.getValues() != null) { - if (CHECK_BOX.equals(field.getString(TYPE))) { - JSONArray options = field.getJSONArray(OPTIONS); - Map optionsKeyValue = new HashMap<>(); - for (int j = 0; j < options.length(); j++) { - JSONObject option = options.getJSONObject(j); - optionsKeyValue.put(option.getString(TEXT), option.getString(KEY)); - } - JSONArray keys = new JSONArray(); - for (Object value : obs.getValues()) { - keys.put(optionsKeyValue.get(value.toString())); - } - field.put(VALUE, keys); - } else - field.put(VALUE, obs.getValue()); - } - } catch (JSONException e) { - Timber.e(e); - } - } - } - - public Pair populateServerOptions(Map serverConfigs, JSONObject formJson, String settingsConfigKey, String formKey, String filterKey) { - if (serverConfigs == null) - return null; - JSONArray serverConfig = (JSONArray) serverConfigs.get(settingsConfigKey); - if (serverConfig != null && !serverConfig.isNull(0)) { - JSONArray fields = JsonFormUtils.fields(formJson); - JSONObject field = JsonFormUtils.getFieldJSONObject(fields, formKey); - if (field == null) - return null; - JSONArray options = serverConfig.optJSONObject(0).optJSONArray(filterKey); - if (options == null) - return null; - JSONArray codes = new JSONArray(); - JSONArray values = new JSONArray(); - for (int i = 0; i < options.length(); i++) { - JSONObject operator = options.optJSONObject(i); - if (operator == null) - continue; - String code = operator.optString(CONFIGURATION.CODE, null); - String name = operator.optString(CONFIGURATION.NAME); - if (StringUtils.isBlank(code) || code.equalsIgnoreCase(name)) { - codes.put(name); - values.put(name); - } else { - codes.put(code + ":" + name); - values.put(code + " - " + name); - } - } - try { - field.put(KEYS, codes); - field.put(VALUES, values); - } catch (JSONException e) { - Timber.e(e, "Error populating %s Operators ", formKey); - } - return new Pair<>(codes, values); - } - return null; - } - - public static org.smartregister.clientandeventmodel.Event createTaskEvent(String baseEntityId, String locationId, Map details, String eventType, String entityType) { - org.smartregister.clientandeventmodel.Event taskEvent = (org.smartregister.clientandeventmodel.Event) new org.smartregister.clientandeventmodel.Event().withBaseEntityId(baseEntityId).withEventDate(new Date()).withEventType(eventType) - .withLocationId(locationId).withEntityType(entityType).withFormSubmissionId(UUID.randomUUID().toString()).withDateCreated(new Date()); - return taskEvent; - } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealMapHelper.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealMapHelper.java index 461d4d22cd..1c25a2ccd5 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealMapHelper.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealMapHelper.java @@ -4,9 +4,10 @@ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Location; -import androidx.annotation.NonNull; import android.widget.ImageButton; +import androidx.annotation.NonNull; + import com.mapbox.geojson.Feature; import com.mapbox.geojson.FeatureCollection; import com.mapbox.geojson.MultiPolygon; @@ -27,8 +28,8 @@ import org.smartregister.reveal.R; import org.smartregister.reveal.layer.DigitalGlobeLayer; import org.smartregister.reveal.layer.MapBoxLayer; -import org.smartregister.reveal.repository.RevealMappingHelper; import org.smartregister.reveal.util.Constants.StructureType; +import org.smartregister.tasking.repository.RevealMappingHelper; import java.util.ArrayList; import java.util.List; @@ -58,8 +59,8 @@ import static org.smartregister.reveal.util.Constants.CONFIGURATION.OUTSIDE_OPERATIONAL_AREA_MASK_OPACITY; import static org.smartregister.reveal.util.Constants.GeoJSON.IS_INDEX_CASE; import static org.smartregister.reveal.util.Constants.GeoJSON.TYPE; -import static org.smartregister.reveal.util.Utils.createCircleFeature; -import static org.smartregister.reveal.util.Utils.getGlobalConfig; +import static org.smartregister.tasking.util.Utils.createCircleFeature; +import static org.smartregister.tasking.util.Utils.getGlobalConfig; /** * Created by samuelgithengi on 2/20/19. diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealSyncConfiguration.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealSyncConfiguration.java index a2fc619271..f74fd1c8dd 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealSyncConfiguration.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/RevealSyncConfiguration.java @@ -7,7 +7,9 @@ import org.smartregister.repository.AllSharedPreferences; import org.smartregister.repository.LocationRepository; import org.smartregister.reveal.BuildConfig; +import org.smartregister.reveal.activity.LoginActivity; import org.smartregister.reveal.application.RevealApplication; +import org.smartregister.view.activity.BaseLoginActivity; import java.util.List; @@ -136,4 +138,24 @@ public SyncFilter getSettingsSyncFilterParam() { public boolean clearDataOnNewTeamLogin() { return true; } + + @Override + public boolean runPlanEvaluationOnClientProcessing() { + return true; + } + + @Override + public String getOauthClientId() { + return BuildConfig.OAUTH_CLIENT_ID; + } + + @Override + public String getOauthClientSecret() { + return BuildConfig.OAUTH_CLIENT_SECRET; + } + + @Override + public Class getAuthenticationActivity() { + return LoginActivity.class; + } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/TaskUtils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/TaskUtils.java index f2336573c6..f6083a10a6 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/TaskUtils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/TaskUtils.java @@ -1,29 +1,23 @@ package org.smartregister.reveal.util; -import android.content.Context; -import androidx.annotation.StringRes; - import net.sqlcipher.Cursor; import net.sqlcipher.database.SQLiteDatabase; import org.joda.time.DateTime; import org.smartregister.clientandeventmodel.Event; -import org.smartregister.domain.Action; -import org.smartregister.domain.PlanDefinition; import org.smartregister.domain.Task; import org.smartregister.repository.AllSharedPreferences; import org.smartregister.repository.BaseRepository; import org.smartregister.repository.PlanDefinitionRepository; import org.smartregister.repository.TaskRepository; import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.model.BaseTaskDetails; import org.smartregister.reveal.util.Constants.BusinessStatus; import org.smartregister.reveal.util.Constants.Intervention; +import org.smartregister.tasking.model.BaseTaskDetails; +import org.smartregister.tasking.util.PreferencesUtil; import java.util.List; -import java.util.UUID; import timber.log.Timber; @@ -32,6 +26,7 @@ import static org.smartregister.reveal.util.Constants.DatabaseKeys.FOR; import static org.smartregister.reveal.util.Constants.DatabaseKeys.STATUS; import static org.smartregister.reveal.util.Constants.DatabaseKeys.TASK_TABLE; +import static org.smartregister.reveal.util.Utils.getDrawOperationalAreaBoundaryAndLabel; /** * Created by samuelgithengi on 4/14/19. @@ -65,66 +60,6 @@ private TaskUtils() { revealApplication = RevealApplication.getInstance(); } - public void generateBloodScreeningTask(Context context, String entityId, String structureId) { - generateTask(context, entityId, structureId, BusinessStatus.NOT_VISITED, Intervention.BLOOD_SCREENING, - R.string.blood_screening_description); - - } - - public void generateBedNetDistributionTask(Context context, String entityId) { - generateTask(context, entityId, entityId, BusinessStatus.NOT_VISITED, Intervention.BEDNET_DISTRIBUTION, - R.string.bednet_distribution_description); - } - - public Task generateTask(Context context, String entityId, String structureId, String businessStatus, String intervention, @StringRes int description) { - Task task = new Task(); - DateTime now = new DateTime(); - task.setIdentifier(UUID.randomUUID().toString()); - task.setPlanIdentifier(prefsUtil.getCurrentPlanId()); - task.setGroupIdentifier(Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId()); - task.setStatus(READY); - task.setBusinessStatus(businessStatus); - task.setPriority(3); - task.setCode(intervention); - task.setDescription(context.getString(description)); - PlanDefinition currentPlan = planRepository.findPlanDefinitionById(prefsUtil.getCurrentPlanId()); - if (currentPlan != null && currentPlan.getActions() != null) { - for (Action action : currentPlan.getActions()) { - if (intervention.equals(action.getCode())) { - task.setFocus(action.getIdentifier()); - continue; - } - } - } - task.setForEntity(entityId); - task.setStructureId(structureId); - task.setExecutionStartDate(now); - task.setAuthoredOn(now); - task.setLastModified(now); - task.setOwner(sharedPreferences.fetchRegisteredANM()); - task.setSyncStatus(BaseRepository.TYPE_Created); - taskRepository.addOrUpdate(task); - revealApplication.setSynced(false); - return task; - } - - - public Task generateRegisterFamilyTask(Context context, String entityId) { - return generateTask(context, entityId, entityId, BusinessStatus.NOT_VISITED, Intervention.REGISTER_FAMILY, - R.string.register_family_description); - - } - - public void generateMDADispenseTask(Context context, String entityId, String structureId) { - generateTask(context, entityId, structureId, BusinessStatus.NOT_VISITED, Intervention.MDA_DISPENSE, - R.string.mda_dispense_desciption); - } - - public void generateMDAAdherenceTask(Context context, String entityId, String structureId) { - generateTask(context, entityId, structureId, BusinessStatus.NOT_VISITED, Intervention.MDA_ADHERENCE, - R.string.mda_adherence_desciption); - } - public void tagEventTaskDetails(List events, SQLiteDatabase sqLiteDatabase) { for (Event event : events) { Cursor cursor = null; @@ -138,6 +73,7 @@ public void tagEventTaskDetails(List events, SQLiteDatabase sqLiteDatabas event.addDetails(Constants.Properties.TASK_STATUS, task.getStatus().name()); event.addDetails(Constants.Properties.LOCATION_ID, task.getForEntity()); event.addDetails(Constants.Properties.APP_VERSION_NAME, BuildConfig.VERSION_NAME); + event.addDetails(Constants.Properties.PLAN_IDENTIFIER, task.getPlanIdentifier()); event.setLocationId(task.getGroupIdentifier()); } @@ -155,7 +91,7 @@ public boolean resetTask(BaseTaskDetails taskDetails) { boolean taskResetSuccessful = false; try { Task task = taskRepository.getTaskByIdentifier(taskDetails.getTaskId()); - String operationalAreaId = Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId(); + String operationalAreaId = org.smartregister.tasking.util.Utils.getOperationalAreaLocation(prefsUtil.getCurrentOperationalArea()).getId(); if (Intervention.CASE_CONFIRMATION.equals(taskDetails.getTaskCode())) { task.setForEntity(operationalAreaId); diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/Utils.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/Utils.java index 84f3683898..73f9168a0b 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/util/Utils.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/util/Utils.java @@ -1,193 +1,13 @@ package org.smartregister.reveal.util; -import android.content.res.Configuration; -import android.content.res.Resources; -import android.os.Build; -import android.preference.PreferenceManager; -import androidx.annotation.NonNull; -import androidx.annotation.StringRes; -import androidx.core.util.Pair; -import android.text.SpannableStringBuilder; -import android.text.Spanned; -import android.text.style.ForegroundColorSpan; -import android.util.DisplayMetrics; -import android.util.TypedValue; -import android.widget.TextView; - -import com.google.gson.JsonElement; -import com.mapbox.geojson.Feature; -import com.mapbox.mapboxsdk.geometry.LatLng; - -import net.sqlcipher.database.SQLiteDatabase; - -import org.apache.commons.lang3.StringUtils; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.smartregister.clientandeventmodel.Client; -import org.smartregister.clientandeventmodel.Event; -import org.smartregister.domain.Location; -import org.smartregister.domain.tag.FormTag; -import org.smartregister.job.DocumentConfigurationServiceJob; -import org.smartregister.job.PullUniqueIdsServiceJob; -import org.smartregister.repository.AllSharedPreferences; -import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; -import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.job.LocationTaskServiceJob; -import org.smartregister.reveal.util.Constants.CONFIGURATION; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.Constants.Tags; -import org.smartregister.util.Cache; -import org.smartregister.util.CacheableData; -import org.smartregister.util.DatabaseMigrationUtils; -import org.smartregister.util.RecreateECUtil; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import timber.log.Timber; - -import static org.smartregister.reveal.util.Constants.CONFIGURATION.KILOMETERS_PER_DEGREE_OF_LATITUDE_AT_EQUITOR; -import static org.smartregister.reveal.util.Constants.CONFIGURATION.KILOMETERS_PER_DEGREE_OF_LONGITUDE_AT_EQUITOR; -import static org.smartregister.reveal.util.Constants.CONFIGURATION.METERS_PER_KILOMETER; -import static org.smartregister.reveal.util.Constants.DateFormat.CARD_VIEW_DATE_FORMAT; -import static org.smartregister.reveal.util.Constants.Intervention.FI; -import static org.smartregister.reveal.util.Constants.Intervention.IRS; -import static org.smartregister.reveal.util.Constants.Intervention.LARVAL_DIPPING; -import static org.smartregister.reveal.util.Constants.Intervention.MDA; -import static org.smartregister.reveal.util.Constants.Intervention.MOSQUITO_COLLECTION; -import static org.smartregister.reveal.util.Constants.Intervention.PAOT; +import static org.smartregister.tasking.util.Constants.CONFIGURATION; +import static org.smartregister.tasking.util.Utils.getGlobalConfig; +/** + * Created by Ephraim Kigamba - nek.eam@gmail.com on 12-08-2020. + */ public class Utils { - public static final ArrayList ALLOWED_LEVELS; - public static final String DEFAULT_LOCATION_LEVEL = Tags.HEALTH_CENTER; - public static final String REVEAL_PROJECT = "reveal"; - - private static Cache cache = new Cache<>(); - - static { - ALLOWED_LEVELS = new ArrayList<>(); - ALLOWED_LEVELS.add(DEFAULT_LOCATION_LEVEL); - ALLOWED_LEVELS.add(Tags.OPERATIONAL_AREA); - ALLOWED_LEVELS.add(Tags.CANTON); - ALLOWED_LEVELS.add(Tags.VILLAGE); - ALLOWED_LEVELS.add(REVEAL_PROJECT); - } - - public static void saveLanguage(String language) { - AllSharedPreferences allSharedPreferences = new AllSharedPreferences(PreferenceManager.getDefaultSharedPreferences(RevealApplication.getInstance().getApplicationContext())); - allSharedPreferences.saveLanguagePreference(language); - setLocale(new Locale(language)); - } - - public static void setLocale(Locale locale) { - Resources resources = RevealApplication.getInstance().getApplicationContext().getResources(); - Configuration configuration = resources.getConfiguration(); - DisplayMetrics displayMetrics = resources.getDisplayMetrics(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { - configuration.setLocale(locale); - RevealApplication.getInstance().getApplicationContext().createConfigurationContext(configuration); - } else { - configuration.locale = locale; - resources.updateConfiguration(configuration, displayMetrics); - } - } - - - public static void setTextViewText(@NonNull TextView textView, @NonNull @StringRes Integer labelResource, String value) { - SpannableStringBuilder builder = new SpannableStringBuilder(); - ForegroundColorSpan blackSpan = new ForegroundColorSpan(textView.getResources().getColor(R.color.text_black)); - builder.append(textView.getResources().getString(labelResource)).append(" "); - int start = builder.length(); - builder.append(value).setSpan(blackSpan, start, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); - textView.setText(builder); - } - - public static String getPropertyValue(Feature feature, String propertyKey) { - JsonElement featureProperty = feature.getProperty(propertyKey); - return featureProperty == null ? null : featureProperty.getAsString(); - } - - public static void startImmediateSync() { - LocationTaskServiceJob.scheduleJobImmediately(LocationTaskServiceJob.TAG); - PullUniqueIdsServiceJob.scheduleJobImmediately(PullUniqueIdsServiceJob.TAG); - DocumentConfigurationServiceJob.scheduleJobImmediately(DocumentConfigurationServiceJob.TAG); - } - - - public static Location getOperationalAreaLocation(String operationalArea) { - return cache.get(operationalArea, new CacheableData() { - @Override - public Location fetch() { - return RevealApplication.getInstance().getLocationRepository().getLocationByName(operationalArea); - } - }); - } - - public static String formatDate(String date, String dateFormat) throws Exception { - DateFormat sdf = new SimpleDateFormat(dateFormat, Locale.getDefault()); - Date originalDate = sdf.parse(date); - - sdf = new SimpleDateFormat(CARD_VIEW_DATE_FORMAT, Locale.getDefault()); - - return sdf.format(originalDate); - - } - - public static String formatDate(Date originalDate) { - if (originalDate == null) { - return null; - } - DateFormat sdf = new SimpleDateFormat(CARD_VIEW_DATE_FORMAT, Locale.getDefault()); - return sdf.format(originalDate); - - } - - public static String getGlobalConfig(String key, String defaultValue) { - Map globalConfigs = RevealApplication.getInstance().getServerConfigs(); - Object val = globalConfigs != null ? globalConfigs.get(key) : null; - return val == null ? defaultValue : val.toString(); - } - - public static Float getLocationBuffer() { - return Float.valueOf(getGlobalConfig(CONFIGURATION.LOCATION_BUFFER_RADIUS_IN_METRES, BuildConfig.MY_LOCATION_BUFFER + "")); - } - - - public static Float getPixelsPerDPI(Resources resources) { - return TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, - 1, - resources.getDisplayMetrics() - ); - } - - public static int getInterventionLabel() { - String plan = PreferencesUtil.getInstance().getCurrentPlan(); - String interventionType = PreferencesUtil.getInstance().getInterventionTypeForPlan(plan); - if (interventionType.equals(FI)) - return R.string.focus_investigation; - else if (interventionType.equals(IRS)) - return R.string.irs; - else if (interventionType.equals(MDA)) - return R.string.mda; - else - return R.string.irs; - } - - public static String getAge(String dob) { - String dobString = org.smartregister.family.util.Utils.getDuration(dob); - return dobString.contains("y") ? dobString.substring(0, dobString.indexOf("y")) : dobString; - } /** * Uses the server setting "draw_operational_area_boundary_and_label" to determine whether to draw the operational area boundary @@ -199,100 +19,11 @@ public static Boolean getDrawOperationalAreaBoundaryAndLabel() { return Boolean.valueOf(getGlobalConfig(CONFIGURATION.DRAW_OPERATIONAL_AREA_BOUNDARY_AND_LABEL, CONFIGURATION.DEFAULT_DRAW_OPERATIONAL_AREA_BOUNDARY_AND_LABEL.toString())); } - /** - * Uses the server setting "validate_far_structures" to determine whether to Validate Far Structures - * If this variable is not available on the server the value is retrieved from BuildConfig.VALIDATE_FAR_STRUCTURES - * - * @return validateFarStructures - */ - public static Boolean validateFarStructures() { - return Boolean.valueOf(getGlobalConfig(CONFIGURATION.VALIDATE_FAR_STRUCTURES, BuildConfig.VALIDATE_FAR_STRUCTURES + "")); - } - - /** - * Uses the server setting "resolve_location_timeout_in_seconds" to determine the Resolve Location Timeout In Seconds value - * If this variable is not available on the server the value is retrieved from BuildConfig.RESOLVE_LOCATION_TIMEOUT_IN_SECONDS - * - * @return ResolveLocationTimeoutInSeconds - */ - public static int getResolveLocationTimeoutInSeconds() { - return Integer.valueOf(getGlobalConfig(CONFIGURATION.RESOLVE_LOCATION_TIMEOUT_IN_SECONDS, BuildConfig.RESOLVE_LOCATION_TIMEOUT_IN_SECONDS + "")); - } - - /** - * Uses the server setting "admin_password_not_near_structures" to determine the Admin Password required to perform any edits when not near a structure - * If this variable is not available on the server the value is retrieved from BuildConfig.ADMIN_PASSWORD_NOT_NEAR_STRUCTURES - * - * @return AdminPassword - */ - public static String getAdminPasswordNotNearStructures() { - return getGlobalConfig(CONFIGURATION.ADMIN_PASSWORD_NOT_NEAR_STRUCTURES, BuildConfig.ADMIN_PASSWORD_NOT_NEAR_STRUCTURES); - } - - /** - * Creates a circle using a GeoJSON polygon. - * It's not strictly a circle but by increasing the number of sides on the polygon you can get pretty close to one. - *

- * Adapted from https://stackoverflow.com/questions/37599561/drawing-a-circle-with-the-radius-in-miles-meters-with-mapbox-gl-js/39006388#39006388 - * - * @param center - Coordinates for the center of the circle - * @param radius - Radius of the circle in meters - * @param points - Since this is a GeoJSON polygon, we need to have a large number of sides - * so that it gets as close as possible to being a circle - * @return - * @throws Exception - */ - - public static Feature createCircleFeature(LatLng center, Float radius, Float points) throws JSONException { - Float radiusInKm = radius / METERS_PER_KILOMETER; - - JSONArray coordinates = new JSONArray(); - JSONArray coordinate = new JSONArray(); - JSONArray bufferArray = new JSONArray(); - double distanceX = radiusInKm / (KILOMETERS_PER_DEGREE_OF_LONGITUDE_AT_EQUITOR * Math.cos(center.getLatitude() * Math.PI / 180)); - double distanceY = radiusInKm / KILOMETERS_PER_DEGREE_OF_LATITUDE_AT_EQUITOR; - - double theta; - double x; - double y; - for (int i = 0; i < points; i++) { - theta = (i / points) * (2 * Math.PI); - x = distanceX * Math.cos(theta); - y = distanceY * Math.sin(theta); - - Double longitude = center.getLongitude() + x; - Double latitude = center.getLatitude() + y; - coordinate.put(longitude); - coordinate.put(latitude); - bufferArray.put(coordinate); - coordinate = new JSONArray(); - } - - coordinates.put(bufferArray); - - JSONObject feature = new JSONObject(); - feature.put("type", "Feature"); - JSONObject geometry = new JSONObject(); - - geometry.put("type", "Polygon"); - geometry.put("coordinates", coordinates); - feature.put("geometry", geometry); - - return Feature.fromJson(feature.toString()); + public static String getAge(String dob) { + String dobString = org.smartregister.family.util.Utils.getDuration(dob); + return dobString.contains("y") ? dobString.substring(0, dobString.indexOf("y")) : dobString; } - /** - * Determines whether a structure is a residence based on the Task Code value - * - * @param taskCode - * @return isResidentialStructure - */ - public static boolean isResidentialStructure(String taskCode) { - if (StringUtils.isEmpty(taskCode)) { - return false; - } - return !(MOSQUITO_COLLECTION.equals(taskCode) || LARVAL_DIPPING.equals(taskCode) || PAOT.equals(taskCode)); - } /** * Uses the server setting "display_add_structure_out_of_boundary_warning_dialog" to determine @@ -307,100 +38,20 @@ public static Boolean displayAddStructureOutOfBoundaryWarningDialog() { return Boolean.valueOf(getGlobalConfig(CONFIGURATION.DISPLAY_ADD_STRUCTURE_OUT_OF_BOUNDARY_WARNING_DIALOG, CONFIGURATION.DEFAULT_DISPLAY_ADD_STRUCTURE_OUT_OF_BOUNDARY_WARNING_DIALOG.toString())); } - public static boolean isFocusInvestigation() { - return getInterventionLabel() == R.string.focus_investigation; - } - - public static boolean isMDA() { - return getInterventionLabel() == R.string.mda; - } - - public static boolean isFocusInvestigationOrMDA() { - return isFocusInvestigation() || isMDA(); - } - - public static String getCurrentLocationId() { - Location currentOperationalArea = getOperationalAreaLocation(PreferencesUtil.getInstance().getCurrentOperationalArea()); - return currentOperationalArea == null ? null : currentOperationalArea.getId(); - } - - public static FormTag getFormTag() { - FormTag formTag = new FormTag(); - AllSharedPreferences sharedPreferences = RevealApplication.getInstance().getContext().allSharedPreferences(); - formTag.providerId = sharedPreferences.fetchRegisteredANM(); - formTag.locationId = PreferencesUtil.getInstance().getCurrentOperationalAreaId(); - formTag.teamId = sharedPreferences.fetchDefaultTeamId(formTag.providerId); - formTag.team = sharedPreferences.fetchDefaultTeam(formTag.providerId); - formTag.databaseVersion = BuildConfig.DATABASE_VERSION; - formTag.appVersion = BuildConfig.VERSION_CODE; - formTag.appVersionName = BuildConfig.VERSION_NAME; - return formTag; - } - - - public static void tagEventMetadata(Event event, FormTag formTag) { - event.setProviderId(formTag.providerId); - event.setLocationId(formTag.locationId); - event.setChildLocationId(formTag.childLocationId); - event.setTeam(formTag.team); - event.setTeamId(formTag.teamId); - event.setClientDatabaseVersion(formTag.databaseVersion); - event.setClientApplicationVersion(formTag.appVersion); - event.addDetails(Properties.APP_VERSION_NAME, formTag.appVersionName); - } - - public static void recreateEventAndClients(String query, String[] params, SQLiteDatabase db, FormTag formTag, String tableName, String eventType, String entityType, RecreateECUtil util) { - try { - if (!DatabaseMigrationUtils.isColumnExists(db, tableName, "id")) { - return; - } - Pair, List> events = util.createEventAndClients(db, tableName, query, params, eventType, entityType, formTag); - if (events.first != null) { - TaskUtils.getInstance().tagEventTaskDetails(events.first, db); - } - util.saveEventAndClients(events, db); - } catch (Exception e) { - Timber.e(e, "Error creating events and clients for %s", tableName); - } - } - - public static boolean matchesSearchPhrase(String toSearch, String searchPhrase) { - if (StringUtils.isBlank(toSearch)) - return false; - String wordsSpaceAndCommaRegex = "[\\w\\h,]*"; - return toSearch.toLowerCase().matches(wordsSpaceAndCommaRegex + searchPhrase.toLowerCase() + wordsSpaceAndCommaRegex); - } - - - public static Set getInterventionUnitCodes(Set filterList) { - if (filterList == null) { - return null; - } - Set codes = new HashSet<>(); - if (filterList.contains(Constants.InterventionType.PERSON) || filterList.contains(Constants.InterventionType.FAMILY)) { - codes.addAll(Constants.Intervention.PERSON_INTERVENTIONS); - } - if (filterList.contains(Constants.InterventionType.OPERATIONAL_AREA)) { - codes.add(Constants.Intervention.BCC); - } - if (filterList.contains(Constants.InterventionType.STRUCTURE)) { - List interventions = new ArrayList<>(Constants.Intervention.FI_INTERVENTIONS); - interventions.removeAll(Constants.Intervention.PERSON_INTERVENTIONS); - interventions.addAll(Constants.Intervention.IRS_INTERVENTIONS); - codes.addAll(interventions); - } - return codes; - - } /** - * Uses the server setting "DISPLAY_DISTANCE_SCALE" to determine whether to display the distance scale - * If this variable is not available on the server the value is retrieved from BuildConfig.DISPLAY_DISTANCE_SCALE + * Determines whether a structure is a residence based on the Task Code value * - * @return displayDistanceScale + * @param taskCode + * @return isResidentialStructure */ - public static Boolean displayDistanceScale() { - return Boolean.valueOf(getGlobalConfig(CONFIGURATION.DISPLAY_DISTANCE_SCALE, BuildConfig.DISPLAY_DISTANCE_SCALE + "")); - } + /*public static boolean isResidentialStructure(String taskCode) { + if (StringUtils.isEmpty(taskCode)) { + return false; + } + return !(Constants.Intervention.MOSQUITO_COLLECTION.equals(taskCode) + || Constants.Intervention.LARVAL_DIPPING.equals(taskCode) + || Constants.Intervention.PAOT.equals(taskCode)); + }*/ } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/DrawerMenuView.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/DrawerMenuView.java index 412097e350..a9a9b2911a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/DrawerMenuView.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/DrawerMenuView.java @@ -4,18 +4,19 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; -import androidx.annotation.NonNull; -import androidx.constraintlayout.widget.ConstraintLayout; -import com.google.android.material.navigation.NavigationView; -import androidx.core.util.Pair; -import androidx.core.view.GravityCompat; -import androidx.drawerlayout.widget.DrawerLayout; import android.view.View; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; +import androidx.annotation.NonNull; +import androidx.constraintlayout.widget.ConstraintLayout; +import androidx.core.util.Pair; +import androidx.core.view.GravityCompat; +import androidx.drawerlayout.widget.DrawerLayout; + +import com.google.android.material.navigation.NavigationView; import com.vijay.jsonwizard.customviews.TreeViewDialog; import org.apache.commons.lang3.StringUtils; @@ -25,12 +26,12 @@ import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseDrawerContract; import org.smartregister.reveal.interactor.BaseDrawerInteractor; import org.smartregister.reveal.presenter.BaseDrawerPresenter; -import org.smartregister.reveal.util.AlertDialogUtils; import org.smartregister.reveal.util.Constants.Tags; import org.smartregister.reveal.util.Country; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.tasking.util.AlertDialogUtils; import org.smartregister.util.Utils; import java.text.SimpleDateFormat; @@ -205,18 +206,18 @@ public String getOperationalArea() { @Override public void setDistrict(String district) { - org.smartregister.reveal.util.Utils.setTextViewText(districtTextView, R.string.district, district); + org.smartregister.tasking.util.Utils.setTextViewText(districtTextView, R.string.district, district); } @Override public void setFacility(String facility, String facilityLevel) { - org.smartregister.reveal.util.Utils.setTextViewText(facilityTextView, + org.smartregister.tasking.util.Utils.setTextViewText(facilityTextView, Tags.CANTON.equals(facilityLevel) ? R.string.canton : R.string.facility, facility); } @Override public void setOperator() { - org.smartregister.reveal.util.Utils.setTextViewText(operatorTextView, R.string.operator, + org.smartregister.tasking.util.Utils.setTextViewText(operatorTextView, R.string.operator, RevealApplication.getInstance().getContext().allSharedPreferences().fetchRegisteredANM()); } @@ -320,7 +321,7 @@ else if (v.getId() == R.id.btn_navMenu_summaryForms) else if (v.getId() == R.id.btn_navMenu_offline_maps) presenter.onShowOfflineMaps(); else if (v.getId() == R.id.sync_button) { - org.smartregister.reveal.util.Utils.startImmediateSync(); + org.smartregister.tasking.util.Utils.startImmediateSync(); closeDrawerLayout(); } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyOtherMemberProfileActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyOtherMemberProfileActivity.java index 327531e0c8..079da6ff23 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyOtherMemberProfileActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyOtherMemberProfileActivity.java @@ -4,11 +4,12 @@ import android.content.Intent; import android.os.Handler; import android.os.Looper; -import androidx.fragment.app.Fragment; -import androidx.viewpager.widget.ViewPager; import android.view.Menu; import android.view.MenuItem; +import androidx.fragment.app.Fragment; +import androidx.viewpager.widget.ViewPager; + import com.vijay.jsonwizard.constants.JsonFormConstants; import com.vijay.jsonwizard.domain.Form; @@ -23,7 +24,7 @@ import org.smartregister.reveal.contract.FamilyOtherMemberProfileContract; import org.smartregister.reveal.fragment.FamilyOtherMemberProfileFragment; import org.smartregister.reveal.presenter.FamilyOtherMemberPresenter; -import org.smartregister.reveal.util.PreferencesUtil; +import org.smartregister.tasking.util.PreferencesUtil; import org.smartregister.view.fragment.BaseRegisterFragment; import timber.log.Timber; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyRegisterActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyRegisterActivity.java index c240bba85d..b93bb48815 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyRegisterActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FamilyRegisterActivity.java @@ -19,6 +19,8 @@ import org.smartregister.reveal.util.Constants.Properties; import org.smartregister.view.fragment.BaseRegisterFragment; +import java.util.Map; + import timber.log.Timber; /** @@ -54,6 +56,11 @@ protected Fragment[] getOtherFragments() { return new Fragment[0]; } + @Override + public void startFormActivity(String s, String s1, Map map) { + + } + @Override protected void registerBottomNavigation() { super.registerBottomNavigation(); diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FilterTasksActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FilterTasksActivity.java deleted file mode 100644 index 2a43ec4a1d..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/FilterTasksActivity.java +++ /dev/null @@ -1,176 +0,0 @@ -package org.smartregister.reveal.view; - -import android.content.Intent; -import android.os.Bundle; -import androidx.appcompat.view.ContextThemeWrapper; -import androidx.appcompat.widget.AppCompatSpinner; -import androidx.appcompat.widget.Toolbar; -import android.view.MenuItem; -import android.widget.CompoundButton; -import android.widget.TextView; -import android.widget.ToggleButton; - -import com.google.android.flexbox.FlexboxLayout; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.FilterTasksContract; -import org.smartregister.reveal.model.TaskFilterParams; -import org.smartregister.reveal.presenter.FilterTasksPresenter; -import org.smartregister.reveal.util.Constants.Filter; -import org.smartregister.reveal.util.Constants.InterventionType; -import org.smartregister.view.activity.MultiLanguageActivity; - -import java.util.List; - -import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; - -public class FilterTasksActivity extends MultiLanguageActivity implements FilterTasksContract.View, CompoundButton.OnCheckedChangeListener { - - private FilterTasksContract.Presenter presenter; - - private AppCompatSpinner sortBySpinner; - - private FlexboxLayout businessStatusLayout; - - private FlexboxLayout taskCodeLayout; - - private FlexboxLayout interventionTypeLayout; - - private TextView applyFiltersTextView; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - presenter = new FilterTasksPresenter(this); - setContentView(R.layout.activity_filter_tasks); - Toolbar toolbar = this.findViewById(R.id.filter_tasks_toolbar); - toolbar.setTitle(R.string.filter); - setSupportActionBar(toolbar); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_close); - - sortBySpinner = findViewById(R.id.sort_by); - businessStatusLayout = findViewById(R.id.business_status_layout); - taskCodeLayout = findViewById(R.id.task_code_layout); - interventionTypeLayout = findViewById(R.id.intervention_type_layout); - applyFiltersTextView = findViewById(R.id.apply_filters); - - setUpToggleButtonGroups(); - - findViewById(R.id.clear_filters).setOnClickListener(view -> { - clearSelections(); - }); - - applyFiltersTextView.setOnClickListener(view -> { - presenter.onApplyFilters(sortBySpinner.getSelectedItem().toString()); - }); - - - TaskFilterParams filterParams = (TaskFilterParams) getIntent().getSerializableExtra(Filter.FILTER_SORT_PARAMS); - if (filterParams != null) { - presenter.restoreCheckedFilters(filterParams); - } - } - - - private void clearSelections() { - sortBySpinner.setSelection(0); - clearSelectedButtons(businessStatusLayout); - clearSelectedButtons(taskCodeLayout); - clearSelectedButtons(interventionTypeLayout); - } - - - private void registerCheckedChangeListener() { - registerCheckedChangeListener(businessStatusLayout, Filter.STATUS); - registerCheckedChangeListener(taskCodeLayout, Filter.CODE); - registerCheckedChangeListener(interventionTypeLayout, Filter.INTERVENTION_UNIT); - } - - private void registerCheckedChangeListener(FlexboxLayout layout, String category) { - for (int i = 0; i < layout.getFlexItemCount(); i++) { - ToggleButton toggleButton = ((ToggleButton) layout.getFlexItemAt(i)); - toggleButton.setOnCheckedChangeListener(this); - toggleButton.setTag(R.id.filter_category, category); - } - } - - private void clearSelectedButtons(FlexboxLayout layout) { - for (int i = 0; i < layout.getFlexItemCount(); i++) { - ((ToggleButton) layout.getFlexItemAt(i)).setChecked(false); - } - } - - private void setUpToggleButtonGroups() { - populateToggleButtons(businessStatusLayout, presenter.getBusinessStatusOptions()); - populateToggleButtons(taskCodeLayout, presenter.getIntentionTypes()); - populateToggleButtons(interventionTypeLayout, InterventionType.FILTERABLE_INTERVENTION_TYPES); - registerCheckedChangeListener(); - - } - - private void populateToggleButtons(FlexboxLayout layout, List options) { - FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); - params.setMargins(0, 0, getResources().getDimensionPixelSize(R.dimen.filter_toggle_end_margin), - getResources().getDimensionPixelSize(R.dimen.filter_toggle_bottom_margin)); - for (String intervention : options) { - - ToggleButton toggleButton = new ToggleButton(new ContextThemeWrapper(this, R.style.TaskFilterToggle), null, 0); - Integer label = presenter.getStringResource(intervention); - if (label == null) { - toggleButton.setText(intervention); - } else { - toggleButton.setText(label); - } - toggleButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.toggle_bg)); - toggleButton.setTag(intervention); - layout.addView(toggleButton, params); - } - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - if (item.getItemId() == android.R.id.home) { - finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - - presenter.onToggleChanged(buttonView.isChecked(), buttonView.getTag(R.id.filter_category), buttonView.getTag()); - } - - @Override - public void onFiltedSelected(int size) { - applyFiltersTextView.setText(getString(R.string.apply_filters_formatter, size)); - } - - @Override - public void applyFilters(Intent intent) { - setResult(RESULT_OK, intent); - finish(); - } - - @Override - public FlexboxLayout getBusinessStatusLayout() { - return businessStatusLayout; - } - - @Override - public FlexboxLayout getTaskCodeLayout() { - return taskCodeLayout; - } - - @Override - public FlexboxLayout getInterventionTypeLayout() { - return interventionTypeLayout; - } - - @Override - public void setSortBySelection(int sortBySpinner) { - this.sortBySpinner.setSelection(sortBySpinner); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/ListTasksActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/ListTasksActivity.java index f28822e64e..397350fd1d 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/ListTasksActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/ListTasksActivity.java @@ -10,13 +10,6 @@ import android.graphics.Color; import android.location.Location; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.annotation.StringRes; -import com.google.android.material.floatingactionbutton.FloatingActionButton; -import com.google.android.material.snackbar.Snackbar; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import androidx.appcompat.app.AppCompatActivity; -import androidx.cardview.widget.CardView; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; @@ -29,6 +22,14 @@ import android.widget.TextView; import android.widget.Toast; +import androidx.annotation.NonNull; +import androidx.annotation.StringRes; +import androidx.appcompat.app.AppCompatActivity; +import androidx.cardview.widget.CardView; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; + +import com.google.android.material.floatingactionbutton.FloatingActionButton; +import com.google.android.material.snackbar.Snackbar; import com.mapbox.android.core.permissions.PermissionsManager; import com.mapbox.geojson.Feature; import com.mapbox.geojson.FeatureCollection; @@ -46,6 +47,7 @@ import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; +import org.smartregister.AllConstants.INTENT_KEY; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.domain.FetchStatus; import org.smartregister.domain.Task; @@ -55,25 +57,26 @@ import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.contract.BaseDrawerContract; import org.smartregister.reveal.contract.ListTaskContract; -import org.smartregister.reveal.contract.UserLocationContract.UserLocationView; -import org.smartregister.reveal.model.CardDetails; import org.smartregister.reveal.model.FamilyCardDetails; import org.smartregister.reveal.model.IRSVerificationCardDetails; import org.smartregister.reveal.model.MosquitoHarvestCardDetails; import org.smartregister.reveal.model.SprayCardDetails; -import org.smartregister.reveal.model.TaskFilterParams; import org.smartregister.reveal.presenter.ListTaskPresenter; -import org.smartregister.reveal.repository.RevealMappingHelper; -import org.smartregister.reveal.util.AlertDialogUtils; import org.smartregister.reveal.util.CardDetailsUtil; -import org.smartregister.reveal.util.Constants.Action; import org.smartregister.reveal.util.Constants.Properties; import org.smartregister.reveal.util.Constants.TaskRegister; import org.smartregister.reveal.util.Country; import org.smartregister.reveal.util.RevealJsonFormUtils; import org.smartregister.reveal.util.RevealMapHelper; +import org.smartregister.tasking.activity.FilterTasksActivity; +import org.smartregister.tasking.activity.TaskRegisterActivity; +import org.smartregister.tasking.contract.BaseDrawerContract; +import org.smartregister.tasking.contract.UserLocationContract; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.model.TaskFilterParams; +import org.smartregister.tasking.repository.RevealMappingHelper; +import org.smartregister.tasking.util.AlertDialogUtils; import io.ona.kujaku.callbacks.OnLocationComponentInitializedCallback; import io.ona.kujaku.layers.BoundaryLayer; @@ -82,6 +85,7 @@ import static android.content.DialogInterface.BUTTON_POSITIVE; import static org.smartregister.reveal.util.Constants.ANIMATE_TO_LOCATION_DURATION; +import static org.smartregister.reveal.util.Constants.Action.STRUCTURE_TASK_SYNCED; import static org.smartregister.reveal.util.Constants.CONFIGURATION.LOCAL_SYNC_DONE; import static org.smartregister.reveal.util.Constants.CONFIGURATION.UPDATE_LOCATION_BUFFER_RADIUS; import static org.smartregister.reveal.util.Constants.DatabaseKeys.STRUCTURE_ID; @@ -98,16 +102,16 @@ import static org.smartregister.reveal.util.Constants.RequestCode.REQUEST_CODE_TASK_LISTS; import static org.smartregister.reveal.util.Constants.VERTICAL_OFFSET; import static org.smartregister.reveal.util.FamilyConstants.Intent.START_REGISTRATION; -import static org.smartregister.reveal.util.Utils.displayDistanceScale; +import static org.smartregister.tasking.util.Utils.displayDistanceScale; import static org.smartregister.reveal.util.Utils.getDrawOperationalAreaBoundaryAndLabel; -import static org.smartregister.reveal.util.Utils.getLocationBuffer; -import static org.smartregister.reveal.util.Utils.getPixelsPerDPI; +import static org.smartregister.tasking.util.Utils.getLocationBuffer; +import static org.smartregister.tasking.util.Utils.getPixelsPerDPI; /** * Created by samuelgithengi on 11/20/18. */ public class ListTasksActivity extends BaseMapActivity implements ListTaskContract.ListTaskView, - View.OnClickListener, SyncStatusBroadcastReceiver.SyncStatusListener, UserLocationView, OnLocationComponentInitializedCallback { + View.OnClickListener, SyncStatusBroadcastReceiver.SyncStatusListener, UserLocationContract.UserLocationView, OnLocationComponentInitializedCallback { private ListTaskPresenter listTaskPresenter; @@ -364,7 +368,7 @@ public boolean onMapLongClick(@NonNull LatLng point) { } protected void initializeScaleBarPlugin(MapboxMap mapboxMap) { - if(displayDistanceScale()) { + if (displayDistanceScale()) { ScaleBarPlugin scaleBarPlugin = new ScaleBarPlugin(kujakuMapView, mapboxMap); // Create a ScaleBarOptions object to use custom styling ScaleBarOptions scaleBarOptions = new ScaleBarOptions(getContext()); @@ -393,13 +397,13 @@ public void positionMyLocationAndLayerSwitcher() { } else { int progressHeight = getResources().getDimensionPixelSize(R.dimen.progress_height); - int bottomMargin = org.smartregister.reveal.util.Utils.getInterventionLabel() == R.string.irs ? progressHeight + 40 : 40; + int bottomMargin = org.smartregister.tasking.util.Utils.getInterventionLabel() == R.string.irs ? progressHeight + 40 : 40; positionMyLocationAndLayerSwitcher(myLocationButtonParams, bottomMargin); if (layerSwitcherFab != null) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layerSwitcherFab.getLayoutParams(); //position the layer selector above location button and with similar bottom margin - if (org.smartregister.reveal.util.Utils.getInterventionLabel() == R.string.irs) + if (org.smartregister.tasking.util.Utils.getInterventionLabel() == R.string.irs) params.bottomMargin = myLocationButton.getMeasuredHeight() + progressHeight + 80; else params.bottomMargin = myLocationButton.getMeasuredHeight() + bottomMargin + 40; @@ -769,8 +773,7 @@ public void onSyncInProgress(FetchStatus fetchStatus) { } @Override - public void onSyncComplete(FetchStatus fetchStatus) - { + public void onSyncComplete(FetchStatus fetchStatus) { onSyncInProgress(fetchStatus); //Check sync status and Update UI to show sync status drawerView.checkSynced(); @@ -780,7 +783,7 @@ public void onSyncComplete(FetchStatus fetchStatus) public void onResume() { super.onResume(); SyncStatusBroadcastReceiver.getInstance().addSyncStatusListener(this); - IntentFilter filter = new IntentFilter(Action.STRUCTURE_TASK_SYNCED); + IntentFilter filter = new IntentFilter(STRUCTURE_TASK_SYNCED); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(refreshGeowidgetReceiver, filter); drawerView.onResume(); listTaskPresenter.onResume(); @@ -855,12 +858,17 @@ private class RefreshGeowidgetReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); boolean localSyncDone; - if (extras != null && extras.getBoolean(UPDATE_LOCATION_BUFFER_RADIUS)) { + if (STRUCTURE_TASK_SYNCED.equals(intent.getAction()) && extras != null && extras.getBoolean(UPDATE_LOCATION_BUFFER_RADIUS)) { float bufferRadius = getLocationBuffer() / getPixelsPerDPI(getResources()); kujakuMapView.setLocationBufferRadius(bufferRadius); - } else { + } else if (STRUCTURE_TASK_SYNCED.equals(intent.getAction())) { localSyncDone = extras != null && extras.getBoolean(LOCAL_SYNC_DONE); listTaskPresenter.refreshStructures(localSyncDone); + } else if (INTENT_KEY.TASK_GENERATED_EVENT.equals(intent.getAction())) { + Task task = extras != null ? (Task) extras.getSerializable(INTENT_KEY.TASK_GENERATED) : null; + if (task != null) { + listTaskPresenter.resetFeatureTasks(task.getStructureId(), task); + } } } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/OfflineMapsActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/OfflineMapsActivity.java index e07b92a16d..5a8594ecb4 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/OfflineMapsActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/OfflineMapsActivity.java @@ -1,143 +1,15 @@ package org.smartregister.reveal.view; -import android.os.Bundle; -import androidx.annotation.Nullable; -import com.google.android.material.tabs.TabLayout; -import androidx.core.util.Pair; -import androidx.viewpager.widget.ViewPager; -import androidx.appcompat.app.AppCompatActivity; -import androidx.appcompat.widget.Toolbar; -import android.view.View; +import androidx.annotation.NonNull; -import com.mapbox.mapboxsdk.offline.OfflineManager; -import com.mapbox.mapboxsdk.offline.OfflineRegion; - -import org.smartregister.family.adapter.ViewPagerAdapter; import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.OfflineMapDownloadCallback; -import org.smartregister.reveal.fragment.AvailableOfflineMapsFragment; -import org.smartregister.reveal.fragment.DownloadedOfflineMapsFragment; -import org.smartregister.reveal.model.OfflineMapModel; -import org.smartregister.reveal.util.OfflineMapHelper; - -import java.util.List; -import java.util.Map; - -import timber.log.Timber; - -public class OfflineMapsActivity extends AppCompatActivity implements OfflineMapDownloadCallback { - - private static final String TAG = OfflineMapsActivity.class.getName(); - - private ViewPagerAdapter adapter; - - private ViewPager viewPager; - - private AvailableOfflineMapsFragment availableOfflineMapsFragment; - - private DownloadedOfflineMapsFragment downloadedOfflineMapsFragment; - - private OfflineManager offlineManager; - - public static final int AVAILABLE_OFFLINE_MAPS_FRAGMENT_INDEX = 0; - public static final int DOWNLOADED_OFFLINE_MAPS_FRAGMENT_INDEX = 1; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.activity_offline_maps); - - setUpToolbar(); - - setupViews(); - - offlineManager = initOfflineManager(); - - getOfflineDownloadedRegions(false); - } - - protected void setUpToolbar() { - Toolbar toolbar= this.findViewById(R.id.offline_maps_toolbar); - toolbar.setTitle(R.string.offline_maps); - this.setSupportActionBar(toolbar); - this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); - toolbar.setNavigationOnClickListener(new View.OnClickListener(){ - - @Override - public void onClick(View v) { - onBackPressed(); - } - }); - } - - protected void setupViews() { - TabLayout tabLayout = findViewById(R.id.tabs); - viewPager = findViewById(R.id.viewpager); - tabLayout.setupWithViewPager(setupViewPager()); - } - protected ViewPager setupViewPager() { - adapter = new ViewPagerAdapter(getSupportFragmentManager()); +public class OfflineMapsActivity extends org.smartregister.tasking.view.OfflineMapsActivity { - availableOfflineMapsFragment = AvailableOfflineMapsFragment.newInstance(this.getIntent().getExtras()); - availableOfflineMapsFragment.setOfflineMapDownloadCallback(this); - adapter.addFragment(availableOfflineMapsFragment, this.getString(R.string.available).toUpperCase()); - - downloadedOfflineMapsFragment = DownloadedOfflineMapsFragment.newInstance(this.getIntent().getExtras(), this ); - downloadedOfflineMapsFragment.setOfflineMapDownloadCallback(this); - adapter.addFragment(downloadedOfflineMapsFragment, this.getString(R.string.downloaded).toUpperCase()); - - viewPager.setAdapter(adapter); - - return viewPager; - } - - public OfflineManager initOfflineManager() { - return OfflineManager.getInstance(this); - } + @NonNull @Override - public void onMapDownloaded(OfflineMapModel offlineMapModel) { - getOfflineDownloadedRegions(true); - } - - @Override - public void onOfflineMapDeleted(OfflineMapModel offlineMapModel) { - availableOfflineMapsFragment = (AvailableOfflineMapsFragment) adapter.getItem(AVAILABLE_OFFLINE_MAPS_FRAGMENT_INDEX); - availableOfflineMapsFragment.updateOperationalAreasToDownload(offlineMapModel); - } - - public void getOfflineDownloadedRegions(boolean refreshDownloadedListOnly) { - - offlineManager.listOfflineRegions(new OfflineManager.ListOfflineRegionsCallback() { - @Override - public void onList(final OfflineRegion[] offlineRegions) { - Pair, Map> offlineRegionInfo = null; - if (offlineRegions != null && offlineRegions.length > 0) { - offlineRegionInfo = OfflineMapHelper.getOfflineRegionInfo(offlineRegions); - } - setOfflineDownloadedMapNames(offlineRegionInfo, refreshDownloadedListOnly); - } - - @Override - public void onError(String error) { - Timber.e(TAG, "ERROR :: " + error); - } - }); - } - - public void setOfflineDownloadedMapNames(Pair, Map> offlineRegionInfo, boolean refreshDownloadedListOnly) { - downloadedOfflineMapsFragment = (DownloadedOfflineMapsFragment) adapter.getItem(DOWNLOADED_OFFLINE_MAPS_FRAGMENT_INDEX); - downloadedOfflineMapsFragment.setOfflineDownloadedMapNames(offlineRegionInfo); - - if (refreshDownloadedListOnly){ - return; - } - - availableOfflineMapsFragment = (AvailableOfflineMapsFragment) adapter.getItem(AVAILABLE_OFFLINE_MAPS_FRAGMENT_INDEX); - List regionNames = offlineRegionInfo != null ? offlineRegionInfo.first : null; - availableOfflineMapsFragment.setOfflineDownloadedMapNames(regionNames); - + public String getMapStyleAssetPath() { + return getString(R.string.reveal_offline_map_download_style); } } diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/SummaryFormsActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/SummaryFormsActivity.java index 18ae407561..99b485fb5a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/SummaryFormsActivity.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/SummaryFormsActivity.java @@ -3,12 +3,14 @@ import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; +import android.view.View; + import androidx.annotation.Nullable; -import com.google.android.material.tabs.TabLayout; -import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; -import android.view.View; +import androidx.viewpager.widget.ViewPager; + +import com.google.android.material.tabs.TabLayout; import org.json.JSONObject; import org.smartregister.family.adapter.ViewPagerAdapter; @@ -16,7 +18,7 @@ import org.smartregister.reveal.contract.OtherFormsContract; import org.smartregister.reveal.fragment.SummaryFormsFragment; import org.smartregister.reveal.presenter.OtherFormsPresenter; -import org.smartregister.reveal.util.RevealJsonFormUtils; +import org.smartregister.tasking.util.RevealJsonFormUtils; import timber.log.Timber; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/TaskRegisterActivity.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/view/TaskRegisterActivity.java deleted file mode 100644 index e6a24e4dd1..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/view/TaskRegisterActivity.java +++ /dev/null @@ -1,121 +0,0 @@ -package org.smartregister.reveal.view; - -import android.content.Intent; -import androidx.annotation.VisibleForTesting; -import androidx.fragment.app.Fragment; - -import android.view.View; - -import org.json.JSONObject; -import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.CaseClassificationContract; -import org.smartregister.reveal.contract.TaskRegisterContract; -import org.smartregister.reveal.fragment.CaseClassificationFragment; -import org.smartregister.reveal.fragment.TaskRegisterFragment; -import org.smartregister.reveal.model.BaseTaskDetails; -import org.smartregister.reveal.presenter.TaskRegisterPresenter; -import org.smartregister.reveal.util.Constants.Properties; -import org.smartregister.reveal.util.RevealJsonFormUtils; -import org.smartregister.view.activity.BaseRegisterActivity; -import org.smartregister.view.contract.BaseRegisterContract; -import org.smartregister.view.fragment.BaseRegisterFragment; - -import java.util.Collections; -import java.util.List; - -import timber.log.Timber; - -import static org.smartregister.reveal.util.Constants.JSON_FORM_PARAM_JSON; -import static org.smartregister.reveal.util.Constants.RequestCode.REQUEST_CODE_GET_JSON; -import static org.smartregister.reveal.util.Constants.TaskRegister; -import static org.smartregister.reveal.util.FamilyConstants.Intent.START_REGISTRATION; - -/** - * Created by samuelgithengi on 3/11/19. - */ -public class TaskRegisterActivity extends BaseRegisterActivity implements BaseRegisterContract.View { - - private RevealJsonFormUtils jsonFormUtils; - - private CaseClassificationFragment caseClassificationFragment = new CaseClassificationFragment(); - - @Override - protected void initializePresenter() { - presenter = new TaskRegisterPresenter(this); - } - - @Override - protected BaseRegisterFragment getRegisterFragment() { - jsonFormUtils = new RevealJsonFormUtils(); - TaskRegisterFragment fragment = new TaskRegisterFragment(); - fragment.setJsonFormUtils(jsonFormUtils); - return fragment; - } - - @Override - protected Fragment[] getOtherFragments() { - return new Fragment[]{caseClassificationFragment}; - } - - @Override - public void startFormActivity(String formName, String entityId, String metaData) {//not used - } - - @Override - public void startFormActivity(JSONObject jsonObject) { - jsonFormUtils.startJsonForm(jsonObject, this); - } - - @Override - protected void onActivityResultExtended(int requestCode, int resultCode, Intent data) { - if (requestCode == REQUEST_CODE_GET_JSON && resultCode == RESULT_OK && data.hasExtra(JSON_FORM_PARAM_JSON)) { - String json = data.getStringExtra(JSON_FORM_PARAM_JSON); - Timber.d(json); - getPresenter().saveJsonForm(json); - } else { - mBaseFragment.onActivityResult(requestCode, resultCode, data); - } - } - - - @Override - public List getViewIdentifiers() { - return Collections.singletonList(TaskRegister.VIEW_IDENTIFIER); - } - - @Override - public void startRegistration() {//not used on reveal/ adding points done on map - } - - @Override - protected void registerBottomNavigation() { - //not used for task register - findViewById(R.id.bottom_navigation).setVisibility(View.GONE); - } - - @VisibleForTesting - public TaskRegisterContract.Presenter getPresenter() { - return (TaskRegisterContract.Presenter) presenter; - } - - public void startFamilyRegistration(BaseTaskDetails taskDetails) { - Intent intent = new Intent(this, FamilyRegisterActivity.class); - intent.putExtra(START_REGISTRATION, true); - intent.putExtra(Properties.LOCATION_UUID, taskDetails.getStructureId()); - intent.putExtra(Properties.TASK_IDENTIFIER, taskDetails.getTaskId()); - intent.putExtra(Properties.TASK_BUSINESS_STATUS, taskDetails.getBusinessStatus()); - intent.putExtra(Properties.TASK_STATUS, taskDetails.getTaskStatus()); - startActivity(intent); - } - - public void displayIndexCaseFragment(JSONObject indexCase) { - ((CaseClassificationContract.View) caseClassificationFragment).displayIndexCase(indexCase); - switchToFragment(1); - } - - @Override - public boolean onSupportNavigateUp() { - switchToBaseFragment(); - return true; - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/AvailableOfflineMapViewHolder.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/AvailableOfflineMapViewHolder.java deleted file mode 100644 index 3368614abb..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/AvailableOfflineMapViewHolder.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.smartregister.reveal.viewholder; - -import androidx.annotation.NonNull; -import android.view.View; - -public class AvailableOfflineMapViewHolder extends BaseOfflineMapViewHolder { - - public AvailableOfflineMapViewHolder(@NonNull View itemView) { - super(itemView); - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/BaseOfflineMapViewHolder.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/BaseOfflineMapViewHolder.java deleted file mode 100644 index 8063f28813..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/BaseOfflineMapViewHolder.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.smartregister.reveal.viewholder; - -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; -import android.view.View; -import android.widget.CheckBox; -import android.widget.TextView; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.model.OfflineMapModel; - -/** - * Created by Richard Kareko on 2/10/20. - */ - -public class BaseOfflineMapViewHolder extends RecyclerView.ViewHolder { - - protected TextView tvOfflineMapNameLabel; - - protected TextView tvDownloadingLabel; - - protected CheckBox offlineMapCheckBox; - - public BaseOfflineMapViewHolder(@NonNull View itemView) { - super(itemView); - tvOfflineMapNameLabel = itemView.findViewById(R.id.offline_map_label); - tvDownloadingLabel = itemView.findViewById(R.id.downloading_label); - offlineMapCheckBox = itemView.findViewById(R.id.offline_map_checkbox); - } - - public void setOfflineMapLabel(String offlineMapLabel) { - this.tvOfflineMapNameLabel.setText(offlineMapLabel); - } - - public void setItemViewListener(OfflineMapModel offlineMapModel, View.OnClickListener onClickListener) { - offlineMapCheckBox.setOnClickListener(onClickListener); - offlineMapCheckBox.setTag(R.id.offline_map_checkbox, offlineMapModel); - } - - public void enableCheckBox(boolean enable) { - offlineMapCheckBox.setEnabled(enable); - } - - public void checkCheckBox(boolean check) { - offlineMapCheckBox.setChecked(check); - } - - public void displayDownloadingLabel(boolean displayDownloadingLabel) { - if (displayDownloadingLabel) { - tvDownloadingLabel.setVisibility(View.VISIBLE); - } else { - tvDownloadingLabel.setVisibility(View.GONE); - } - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/DownloadedOfflineMapViewHolder.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/DownloadedOfflineMapViewHolder.java deleted file mode 100644 index fd81913e73..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/DownloadedOfflineMapViewHolder.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.smartregister.reveal.viewholder; - -import androidx.annotation.NonNull; -import android.view.View; -import android.widget.TextView; - -import org.smartregister.reveal.R; - -public class DownloadedOfflineMapViewHolder extends BaseOfflineMapViewHolder { - - private TextView tvDownloadingLabel; - - - public DownloadedOfflineMapViewHolder(@NonNull View itemView) { - super(itemView); - tvDownloadingLabel = itemView.findViewById(R.id.downloading_label); - } - - public void setDownloadedMapSize(String offlineMapSize) { - this.tvDownloadingLabel.setText(offlineMapSize); - } - - - public void displayDownloadSizeLabel(boolean displayDownloadSizeLabel) { - if (displayDownloadSizeLabel) { - tvDownloadingLabel.setVisibility(View.VISIBLE); - } else { - tvDownloadingLabel.setVisibility(View.GONE); - } - } - -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/StructureTaskViewHolder.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/StructureTaskViewHolder.java index e66a8ac679..411eccafe3 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/StructureTaskViewHolder.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/StructureTaskViewHolder.java @@ -1,19 +1,20 @@ package org.smartregister.reveal.viewholder; import android.content.Context; -import androidx.annotation.NonNull; -import androidx.recyclerview.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + import org.apache.commons.lang3.StringUtils; import org.smartregister.reveal.R; -import org.smartregister.reveal.model.CardDetails; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.util.CardDetailsUtil; import org.smartregister.reveal.util.Constants.BusinessStatus; import org.smartregister.reveal.util.Constants.Intervention; +import org.smartregister.tasking.model.CardDetails; +import org.smartregister.tasking.util.CardDetailsUtil; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/TaskRegisterViewHolder.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/TaskRegisterViewHolder.java deleted file mode 100644 index 67d37d0ff5..0000000000 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/viewholder/TaskRegisterViewHolder.java +++ /dev/null @@ -1,198 +0,0 @@ -package org.smartregister.reveal.viewholder; - -import android.content.Context; -import android.graphics.drawable.Drawable; -import androidx.annotation.DrawableRes; -import androidx.annotation.NonNull; -import androidx.core.util.Pair; -import androidx.recyclerview.widget.RecyclerView; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; - -import org.smartregister.reveal.R; -import org.smartregister.reveal.model.CardDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.util.Constants; -import org.smartregister.reveal.util.PreferencesUtil; -import org.smartregister.reveal.util.Utils; - - -/** - * Created by samuelgithengi on 3/12/19. - */ -public class TaskRegisterViewHolder extends RecyclerView.ViewHolder { - - private Context context; - - private ImageView iconView; - - private TextView nameView; - - private TextView distanceView; - - private TextView actionView; - - private TextView taskDetailsView; - - private TextView houseNumberView; - - private PreferencesUtil prefsUtil = PreferencesUtil.getInstance(); - - public TaskRegisterViewHolder(@NonNull View itemView) { - super(itemView); - context = itemView.getContext(); - iconView = itemView.findViewById(R.id.task_icon); - nameView = itemView.findViewById(R.id.task_name); - distanceView = itemView.findViewById(R.id.distance_from_structure); - taskDetailsView = itemView.findViewById(R.id.task_details); - actionView = itemView.findViewById(R.id.task_action); - houseNumberView = itemView.findViewById(R.id.house_number); - } - - - public void setIcon(@DrawableRes int iconResource) { - iconView.setVisibility(View.VISIBLE); - iconView.setImageDrawable(context.getResources().getDrawable(iconResource)); - } - - public void setTaskName(String taskName) { - nameView.setText(taskName); - } - - public void setDistanceFromStructure(float distance, boolean distanceFromCenter) { - if (distanceFromCenter) { - distanceView.setText(context.getString( - R.string.distance_from_center, distance, prefsUtil.getCurrentOperationalArea())); - } else { - distanceView.setText(context.getString(R.string.distance_from_structure, distance)); - } - } - - public void hideDistanceFromStructure() { - distanceView.setVisibility(View.GONE); - } - - - /** - * Method that handles the populating of action view information on each row of the - * task register. - *

- * It handles the text and color displayed on an Action View. Also attaches a clickListener - * which handles clicks on the action view. - * - * @param actionLabel Text that shows what action to take when action view is clicked - * @param task TaskDetails object used to populate info in a particular row - * @param cardDetails Object that contains status, status message and status color - * @param onClickListener Click listener that handles clicks events on the Task Action - */ - public void setTaskAction(String actionLabel, TaskDetails task, CardDetails cardDetails, View.OnClickListener onClickListener) { - actionView.setText(actionLabel); - - // registered family with multiple tasks - if (cardDetails != null && task.getTaskCount() != null) { // task grouping only for FI - if (task.getTaskCount() > 1) { - if (task.getTaskCount() != task.getCompleteTaskCount()) { - - - Pair actionViewPair = getActionDrawable(task); - actionView.setTextColor(context.getResources().getColor(R.color.text_black)); - actionView.setBackground(actionViewPair.first); - actionView.setText(actionViewPair.second); - } else if (task.getTaskCount() == task.getCompleteTaskCount()) { - showTasksCompleteActionView(); - } - } - - } else if (cardDetails != null && cardDetails.getStatusColor() != null) { - actionView.setBackground(null); - actionView.setTextColor(context.getResources().getColor(cardDetails.getStatusColor())); - } else { - actionView.setBackground(context.getResources().getDrawable(R.drawable.task_action_bg)); - actionView.setTextColor(context.getResources().getColor(R.color.text_black)); - } - actionView.setOnClickListener(onClickListener); - actionView.setTag(R.id.task_details, task); - } - - public void setItemViewListener(TaskDetails task, View.OnClickListener onClickListener) { - itemView.setOnClickListener(onClickListener); - itemView.setTag(R.id.task_details, task); - } - - public void setTaskDetails(String businessStatus, String taskDetails) { - if (Constants.BusinessStatus.NOT_SPRAYED.equals(businessStatus)) { - taskDetailsView.setVisibility(View.VISIBLE); - taskDetailsView.setText(context.getString(R.string.task_reason, taskDetails)); - } else { - taskDetailsView.setVisibility(View.GONE); - } - } - - public void setHouseNumber(String houseNumber) { - houseNumberView.setText(houseNumber); - } - - public void showHouseNumber() { - houseNumberView.setVisibility(View.VISIBLE); - } - public void hideHouseNumber() { - houseNumberView.setVisibility(View.GONE); - } - - public void hideIcon() { - iconView.setVisibility(View.GONE); - } - - private void showTasksCompleteActionView() { - if (Utils.isFocusInvestigation()) { - actionView.setBackground(context.getResources().getDrawable(R.drawable.tasks_complete_bg)); - } else if (Utils.isMDA()){ - actionView.setBackground(context.getResources().getDrawable(R.drawable.mda_adhered_bg)); - } - actionView.setTextColor(context.getResources().getColor(R.color.text_black)); - actionView.setText(context.getText(R.string.tasks_complete)); - } - - private Pair getActionDrawable(TaskDetails task) { - // The assumption is that a register structure task always exists if the structure has - // atleast one bednet distribution or blood screening task - boolean familyRegTaskMissingOrFamilyRegComplete = task.isFamilyRegistered() || !task.isFamilyRegTaskExists(); - Drawable actionBg = null; - String actionText = context.getText(R.string.view_tasks).toString(); - - if (Utils.isFocusInvestigation()) { - if (familyRegTaskMissingOrFamilyRegComplete && task.isBednetDistributed() && task.isBloodScreeningDone()) { - actionBg = context.getResources().getDrawable(R.drawable.tasks_complete_bg); - actionText = context.getText(R.string.tasks_complete).toString(); - } else if (familyRegTaskMissingOrFamilyRegComplete && !task.isBednetDistributed() && !task.isBloodScreeningDone()) { - actionBg = context.getResources().getDrawable(R.drawable.family_registered_bg); - } else if (familyRegTaskMissingOrFamilyRegComplete && task.isBednetDistributed()) { - actionBg = context.getResources().getDrawable(R.drawable.bednet_distributed_bg); - } else if (task.isBloodScreeningDone()) { - actionBg = context.getResources().getDrawable(R.drawable.blood_screening_complete_bg); - } else { - actionBg = context.getResources().getDrawable(R.drawable.no_task_complete_bg); - } - } else if (Utils.isMDA()) { - if (familyRegTaskMissingOrFamilyRegComplete && task.isMdaAdhered()) { - actionBg = context.getResources().getDrawable(R.drawable.mda_adhered_bg); - actionText = context.getText(R.string.tasks_complete).toString(); - } else if (familyRegTaskMissingOrFamilyRegComplete && task.isFullyReceived()) { - actionBg = context.getResources().getDrawable(R.drawable.mda_dispensed_bg); - } else if (familyRegTaskMissingOrFamilyRegComplete && task.isPartiallyReceived()) { - actionBg = context.getResources().getDrawable(R.drawable.mda_partially_received_bg); - } else if (familyRegTaskMissingOrFamilyRegComplete && task.isNoneReceived()) { - actionBg = context.getResources().getDrawable(R.drawable.mda_none_received_bg); - } else if (familyRegTaskMissingOrFamilyRegComplete && task.isNotEligible()) { - actionBg = context.getResources().getDrawable(R.drawable.mda_not_eligible_bg); - } else if (familyRegTaskMissingOrFamilyRegComplete) { - actionBg = context.getResources().getDrawable(R.drawable.family_registered_bg); - } else { - actionBg = context.getResources().getDrawable(R.drawable.no_task_complete_bg); - } - } - - return new Pair<>(actionBg, actionText); - } -} diff --git a/opensrp-reveal/src/main/java/org/smartregister/reveal/widget/GeoWidgetFactory.java b/opensrp-reveal/src/main/java/org/smartregister/reveal/widget/GeoWidgetFactory.java index 335b28484a..72b1868c3a 100644 --- a/opensrp-reveal/src/main/java/org/smartregister/reveal/widget/GeoWidgetFactory.java +++ b/opensrp-reveal/src/main/java/org/smartregister/reveal/widget/GeoWidgetFactory.java @@ -5,7 +5,6 @@ import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; -import androidx.annotation.NonNull; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; @@ -15,6 +14,8 @@ import android.widget.LinearLayout; import android.widget.Toast; +import androidx.annotation.NonNull; + import com.cocoahero.android.geojson.Feature; import com.cocoahero.android.geojson.Point; import com.mapbox.android.core.permissions.PermissionsManager; @@ -47,12 +48,12 @@ import org.smartregister.reveal.BuildConfig; import org.smartregister.reveal.R; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.util.AlertDialogUtils; import org.smartregister.reveal.util.Constants.Map; import org.smartregister.reveal.util.RevealMapHelper; import org.smartregister.reveal.validators.MinZoomValidator; import org.smartregister.reveal.validators.WithinOperationAreaValidator; import org.smartregister.reveal.view.RevealMapView; +import org.smartregister.tasking.util.AlertDialogUtils; import org.smartregister.util.AssetHandler; import org.smartregister.util.Utils; @@ -69,8 +70,8 @@ import static android.content.DialogInterface.BUTTON_POSITIVE; import static org.smartregister.reveal.util.Constants.JsonForm.LOCATION_COMPONENT_ACTIVE; import static org.smartregister.reveal.util.Constants.JsonForm.OPERATIONAL_AREA_TAG; -import static org.smartregister.reveal.util.Utils.getLocationBuffer; -import static org.smartregister.reveal.util.Utils.getPixelsPerDPI; +import static org.smartregister.tasking.util.Utils.getLocationBuffer; +import static org.smartregister.tasking.util.Utils.getPixelsPerDPI; /** * Created by samuelgithengi on 12/13/18. diff --git a/opensrp-reveal/src/main/res/layout/activity_filter_tasks.xml b/opensrp-reveal/src/main/res/layout/activity_filter_tasks.xml deleted file mode 100644 index 11ecc0156f..0000000000 --- a/opensrp-reveal/src/main/res/layout/activity_filter_tasks.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/TestRevealApplication.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/TestRevealApplication.java index d3e63a329b..2c15d668e4 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/TestRevealApplication.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/TestRevealApplication.java @@ -11,7 +11,7 @@ import org.smartregister.family.FamilyLibrary; import org.smartregister.repository.Repository; import org.smartregister.reveal.application.RevealApplication; -import org.smartregister.reveal.util.AppExecutors; +import org.smartregister.util.AppExecutors; import java.util.concurrent.Executors; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/ListTaskInteractorPowerMockTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/ListTaskInteractorPowerMockTest.java index 9a3013ac04..269ae63902 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/ListTaskInteractorPowerMockTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/ListTaskInteractorPowerMockTest.java @@ -14,8 +14,8 @@ import org.powermock.reflect.Whitebox; import org.smartregister.reveal.model.MosquitoHarvestCardDetails; import org.smartregister.reveal.model.SprayCardDetails; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.CardDetailsUtil; +import org.smartregister.util.AppExecutors; import java.util.concurrent.Executor; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractorTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractorTest.java index 47688c7845..d97e6df4dc 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractorTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyProfileInteractorTest.java @@ -29,13 +29,13 @@ import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.contract.FamilyProfileContract; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.FamilyConstants.EventType; import org.smartregister.reveal.util.FamilyConstants.TABLE_NAME; -import org.smartregister.reveal.util.InteractorUtils; import org.smartregister.reveal.util.TaskUtils; import org.smartregister.reveal.util.TestingUtils; import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.util.AppExecutors; import java.util.ArrayList; import java.util.Arrays; @@ -47,9 +47,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -123,7 +123,6 @@ public void testGenerateTasks() { String baseEntityId = UUID.randomUUID().toString(); String structureId = UUID.randomUUID().toString(); interactor.generateTasks(context, baseEntityId, structureId); - verify(taskUtils, timeout(ASYNC_TIMEOUT)).generateBloodScreeningTask(context, baseEntityId, structureId); verify(presenter, timeout(ASYNC_TIMEOUT)).onTasksGenerated(); } @@ -209,7 +208,6 @@ public void testArchiveFamily() { when(commonRepository.findSearchIds(anyString())).thenReturn(familyMembers); Task task = TestingUtils.getTask(structureId); - when(taskUtils.generateRegisterFamilyTask(any(), any())).thenReturn(task); interactor.archiveFamily(familyId, structureId); for (String familyMember : new ArrayList<>(familyMembers)) @@ -218,8 +216,7 @@ public void testArchiveFamily() { verify(taskRepository, timeout(ASYNC_TIMEOUT)).archiveTasksForEntity(structureId); verify(taskRepository, timeout(ASYNC_TIMEOUT)).cancelTasksForEntity(structureId); - verify(taskUtils, timeout(ASYNC_TIMEOUT)).generateRegisterFamilyTask(any(), eq(structureId)); - verify(presenter, timeout(ASYNC_TIMEOUT)).onArchiveFamilyCompleted(true, task); + verify(presenter, timeout(ASYNC_TIMEOUT)).onArchiveFamilyCompleted(eq(true), nullable(Task.class)); } diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractorTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractorTest.java index d1532663d3..0ff82aa6ea 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractorTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/RevealFamilyRegisterInteractorTest.java @@ -17,9 +17,9 @@ import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.contract.FamilyRegisterContract; import org.smartregister.reveal.sync.RevealClientProcessor; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.TaskUtils; import org.smartregister.sync.ClientProcessorForJava; +import org.smartregister.util.AppExecutors; import java.util.ArrayList; import java.util.Collections; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StatsFragmentInteractorTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StatsFragmentInteractorTest.java index 5815a06b22..660fe6b949 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StatsFragmentInteractorTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StatsFragmentInteractorTest.java @@ -16,7 +16,7 @@ import org.smartregister.repository.BaseRepository; import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.presenter.StatsFragmentPresenter; -import org.smartregister.reveal.util.AppExecutors; +import org.smartregister.util.AppExecutors; import java.util.Map; import java.util.concurrent.Executors; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StructureTasksInteractorTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StructureTasksInteractorTest.java index f4c08a2ba5..53b1e63e59 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StructureTasksInteractorTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/StructureTasksInteractorTest.java @@ -14,19 +14,19 @@ import org.mockito.junit.MockitoRule; import org.powermock.reflect.Whitebox; import org.robolectric.RuntimeEnvironment; +import org.smartregister.domain.Event; import org.smartregister.domain.Location; import org.smartregister.domain.Task; -import org.smartregister.domain.Event; import org.smartregister.repository.EventClientRepository; import org.smartregister.repository.StructureRepository; import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.contract.StructureTasksContract; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.util.AppExecutors; import org.smartregister.reveal.util.Constants.BusinessStatus; import org.smartregister.reveal.util.Constants.Intervention; -import org.smartregister.reveal.util.InteractorUtils; import org.smartregister.reveal.util.TestingUtils; +import org.smartregister.tasking.util.InteractorUtils; +import org.smartregister.util.AppExecutors; import org.smartregister.util.JsonFormUtils; import java.util.List; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/TaskRegisterInteractorTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/TaskRegisterInteractorTest.java index 7e6eebb857..e9a9a0fdbd 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/TaskRegisterInteractorTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/interactor/TaskRegisterInteractorTest.java @@ -9,8 +9,9 @@ import org.powermock.reflect.Whitebox; import org.smartregister.configurableviews.helper.ConfigurableViewsHelper; import org.smartregister.reveal.BaseUnitTest; -import org.smartregister.reveal.contract.BaseContract; import org.smartregister.reveal.util.Constants; +import org.smartregister.tasking.contract.BaseContract; +import org.smartregister.tasking.interactor.TaskRegisterInteractor; import java.util.Collections; import java.util.List; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/presenter/FormFragmentPresenterTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/presenter/FormFragmentPresenterTest.java index cf2bb4ba42..8648503c54 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/presenter/FormFragmentPresenterTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/presenter/FormFragmentPresenterTest.java @@ -1,8 +1,9 @@ package org.smartregister.reveal.presenter; import android.content.Context; -import androidx.core.util.Pair; + import androidx.appcompat.app.AlertDialog; +import androidx.core.util.Pair; import com.mapbox.mapboxsdk.geometry.LatLng; @@ -22,14 +23,15 @@ import org.smartregister.domain.Location; import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.R; -import org.smartregister.reveal.contract.BaseFormFragmentContract; -import org.smartregister.reveal.interactor.BaseFormFragmentInteractor; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.repository.RevealMappingHelper; import org.smartregister.reveal.util.Constants; import org.smartregister.reveal.util.RevealJsonFormUtils; import org.smartregister.reveal.util.TestingUtils; +import org.smartregister.tasking.contract.BaseFormFragmentContract; +import org.smartregister.tasking.interactor.BaseFormFragmentInteractor; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.presenter.BaseFormFragmentPresenter; +import org.smartregister.tasking.repository.RevealMappingHelper; import org.smartregister.util.AssetHandler; import org.smartregister.util.JsonFormUtils; diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/sync/RevealClientProcessorPowerMockTest.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/sync/RevealClientProcessorPowerMockTest.java index 18b41dd6e1..893d36168f 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/sync/RevealClientProcessorPowerMockTest.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/sync/RevealClientProcessorPowerMockTest.java @@ -10,12 +10,12 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; +import org.smartregister.domain.Event; import org.smartregister.domain.Location; import org.smartregister.domain.LocationProperty; +import org.smartregister.domain.Obs; import org.smartregister.domain.Task; -import org.smartregister.domain.Event; import org.smartregister.domain.db.EventClient; -import org.smartregister.domain.Obs; import org.smartregister.domain.jsonmapping.ClientClassification; import org.smartregister.repository.BaseRepository; import org.smartregister.repository.EventClientRepository; @@ -24,8 +24,9 @@ import org.smartregister.reveal.application.RevealApplication; import org.smartregister.reveal.util.Constants; import org.smartregister.reveal.util.Constants.JsonForm; -import org.smartregister.reveal.util.PreferencesUtil; import org.smartregister.reveal.util.Utils; +import org.smartregister.tasking.util.PreferencesUtil; +import org.smartregister.util.AppExecutors; import java.util.ArrayList; import java.util.Collections; @@ -74,6 +75,7 @@ public class RevealClientProcessorPowerMockTest { @Before public void setUp() { clientProcessor = spy(Whitebox.newInstance(RevealClientProcessor.class)); + Whitebox.setInternalState(clientProcessor, "appExecutors", new AppExecutors()); } @Test @@ -220,7 +222,7 @@ private void mockStaticMethods() { PowerMockito.when(preferencesUtil.getCurrentOperationalArea()).thenReturn(""); PowerMockito.when(PreferencesUtil.getInstance()).thenReturn(preferencesUtil); - PowerMockito.when(Utils.getOperationalAreaLocation(anyString())).thenReturn(new Location()); + PowerMockito.when(org.smartregister.tasking.util.Utils.getOperationalAreaLocation(anyString())).thenReturn(new Location()); } private void mockRepositories() { diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TaskUtilsTests.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TaskUtilsTests.java index fcd4e2305b..dda25284e2 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TaskUtilsTests.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TaskUtilsTests.java @@ -18,39 +18,28 @@ import org.smartregister.clientandeventmodel.Event; import org.smartregister.domain.Location; import org.smartregister.domain.Task; -import org.smartregister.repository.BaseRepository; import org.smartregister.repository.TaskRepository; import org.smartregister.reveal.BaseUnitTest; import org.smartregister.reveal.BuildConfig; -import org.smartregister.reveal.R; import org.smartregister.reveal.model.TaskDetails; import org.smartregister.util.Cache; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.UUID; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.when; import static org.smartregister.domain.Task.TaskStatus.READY; import static org.smartregister.repository.BaseRepository.TYPE_Unsynced; import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_VISITED; -import static org.smartregister.reveal.util.Constants.Intervention.BEDNET_DISTRIBUTION; -import static org.smartregister.reveal.util.Constants.Intervention.BLOOD_SCREENING; import static org.smartregister.reveal.util.Constants.Intervention.CASE_CONFIRMATION; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_ADHERENCE; -import static org.smartregister.reveal.util.Constants.Intervention.MDA_DISPENSE; -import static org.smartregister.reveal.util.Constants.Intervention.REGISTER_FAMILY; /** * Created by Richard Kareko on 2/17/20. @@ -136,118 +125,6 @@ public void testResetTask() { } - @Test - public void testGenerateTask() { - - String expectedBusinessStatus = NOT_VISITED; - String expectedIntervention = BEDNET_DISTRIBUTION; - int expectedDescription = R.string.bednet_distribution_description; - - Task actualTask = taskUtils.generateTask(context, expectedEntityId, expectedStructureId, expectedBusinessStatus, expectedIntervention, expectedDescription); - - assertEquals(expectedEntityId, actualTask.getForEntity()); - assertEquals(expectedStructureId, actualTask.getStructureId()); - assertEquals(expectedIntervention, actualTask.getCode()); - assertEquals(expectedBusinessStatus, actualTask.getBusinessStatus()); - assertEquals(context.getString(expectedDescription), actualTask.getDescription()); - assertNotNull(actualTask.getIdentifier()); - assertEquals(3, actualTask.getPriority()); - assertNotNull(actualTask.getExecutionStartDate()); - assertNotNull(actualTask.getAuthoredOn()); - assertNotNull(actualTask.getLastModified()); - assertEquals(BaseRepository.TYPE_Created, actualTask.getSyncStatus()); - - } - - @Test - public void testGenerateRegisterFamilyTask() { - - taskUtils = spy(taskUtils); - - taskUtils.generateRegisterFamilyTask(context, expectedEntityId); - - verify(taskUtils).generateTask(eq(context), stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); - - Iterator iterator = stringArgumentCaptor.getAllValues().iterator(); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(NOT_VISITED, iterator.next()); - assertEquals(REGISTER_FAMILY, iterator.next()); - assertEquals(R.string.register_family_description, integerArgumentCaptor.getValue().intValue()); - } - - @Test - public void testGenerateBloodScreeningTask() { - - taskUtils = spy(taskUtils); - - taskUtils.generateBloodScreeningTask(context, expectedEntityId, expectedStructureId); - - verify(taskUtils).generateTask(eq(context), stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); - - Iterator iterator = stringArgumentCaptor.getAllValues().iterator(); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(expectedStructureId, iterator.next()); - assertEquals(NOT_VISITED, iterator.next()); - assertEquals(BLOOD_SCREENING, iterator.next()); - assertEquals(R.string.blood_screening_description, integerArgumentCaptor.getValue().intValue()); - } - - @Test - public void testGenerateBednetDistributionTask() { - - taskUtils = spy(taskUtils); - - taskUtils.generateBedNetDistributionTask(context, expectedEntityId); - - verify(taskUtils).generateTask(eq(context), stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); - - Iterator iterator = stringArgumentCaptor.getAllValues().iterator(); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(NOT_VISITED, iterator.next()); - assertEquals(BEDNET_DISTRIBUTION, iterator.next()); - assertEquals(R.string.bednet_distribution_description, integerArgumentCaptor.getValue().intValue()); - } - - @Test - public void testGenerateMDADispenceTask() { - - taskUtils = spy(taskUtils); - - taskUtils.generateMDADispenseTask(context, expectedEntityId, expectedStructureId); - - verify(taskUtils).generateTask(eq(context), stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); - - Iterator iterator = stringArgumentCaptor.getAllValues().iterator(); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(expectedStructureId, iterator.next()); - assertEquals(NOT_VISITED, iterator.next()); - assertEquals(MDA_DISPENSE, iterator.next()); - assertEquals(R.string.mda_dispense_desciption, integerArgumentCaptor.getValue().intValue()); - } - - @Test - public void testGenerateMDAAdherenceTask() { - - taskUtils = spy(taskUtils); - - taskUtils.generateMDAAdherenceTask(context, expectedEntityId, expectedStructureId); - - verify(taskUtils).generateTask(eq(context), stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), integerArgumentCaptor.capture()); - - Iterator iterator = stringArgumentCaptor.getAllValues().iterator(); - assertEquals(expectedEntityId, iterator.next()); - assertEquals(expectedStructureId, iterator.next()); - assertEquals(NOT_VISITED, iterator.next()); - assertEquals(MDA_ADHERENCE, iterator.next()); - assertEquals(R.string.mda_adherence_desciption, integerArgumentCaptor.getValue().intValue()); - } @Test public void testTagEventTaskdetails() { diff --git a/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TestingUtils.java b/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TestingUtils.java index 230b032c7b..9c62153374 100644 --- a/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TestingUtils.java +++ b/opensrp-reveal/src/test/java/org/smartregister/reveal/util/TestingUtils.java @@ -1,6 +1,7 @@ package org.smartregister.reveal.util; import android.location.Location; + import androidx.core.util.Pair; import com.google.gson.Gson; @@ -17,13 +18,13 @@ import org.smartregister.domain.Task; import org.smartregister.domain.Task.TaskStatus; import org.smartregister.domain.form.FormLocation; -import org.smartregister.reveal.model.OfflineMapModel; import org.smartregister.reveal.model.StructureTaskDetails; -import org.smartregister.reveal.model.TaskDetails; -import org.smartregister.reveal.model.TaskFilterParams; import org.smartregister.reveal.util.Constants.BusinessStatus; import org.smartregister.reveal.util.Constants.Intervention; import org.smartregister.reveal.util.Constants.InterventionType; +import org.smartregister.tasking.model.OfflineMapModel; +import org.smartregister.tasking.model.TaskDetails; +import org.smartregister.tasking.model.TaskFilterParams; import org.smartregister.util.DateTimeTypeConverter; import java.util.ArrayList; @@ -40,7 +41,6 @@ import static io.ona.kujaku.downloaders.MapBoxOfflineResourcesDownloader.METADATA_JSON_FIELD_REGION_NAME; import static org.smartregister.family.util.DBConstants.KEY; -import static org.smartregister.reveal.model.OfflineMapModel.OfflineMapStatus.DOWNLOADED; import static org.smartregister.reveal.util.Constants.BusinessStatus.NOT_VISITED; import static org.smartregister.reveal.util.Constants.DatabaseKeys.BUSINESS_STATUS; import static org.smartregister.reveal.util.Constants.DatabaseKeys.CODE; @@ -135,7 +135,7 @@ public static MatrixCursor getTaskCursor(Task task ) { public static OfflineMapModel getOfflineMapModel() { OfflineMapModel model = new OfflineMapModel(); - model.setOfflineMapStatus(DOWNLOADED); + model.setOfflineMapStatus(OfflineMapModel.OfflineMapStatus.DOWNLOADED); model.setLocation(TestingUtils.gson.fromJson(TestingUtils.operationalAreaGeoJSON, org.smartregister.domain.Location.class)); return model; }