Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assign child's origin facility id to OOC vaccine events #331

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION_NAME=1.0.1-SNAPSHOT
VERSION_NAME=1.0.2-SNAPSHOT
VERSION_CODE=1
GROUP=org.smartregister
POM_SETTING_DESCRIPTION=OpenSRP Client Child Library
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1533,7 +1533,22 @@ private void saveVaccine(VaccineRepository vaccineRepository, VaccineWrapper tag
vaccine.setName(tag.getName());
vaccine.setDate(tag.getUpdatedVaccineDate().toDate());
vaccine.setAnmId(getOpenSRPContext().allSharedPreferences().fetchRegisteredANM());
vaccine.setLocationId(ChildJsonFormUtils.getProviderLocationId(this));

// Assign Location Id as per the child's home facility
if (Utils.childBelongsToCurrentFacility(getChildDetails().getColumnmaps())) {
vaccine.setLocationId(ChildJsonFormUtils.getProviderLocationId(this));
} else if (Utils.isChildTemporaryOOC(childDetails.getColumnmaps())) {
String locationId = Utils.getLocationIdFromChildTempOOCEvent(vaccine.getBaseEntityId());
if (StringUtils.isEmpty(locationId)) // Pickup current faciilty id
locationId = ChildJsonFormUtils.getProviderLocationId(this);
vaccine.setLocationId(locationId);
} else {
String locationId = childDetails.getColumnmaps().get(AllConstants.LOCATION_ID);
if (StringUtils.isEmpty(locationId))
locationId = ChildJsonFormUtils.getProviderLocationId(this);
vaccine.setLocationId(locationId);
}

vaccine.setChildLocationId(ChildJsonFormUtils.getChildLocationId(getOpenSRPContext().allSharedPreferences().fetchDefaultLocalityId(vaccine.getAnmId()), getOpenSRPContext().allSharedPreferences()));

String lastChar = vaccine.getName().substring(vaccine.getName().length() - 1);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package org.smartregister.child.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
Expand Down Expand Up @@ -75,21 +77,6 @@ public abstract class BaseAdvancedSearchFragment extends BaseChildRegisterFragme
implements ChildAdvancedSearchContract.View, ChildRegisterFragmentContract.View, View.OnClickListener {
public static final String START_DATE = "start_date";
public static final String END_DATE = "end_date";
private final Listener<MoveToCatchmentEvent> moveToMyCatchmentListener = moveToCatchmentEvent -> {
if (moveToCatchmentEvent != null) {
if (ChildJsonFormUtils.processMoveToCatchment(context(), moveToCatchmentEvent)) {
clientAdapter.notifyDataSetChanged();
((BaseRegisterActivity) requireActivity()).refreshList(FetchStatus.fetched);
((BaseRegisterActivity) requireActivity()).switchToBaseFragment();

Utils.showToast(requireActivity(), requireActivity().getString(R.string.move_to_catchment_success_message));
} else {
Utils.showShortToast(requireActivity(), requireActivity().getString(R.string.an_error_occured));
}
} else {
Utils.showShortToast(requireActivity(), requireActivity().getString(R.string.unable_to_move_to_my_catchment));
}
};
protected AdvancedSearchTextWatcher advancedSearchTextwatcher = new AdvancedSearchTextWatcher();
protected HashMap<String, String> searchFormData = new HashMap<>();
protected CheckBox active;
Expand Down Expand Up @@ -117,19 +104,53 @@ public abstract class BaseAdvancedSearchFragment extends BaseChildRegisterFragme
private AdvanceSearchDatePickerDialog endDateDatePicker;
private final SimpleDateFormat dateFormatter = new SimpleDateFormat(FormUtils.NATIIVE_FORM_DATE_FORMAT_PATTERN,
Locale.getDefault().toString().startsWith("ar") ? Locale.ENGLISH : Locale.getDefault());
@SuppressLint("StaticFieldLeak")
private final Listener<MoveToCatchmentEvent> moveToMyCatchmentListener = moveToCatchmentEvent -> {
if (moveToCatchmentEvent != null) {
org.smartregister.util.Utils.startAsyncTask(new AsyncTask<MoveToCatchmentEvent, Void, Boolean>() {

@Override
protected Boolean doInBackground(MoveToCatchmentEvent... moveToCatchmentEvents) {
return ChildJsonFormUtils.processMoveToCatchment(context(), moveToCatchmentEvents[0]);
}

@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
hideProgressDialog();
if (result) {
clientAdapter.notifyDataSetChanged();
((BaseRegisterActivity) requireActivity()).refreshList(FetchStatus.fetched);
((BaseRegisterActivity) requireActivity()).switchToBaseFragment();

Utils.showToast(requireActivity(), requireActivity().getString(R.string.move_to_catchment_success_message));
} else {
Utils.showShortToast(requireActivity(), requireActivity().getString(R.string.an_error_occured));
}
}
}, new MoveToCatchmentEvent[]{moveToCatchmentEvent});
} else {
hideProgressDialog();
Utils.showShortToast(requireActivity(), requireActivity().getString(R.string.unable_to_move_to_my_catchment));
}
};

@Override
protected void initializePresenter() {
presenter = getPresenter();
initProgressDialog();

}

private void initProgressDialog() {
progressDialog = new ProgressDialog(requireActivity());
progressDialog.setCancelable(false);
}

private void hideProgressDialog() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
}

protected abstract BaseChildAdvancedSearchPresenter getPresenter();

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -570,4 +570,4 @@ public int getOverDueCount() {
public void setOverDueCount(int overDueCount) {
this.overDueCount = overDueCount;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1798,6 +1798,7 @@ public static boolean processMoveToCatchment(org.smartregister.Context openSRPCo
String teamId = allSharedPreferences.fetchDefaultTeamId(providerId);
String locationId = allSharedPreferences.fetchUserLocalityId(providerId);

String fromLocationId = ""; // SAve Child's origin location
for (int i = 0; i < clients.length(); i++) {
JSONObject client = clients.getJSONObject(i);

Expand All @@ -1808,6 +1809,7 @@ public static boolean processMoveToCatchment(org.smartregister.Context openSRPCo
}

client.put("teamId", teamId);
fromLocationId = client.getString("locationId");
client.put("locationId", locationId);
}

Expand All @@ -1823,7 +1825,7 @@ public static boolean processMoveToCatchment(org.smartregister.Context openSRPCo
processMoveToCatchmentPermanent(openSRPContext.applicationContext(), openSRPContext.allSharedPreferences(), eventPairList);
processTriggerClientProcessorAndUpdateFTS(openSRPContext, clients);
} else {
processMoveToCatchmentTemporary(openSRPContext, events, clients, moveToCatchmentEvent.isCreateEvent());
processMoveToCatchmentTemporary(openSRPContext, events, clients, moveToCatchmentEvent.isCreateEvent(), fromLocationId);
}

return true;
Expand All @@ -1848,9 +1850,9 @@ private static void processTriggerClientProcessorAndUpdateFTS(org.smartregister.
Timber.i("Moved %s client(s) to new catchment area.", clientIds.size());
}

public static void processMoveToCatchmentTemporary(org.smartregister.Context opensrpContext, JSONArray events, JSONArray clients, boolean createEvent) throws Exception {
public static void processMoveToCatchmentTemporary(org.smartregister.Context opensrpContext, JSONArray events, JSONArray clients, boolean createEvent, String fromLocationId) throws Exception {
if (createEvent) {
Event moveToCatchmentSyncEvent = createMoveToCatchmentSyncEvent(opensrpContext, clients);
Event moveToCatchmentSyncEvent = createMoveToCatchmentSyncEvent(opensrpContext, clients, fromLocationId);

convertAndPersistEvent(moveToCatchmentSyncEvent);
}
Expand Down Expand Up @@ -2063,7 +2065,7 @@ public static Event createMoveToCatchmentEvent(Context context, Identifiers toId
}
}

public static Event createMoveToCatchmentSyncEvent(org.smartregister.Context opensrpContext, JSONArray clientList) {
public static Event createMoveToCatchmentSyncEvent(org.smartregister.Context opensrpContext, JSONArray clientList, String fromLocationId) {
try {

if (clientList == null) {
Expand All @@ -2086,6 +2088,14 @@ public static Event createMoveToCatchmentSyncEvent(org.smartregister.Context ope
}

event.addObs(new Obs(FORM_SUBMISSION_FIELD, DATA_TYPE, MoveToMyCatchmentUtils.MOVE_TO_CATCHMENT_IDENTIFIERS_FORM_FIELD, "", val, new ArrayList<>(), null, MoveToMyCatchmentUtils.MOVE_TO_CATCHMENT_IDENTIFIERS_FORM_FIELD));

// Add info for origin's location Id
String formSubmissionField = "From_LocationId";
List<Object> vall = new ArrayList<>();
vall.add(fromLocationId);
event.addObs(new Obs(FORM_SUBMISSION_FIELD, DATA_TYPE, formSubmissionField, "", vall, new ArrayList<>(), null,
formSubmissionField));

event.setBaseEntityId(clientBaseEntityId);

addMetaData(opensrpContext.applicationContext(), event, new Date());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ protected MoveToCatchmentEvent doInBackground(Void... params) {
@Override
protected void onPostExecute(MoveToCatchmentEvent result) {
listener.onEvent(result);
progressDialog.dismiss();
}
}, null);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.smartregister.child.util;

import static org.smartregister.child.util.MoveToMyCatchmentUtils.MOVE_TO_CATCHMENT_SYNC_EVENT;
import static org.smartregister.immunization.util.VaccinatorUtils.translate;

import android.app.Activity;
Expand Down Expand Up @@ -53,6 +54,7 @@
import org.smartregister.commonregistry.CommonPersonObject;
import org.smartregister.commonregistry.CommonPersonObjectClient;
import org.smartregister.commonregistry.CommonRepository;
import org.smartregister.domain.db.EventClient;
import org.smartregister.domain.tag.FormTag;
import org.smartregister.growthmonitoring.domain.Height;
import org.smartregister.growthmonitoring.domain.HeightWrapper;
Expand All @@ -69,6 +71,7 @@
import org.smartregister.immunization.service.intent.VaccineIntentService;
import org.smartregister.repository.AllSharedPreferences;
import org.smartregister.repository.BaseRepository;
import org.smartregister.repository.EventClientRepository;
import org.smartregister.repository.UniqueIdRepository;

import java.text.DateFormat;
Expand Down Expand Up @@ -780,6 +783,41 @@ public static boolean isChildHasNFCCard(Map<String, String> detailsMap) {
&& !Constants.TRUE.equalsIgnoreCase(detailsMap.getOrDefault(Constants.KEY.NFC_CARD_BLACKLISTED, Constants.FALSE));
}

public static boolean childBelongsToCurrentFacility(@NotNull Map<String, String> childDetails) {
String caseId = childDetails.get(DBConstants.KEY.BASE_ENTITY_ID);
CommonPersonObjectClient client = ChildDbUtils.fetchCommonPersonObjectClientByBaseEntityId(caseId);

String outOfArea = getValue(childDetails, Constants.Client.IS_OUT_OF_CATCHMENT, false);
return client != null && (Constants.FALSE.equalsIgnoreCase(outOfArea) || StringUtils.isEmpty(outOfArea));
}

public static boolean isChildTemporaryOOC(@NotNull Map<String, String> childDetails) {
return !childBelongsToCurrentFacility(childDetails) && (ChildLibrary.getInstance()
.getProperties().isTrue(ChildAppProperties.KEY.NOVEL.OUT_OF_CATCHMENT)
&& Boolean.parseBoolean(org.smartregister.util.Utils.getValue(childDetails, Constants.Client.IS_OUT_OF_CATCHMENT, false)));
}

public static String getLocationIdFromChildTempOOCEvent(String baseEntityId) {
EventClientRepository eventClientRepository = ChildLibrary.getInstance().eventClientRepository();
String query = "SELECT "+ EventClientRepository.event_column.json.name() +" FROM "
+ EventClientRepository.Table.event.name()
+ " WHERE "
+ "eventType = '"+ MOVE_TO_CATCHMENT_SYNC_EVENT +"' "
+ "AND baseEntityId = '"+ baseEntityId +"' "
+ "ORDER BY "+EventClientRepository.event_column.dateCreated.name()+" DESC LIMIT 1";
List<EventClient> moveToCatchmentSyncEventClient = eventClientRepository.fetchEventClientsCore(query, null);
org.smartregister.domain.Event moveToCatchmentSyncEvent = moveToCatchmentSyncEventClient.get(0).getEvent();
String locationId = "";
for (int i = moveToCatchmentSyncEvent.getObs().size() - 1; i > -1; i--) {
org.smartregister.domain.Obs obs = moveToCatchmentSyncEvent.getObs().get(i);

if (obs != null && "From_LocationId".equals(obs.getFormSubmissionField())) {
locationId = (String) obs.getValues().get(0);
}
}
return locationId;
}

public static boolean hasCompassRelationshipId(Map<String, String> detailsMap) {
return StringUtils.isNotBlank(detailsMap.get(DBConstants.KEY.MOTHER_COMPASS_RELATIONSHIP_ID));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package org.smartregister.child.utils;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;

import android.app.Activity;
import android.graphics.Typeface;
import android.view.View;
Expand All @@ -11,6 +15,8 @@

import com.google.common.collect.ImmutableMap;

import net.sqlcipher.database.SQLiteDatabase;

import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Before;
Expand All @@ -33,8 +39,11 @@
import org.smartregister.child.ChildLibrary;
import org.smartregister.child.R;
import org.smartregister.child.domain.ChildMetadata;
import org.smartregister.child.provider.RegisterQueryProvider;
import org.smartregister.child.util.ChildAppProperties;
import org.smartregister.child.util.Constants;
import org.smartregister.child.util.Utils;
import org.smartregister.domain.db.EventClient;
import org.smartregister.growthmonitoring.domain.Height;
import org.smartregister.growthmonitoring.domain.HeightWrapper;
import org.smartregister.growthmonitoring.domain.Weight;
Expand All @@ -46,13 +55,15 @@
import org.smartregister.immunization.domain.Vaccine;
import org.smartregister.immunization.repository.VaccineRepository;
import org.smartregister.repository.AllSharedPreferences;
import org.smartregister.repository.EventClientRepository;
import org.smartregister.repository.Repository;
import org.smartregister.util.AppProperties;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PrepareForTest({VaccineRepo.class, ImmunizationLibrary.class})
Expand Down Expand Up @@ -522,4 +533,72 @@ public void testGetWeeksDueWithNullDateReturnsZero() {
int weeksDue = Utils.getWeeksDue(date);
Assert.assertEquals(0, weeksDue);
}

@Test
public void testChildBelongsToCurrentFacilityShouldReturnTrueWhenChildExistsInDB() {
HashMap<String, String> childDetails = new HashMap<>();
childDetails.put("base_entity_id", "case_id");
childDetails.put("is_out_of_catchment", "false");
ArrayList<HashMap<String, String>> childDetailsList = new ArrayList<>();
childDetailsList.add(childDetails);

EventClientRepository eventClientRepository = Mockito.mock(EventClientRepository.class);
Repository repository = Mockito.mock(Repository.class);
Mockito.doReturn(eventClientRepository).when(childLibrary).eventClientRepository();
Mockito.doReturn(repository).when(childLibrary).getRepository();
Mockito.when(repository.getReadableDatabase()).thenReturn(Mockito.mock(SQLiteDatabase.class));
Mockito.doReturn(childDetailsList).when(eventClientRepository).rawQuery(any(SQLiteDatabase.class), anyString());
ChildMetadata metadata = Mockito.mock(ChildMetadata.class);
RegisterQueryProvider registerQueryProvider = Mockito.mock(RegisterQueryProvider.class);
Mockito.doReturn(metadata).when(childLibrary).metadata();
Mockito.doReturn(registerQueryProvider).when(metadata).getRegisterQueryProvider();
Mockito.doReturn("").when(registerQueryProvider).mainRegisterQuery();
Mockito.doReturn("").when(registerQueryProvider).getDemographicTable();

Assert.assertTrue(Utils.childBelongsToCurrentFacility(childDetails));
}

@Test
public void testIsChildTemporaryOOCShouldReturnTrueWhenOOCEvent() {
EventClientRepository eventClientRepository = Mockito.mock(EventClientRepository.class);
Repository repository = Mockito.mock(Repository.class);
Mockito.doReturn(eventClientRepository).when(childLibrary).eventClientRepository();
Mockito.doReturn(repository).when(childLibrary).getRepository();
Mockito.when(repository.getReadableDatabase()).thenReturn(Mockito.mock(SQLiteDatabase.class));
Mockito.doReturn(null).when(eventClientRepository).rawQuery(any(SQLiteDatabase.class), anyString());
ChildMetadata metadata = Mockito.mock(ChildMetadata.class);
RegisterQueryProvider registerQueryProvider = Mockito.mock(RegisterQueryProvider.class);
Mockito.doReturn(metadata).when(childLibrary).metadata();
Mockito.doReturn(registerQueryProvider).when(metadata).getRegisterQueryProvider();
Mockito.doReturn("").when(registerQueryProvider).mainRegisterQuery();
Mockito.doReturn("").when(registerQueryProvider).getDemographicTable();
Mockito.doReturn(true).when(appProperties).isTrue(eq(ChildAppProperties.KEY.NOVEL.OUT_OF_CATCHMENT));

Map<String, String> childDetails = new HashMap<>();
childDetails.put("base_entity_id", "case_id");
childDetails.put("is_out_of_catchment", "true");

Assert.assertTrue(Utils.isChildTemporaryOOC(childDetails));
}

@Test
public void testGetLocationIdFromChildTempOOCEventRetursCorrectLocation() {
EventClientRepository repository = Mockito.mock(EventClientRepository.class);
Mockito.when(childLibrary.eventClientRepository()).thenReturn(repository);

List<EventClient> eventClientList = new ArrayList<>();
org.smartregister.domain.Event event = new org.smartregister.domain.Event();
event.setBaseEntityId("case_id");
org.smartregister.domain.Obs obs = new org.smartregister.domain.Obs();
obs.setFormSubmissionField("From_LocationId");
obs.addToValueList("location_123");
event.addObs(obs);
EventClient eventClient = new EventClient(event);
eventClientList.add(eventClient);

Mockito.doReturn(eventClientList).when(repository).fetchEventClientsCore(anyString(), any());

String locationId = Utils.getLocationIdFromChildTempOOCEvent("case_id");
Assert.assertEquals("location_123", locationId);
}
}