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

Implement closing of expired referral intent service #206

Merged
merged 22 commits into from
May 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
f3ec697
implemented method for fetching tasks with ready status
cozej4 Apr 29, 2020
6187b8b
Added a query for all tasks with business status referred left joined…
cozej4 May 6, 2020
de54bac
Merged changes from master
cozej4 May 6, 2020
5b16c13
Added hiv, tb and gbv task focus constants
cozej4 May 6, 2020
07ced33
Implemented checks for expired and not completed yet referrals
cozej4 May 7, 2020
70b0619
Implemented a method to generate expred and not completed events
cozej4 May 7, 2020
118b743
Implemented methods for saving expired and not yet done referral events
cozej4 May 7, 2020
8dcf569
Code refactoring
cozej4 May 7, 2020
7e29e7c
Implement Updating of tasts
cozej4 May 7, 2020
5facc61
Implemented close expired referrals service job
cozej4 May 7, 2020
5a0ed64
Refactored chw task repository and added implementation for querying …
cozej4 May 7, 2020
e3ee0ed
Updated library version
cozej4 May 7, 2020
f2c6855
Code cleaning
cozej4 May 7, 2020
0e91606
Code cleaning
cozej4 May 7, 2020
b455f4f
Code refactoring
cozej4 May 11, 2020
b57a236
Added child gbv focus in costants
cozej4 May 11, 2020
67c007c
Merge branch 'master' into implement-closing-of-expired-referral-inte…
cozej4 May 11, 2020
9b269e2
Refactored malaria referrals timeouts
cozej4 May 12, 2020
f6ff046
Implemented notifications for not yet done referrals
cozej4 May 12, 2020
523585a
Refactored Referral Not Yet done notification type
cozej4 May 12, 2020
9478859
Code refactoring
cozej4 May 12, 2020
90e2adb
Merge branch 'master' into implement-closing-of-expired-referral-inte…
ellykits May 18, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.2.2-SNAPSHOT
VERSION_NAME=1.2.3-SNAPSHOT
VERSION_CODE=1
GROUP=org.smartregister
POM_SETTING_DESCRIPTION=OpenSRP Client Chw Core Library
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,6 @@ interface Interactor {
*/
void fetchNotificationDetails(String notificationId, String notificationType);

/**
* Crete a referral dismissal entry for the provided task id
*
* @param referralTaskId referral task id
*/
void createReferralDismissalEvent(String referralTaskId);

/**
* Crete a Notification dismissal entry for the provided notification id
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,4 +215,48 @@ private static String formatVisitDate(String visitDate) {
}
return "";
}

/**
*This method is used to get details of referral notification with the provided task id
* @param referralId unique identifier for the task
* @return a notification record with details for the referral
*/
public static NotificationRecord getNotYetDoneReferral(String referralId) {
String sql = String.format(
"/* Get details for not yet done referral */\n" +
"SELECT ec_family_member.first_name || ' ' || CASE ec_family_member.last_name\n" +
" WHEN NULL THEN ec_family_member.middle_name\n" +
" ELSE ec_family_member.last_name END full_name,\n" +
" ec_family_member.dob AS dob,\n" +
" ec_family.village_town AS village,\n" +
" event.dateCreated AS notification_date,\n" +
" ec_family_member.phone_number AS phone_number,\n" +
" ec_family_member.base_entity_id AS base_entity_id\n" +
"\n" +
"FROM task\n" +
" inner join ec_family_member on ec_family_member.base_entity_id = task.for\n" +
" inner join ec_not_yet_done_referral on ec_not_yet_done_referral.referral_task = task._id\n" +
" inner join event on ec_not_yet_done_referral.id = event.formSubmissionId\n" +
" inner join ec_family on ec_family.base_entity_id = ec_family_member.relational_id\n" +
"\n" +
"WHERE ec_family_member.is_closed = '0'\n" +
" AND ec_family_member.date_removed is null\n" +
" AND task.code = 'Referral'\n" +
" AND task._id = '%s' COLLATE NOCASE\n", referralId);

return AbstractDao.readSingleValue(sql, mapReferralNotificationColumns());

}

private static DataMap<NotificationRecord> mapReferralNotificationColumns() {
return row -> {
NotificationRecord record = new NotificationRecord(getCursorValue(row, "base_entity_id"));
record.setClientName(getCursorValue(row, "full_name"));
record.setClientDateOfBirth(getCursorValue(row, "dob"));
record.setVillage(getCursorValue(row, "village"));
record.setNotificationDate(getCursorValue(row, "notification_date"));
record.setPhone(getCursorValue(row, "phone_number"));
return record;
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
public class NotificationItem {
private String title;
private List<String> details;
private String clientBaseEntityId;

public NotificationItem(String title, List<String> details) {
this.title = title;
Expand All @@ -18,4 +19,13 @@ public String getTitle() {
public List<String> getDetails() {
return details;
}

public NotificationItem setClientBaseEntityId(String clientBaseEntityId) {
this.clientBaseEntityId = clientBaseEntityId;
return this;
}

public String getClientBaseEntityId() {
return clientBaseEntityId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ public class NotificationRecord {

private String clientBaseEntityId;
private String clientName;
private String careGiverName;
private String clientDateOfBirth;
private String phone;
private String village;
private String notificationDate;
private String actionTaken;
private String dangerSigns;
private String diagnosis;
private String results;
private String visitDate;
private String method;
private String careGiverName;

public NotificationRecord(String clientBaseEntityId) {
this.clientBaseEntityId = clientBaseEntityId;
Expand Down Expand Up @@ -96,4 +99,28 @@ public String getMethod() {
public void setMethod(String method) {
this.method = method;
}

public String getClientDateOfBirth() {
return clientDateOfBirth;
}

public void setClientDateOfBirth(String clientDateOfBirth) {
this.clientDateOfBirth = clientDateOfBirth;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getNotificationDate() {
return notificationDate;
}

public void setNotificationDate(String notificationDate) {
this.notificationDate = notificationDate;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.app.Activity;
import android.content.Context;
import android.util.Pair;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
Expand All @@ -19,12 +20,18 @@
import org.smartregister.clientandeventmodel.Event;
import org.smartregister.clientandeventmodel.Obs;
import org.smartregister.family.FamilyLibrary;
import org.smartregister.family.util.Utils;
import org.smartregister.opd.utils.OpdUtils;
import org.smartregister.repository.AllSharedPreferences;
import org.smartregister.sync.helper.ECSyncHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

Expand All @@ -34,68 +41,13 @@ public class BaseChwNotificationDetailsInteractor implements ChwNotificationDeta

private ChwNotificationDetailsContract.Presenter presenter;
private Context context;
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

public BaseChwNotificationDetailsInteractor(ChwNotificationDetailsContract.Presenter presenter) {
this.presenter = presenter;
context = (Activity) presenter.getView();
}

@Override
public void createReferralDismissalEvent(String referralTaskId) {
try {
AllSharedPreferences sharedPreferences = CoreChwApplication.getInstance().getContext().allSharedPreferences();
ECSyncHelper syncHelper = FamilyLibrary.getInstance().getEcSyncHelper();
String userLocationId = sharedPreferences.fetchUserLocalityId(sharedPreferences.fetchRegisteredANM());
Event baseEvent = (Event) new Event()
.withBaseEntityId(presenter.getClientBaseEntityId())
.withEventDate(new Date())
.withEventType(CoreConstants.EventType.REFERRAL_DISMISSAL)
.withFormSubmissionId(JsonFormUtils.generateRandomUUIDString())
.withEntityType(CoreConstants.TABLE_NAME.REFERRAL_DISMISSAL)
.withProviderId(sharedPreferences.fetchRegisteredANM())
.withLocationId(userLocationId)
.withTeamId(sharedPreferences.fetchDefaultTeamId(sharedPreferences.fetchRegisteredANM()))
.withTeam(sharedPreferences.fetchDefaultTeam(sharedPreferences.fetchRegisteredANM()))
.withDateCreated(new Date());

baseEvent.addObs((new Obs())
.withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK)
.withValue(referralTaskId)
.withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.REFERRAL_TASK)
.withFieldType(CoreConstants.FORMSUBMISSION_FIELD).withFieldDataType(CoreConstants.TEXT)
.withParentCode("").withHumanReadableValues(new ArrayList<>()));

baseEvent.addObs((new Obs())
.withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.NOTIFICATION_DATE_CREATED)
.withValue(presenter.getNotificationDates().first)
.withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.NOTIFICATION_DATE_CREATED)
.withFieldType(CoreConstants.FORMSUBMISSION_FIELD).withFieldDataType(CoreConstants.DATE)
.withParentCode("").withHumanReadableValues(new ArrayList<>()));

baseEvent.addObs((new Obs())
.withFormSubmissionField(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.NOTIFICATION_DISMISSAL_DATE)
.withValue(presenter.getNotificationDates().second)
.withFieldCode(CoreConstants.FORM_CONSTANTS.FORM_SUBMISSION_FIELD.NOTIFICATION_DISMISSAL_DATE)
.withFieldType(CoreConstants.FORMSUBMISSION_FIELD).withFieldDataType(CoreConstants.DATE)
.withParentCode("").withHumanReadableValues(new ArrayList<>()));

CoreJsonFormUtils.tagSyncMetadata(sharedPreferences, baseEvent);

baseEvent.setLocationId(userLocationId);

JSONObject eventJson = new JSONObject(JsonFormUtils.gson.toJson(baseEvent));
syncHelper.addEvent(referralTaskId, eventJson);
long lastSyncTimeStamp = sharedPreferences.fetchLastUpdatedAtDate(0);
Date lastSyncDate = new Date(lastSyncTimeStamp);
List<String> formSubmissionIds = new ArrayList<>();
formSubmissionIds.add(baseEvent.getFormSubmissionId());
CoreChwApplication.getInstance().getClientProcessorForJava().processClient(syncHelper.getEvents(formSubmissionIds));
sharedPreferences.saveLastUpdatedAtDate(lastSyncDate.getTime());
} catch (Exception e) {
Timber.e(e, "BaseReferralNotificationDetailsInteractor --> createReferralDismissalEvent");
}
}

@Override
public void createNotificationDismissalEvent(String notificationId, String notificationType) {
Event baseEvent = ChwNotificationUtil.createNotificationDismissalBaseEvent(presenter.getClientBaseEntityId(), ChwNotificationUtil.getNotificationDismissalEventType(context, notificationType));
Expand All @@ -116,17 +68,18 @@ public void createNotificationDismissalEvent(String notificationId, String notif
@Override
public void fetchNotificationDetails(String notificationId, String notificationType) {
NotificationItem notificationItem = null;

if (notificationType.equals(context.getString(R.string.notification_type_sick_child_follow_up))) {
if (notificationType.equals(context.getString(R.string.notification_type_sick_child_follow_up)))
notificationItem = getSickChildFollowUpDetails(notificationId);
} else if (notificationType.equals(context.getString(R.string.notification_type_pnc_danger_signs)) ||
notificationType.equals(context.getString(R.string.notification_type_anc_danger_signs))) {
else if (notificationType.equals(context.getString(R.string.notification_type_pnc_danger_signs)) ||
notificationType.equals(context.getString(R.string.notification_type_anc_danger_signs)))
notificationItem = getAncPncOutcomeDetails(notificationId, notificationType);
} else if (notificationType.contains(context.getString(R.string.notification_type_malaria_follow_up))) {
else if (notificationType.contains(context.getString(R.string.notification_type_malaria_follow_up)))
notificationItem = getMalariaFollowUpDetails(notificationId);
} else if (notificationType.contains(context.getString(R.string.notification_type_family_planning))) {
else if (notificationType.contains(context.getString(R.string.notification_type_family_planning)))
notificationItem = getDetailsForFamilyPlanning(notificationId);
}
else if (notificationType.contains(context.getString(R.string.notification_type_not_yet_done_referrals)))
notificationItem = getDetailsForNotYetDoneReferral(notificationId);

presenter.onNotificationDetailsFetched(notificationItem);
}

Expand Down Expand Up @@ -176,4 +129,58 @@ private NotificationItem getDetailsForFamilyPlanning(String notificationId) {
details.add(context.getString(R.string.notification_village, notificationRecord.getVillage()));
return new NotificationItem(title, details);
}

@NotNull
private NotificationItem getDetailsForNotYetDoneReferral(String referralTaskId) {
NotificationRecord record = ChwNotificationDao.getNotYetDoneReferral(referralTaskId);
List<String> details = setNotificationRecordDetails(record);
details.add(context.getString(R.string.notification_record_not_yet_done));
String title = context.getString(R.string.successful_referral_notification_title,
record.getClientName(), getClientAge(record.getClientDateOfBirth()));
return new NotificationItem(title, details).setClientBaseEntityId(record.getClientBaseEntityId());
}

private List<String> setNotificationRecordDetails(NotificationRecord record) {
presenter.setClientBaseEntityId(record.getClientBaseEntityId());

Pair<String, String> notificationDatesPair = null;
String notificationDate = record.getNotificationDate();
try {
notificationDate = dateFormat.format(dateFormat.parse(record.getNotificationDate()));
notificationDatesPair = Pair.create(notificationDate, getDismissalDate(dateFormat.format(new Date())));
} catch (ParseException e) {
Timber.e(e, "Error Parsing date: %s", record.getNotificationDate());
}
presenter.setNotificationDates(notificationDatesPair);

List<String> details = new ArrayList<>();
details.add(context.getString(R.string.notification_phone, record.getPhone() != null ? record.getPhone() : context.getString(R.string.no_phone_provided)));
details.add(context.getString(R.string.referral_notification_closure_date, notificationDate));
if (record.getVillage() != null) {
details.add(context.getString(R.string.notification_village, record.getVillage()));
}
return details;
}
/**
* This method is used to obtain the date when the referral will be dismissed from the updates
* register
*
* @param eventCreationDate date the referral was created
* @return new date returned after adding 3 to the provided date
*/
private String getDismissalDate(String eventCreationDate) {

Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(dateFormat.parse(eventCreationDate));
} catch (ParseException e) {
Timber.e(e);
}
calendar.add(Calendar.DAY_OF_MONTH, 3);
return dateFormat.format(calendar.getTime());
}
private String getClientAge(String dobString) {
String translatedYearInitial = context.getResources().getString(R.string.abbrv_years);
return OpdUtils.getClientAge(Utils.getDuration(dobString), translatedYearInitial);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import static org.smartregister.chw.core.utils.QueryConstant.ANC_DANGER_SIGNS_OUTCOME_COUNT_QUERY;
import static org.smartregister.chw.core.utils.QueryConstant.FAMILY_PLANNING_UPDATE_COUNT_QUERY;
import static org.smartregister.chw.core.utils.QueryConstant.MALARIA_HF_FOLLOW_UP_COUNT_QUERY;
import static org.smartregister.chw.core.utils.QueryConstant.NOT_YET_DONE_REFERRAL_COUNT_QUERY;
import static org.smartregister.chw.core.utils.QueryConstant.PNC_DANGER_SIGNS_OUTCOME_COUNT_QUERY;
import static org.smartregister.chw.core.utils.QueryConstant.SICK_CHILD_FOLLOW_UP_COUNT_QUERY;

Expand Down Expand Up @@ -256,9 +257,10 @@ private int getCount(String tableName) {

case CoreConstants.TABLE_NAME.NOTIFICATION_UPDATE:
String referralNotificationQuery =
String.format("SELECT SUM(c) FROM (\n %s UNION ALL\n %s UNION ALL\n %s UNION ALL\n %s UNION ALL\n %s)",
String.format("SELECT SUM(c) FROM (\n %s \nUNION ALL\n %s \nUNION ALL\n %s \nUNION ALL\n %s \nUNION ALL\n %s \nUNION ALL %s)",
SICK_CHILD_FOLLOW_UP_COUNT_QUERY, ANC_DANGER_SIGNS_OUTCOME_COUNT_QUERY,
PNC_DANGER_SIGNS_OUTCOME_COUNT_QUERY, FAMILY_PLANNING_UPDATE_COUNT_QUERY, MALARIA_HF_FOLLOW_UP_COUNT_QUERY);
PNC_DANGER_SIGNS_OUTCOME_COUNT_QUERY, FAMILY_PLANNING_UPDATE_COUNT_QUERY,
MALARIA_HF_FOLLOW_UP_COUNT_QUERY, NOT_YET_DONE_REFERRAL_COUNT_QUERY);
return NavigationDao.getQueryCount(referralNotificationQuery);

default:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.smartregister.chw.core.job;

import android.content.Intent;

import androidx.annotation.NonNull;

import org.smartregister.AllConstants;
import org.smartregister.chw.core.sync.intent.CloseExpiredReferralsIntentService;
import org.smartregister.job.BaseJob;

/**
* Created by cozej4 on 2020-02-08.
*
* @author cozej4 https://github.com/cozej4
*/
public class CloseExpiredReferralsServiceJob extends BaseJob {

public static final String TAG = "CloseExpiredReferralsServiceJob";

@NonNull
@Override
protected Result onRunJob(@NonNull Params params) {
Intent intent = new Intent(getApplicationContext(), CloseExpiredReferralsIntentService.class);
getApplicationContext().startService(intent);
return params != null && params.getExtras().getBoolean(AllConstants.INTENT_KEY.TO_RESCHEDULE, false) ? Result.RESCHEDULE : Result.SUCCESS;
}
}
Loading