diff --git a/opensrp-chw/src/kk/assets/json.form/add_anc_registration.json b/opensrp-chw/src/kk/assets/json.form/add_anc_registration.json index dda69ced4..2dc61b3c5 100644 --- a/opensrp-chw/src/kk/assets/json.form/add_anc_registration.json +++ b/opensrp-chw/src/kk/assets/json.form/add_anc_registration.json @@ -88,7 +88,7 @@ { "key": "edi_id", "openmrs_entity_parent": "", - "openmrs_entity": "person_identifier", + "openmrs_entity": "concept", "openmrs_entity_id": "edi_id", "type": "edit_text", "hint": "{{add_anc_registration.step1.ediid.hint}}", diff --git a/opensrp-chw/src/kk/assets/json.form/family_member_register.json b/opensrp-chw/src/kk/assets/json.form/family_member_register.json index 8a91f1f7f..c71546096 100644 --- a/opensrp-chw/src/kk/assets/json.form/family_member_register.json +++ b/opensrp-chw/src/kk/assets/json.form/family_member_register.json @@ -76,7 +76,7 @@ { "key": "edi_id", "openmrs_entity_parent": "", - "openmrs_entity": "person_identifier", + "openmrs_entity": "concept", "openmrs_entity_id": "edi_id", "type": "edit_text", "hint": "{{family_member_register.step1.ediid.hint}}", diff --git a/opensrp-chw/src/kk/assets/json.form/family_register.json b/opensrp-chw/src/kk/assets/json.form/family_register.json index 6dea2cbdc..823d81ea7 100644 --- a/opensrp-chw/src/kk/assets/json.form/family_register.json +++ b/opensrp-chw/src/kk/assets/json.form/family_register.json @@ -887,7 +887,7 @@ { "key": "edi_id", "openmrs_entity_parent": "", - "openmrs_entity": "person_identifier", + "openmrs_entity": "concept", "openmrs_entity_id": "edi_id", "type": "edit_text", "hint": "{{family_register.step1.ediid.hint}}", diff --git a/opensrp-chw/src/kk/assets/json.form/group_session.json b/opensrp-chw/src/kk/assets/json.form/group_session.json index 7f0ba2ae4..bfd3f6665 100644 --- a/opensrp-chw/src/kk/assets/json.form/group_session.json +++ b/opensrp-chw/src/kk/assets/json.form/group_session.json @@ -132,6 +132,13 @@ "openmrs_entity": "concept", "openmrs_entity_id": "session_duration", "type": "hidden" + }, + { + "key": "session_duration_minutes", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "session_duration_minutes", + "type": "hidden" } ] }, diff --git a/opensrp-chw/src/kk/assets/json.form/group_session_child_form.json b/opensrp-chw/src/kk/assets/json.form/group_session_child_form.json index 9cf349a13..047372761 100644 --- a/opensrp-chw/src/kk/assets/json.form/group_session_child_form.json +++ b/opensrp-chw/src/kk/assets/json.form/group_session_child_form.json @@ -83,6 +83,27 @@ "openmrs_entity": "concept", "openmrs_entity_id": "other_people_present", "type": "hidden" + }, + { + "key": "other_people_present_other", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "other_people_present_other", + "type": "hidden" + }, + { + "key": "care_giver_representatives", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "care_giver_representatives", + "type": "hidden" + }, + { + "key": "care_giver_representatives_other", + "openmrs_entity_parent": "", + "openmrs_entity": "concept", + "openmrs_entity_id": "care_giver_representatives_other", + "type": "hidden" } ] }, diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcFinalStepFragment.java b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcFinalStepFragment.java index d0763fed7..8de5dd0bf 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcFinalStepFragment.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcFinalStepFragment.java @@ -69,6 +69,8 @@ public class GcFinalStepFragment extends BaseGroupSessionRegisterFragment { CheckBox activityReview; CheckBox activityOne; CheckBox activityTwo; + + CheckBox activityNutrition; CheckBox activityRecap; CheckBox activityClosingSong; @@ -80,6 +82,9 @@ public class GcFinalStepFragment extends BaseGroupSessionRegisterFragment { CheckBox difficultReview; CheckBox difficultActivity1; CheckBox difficultActivity2; + + CheckBox difficultNutrition; + CheckBox difficultRecap; CheckBox difficultClosingSong; @@ -94,6 +99,8 @@ public class GcFinalStepFragment extends BaseGroupSessionRegisterFragment { TextInputEditText etDurationInHours; + TextInputEditText etDurationMinutes; + ProgressBar progressBar; MaterialButton submitButton; @@ -112,7 +119,7 @@ public class GcFinalStepFragment extends BaseGroupSessionRegisterFragment { private SessionModelUpdatedListener sessionModelUpdatedListener; private GroupSessionModel sessionModel; - public GcFinalStepFragment(SessionModelUpdatedListener listener){ + public GcFinalStepFragment(SessionModelUpdatedListener listener) { this.sessionModelUpdatedListener = listener; } @@ -186,16 +193,28 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { }); difficultActivity2 = view.findViewById(R.id.difficult_activity_2); - difficultActivity2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { - @Override - public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b) - listOfDifficultActivities.add(ACTIVITY_2); - else - listOfDifficultActivities.remove(ACTIVITY_2); - } + difficultActivity2.setOnCheckedChangeListener((compoundButton, b) -> { + if (b) + listOfDifficultActivities.add(ACTIVITY_2); + else + listOfDifficultActivities.remove(ACTIVITY_2); }); + difficultNutrition = view + .findViewById( + R.id.difficult_nutrition_activity + ); + + difficultNutrition + .setOnCheckedChangeListener( + (buttonView, isChecked) -> { + if (isChecked) { + listOfDifficultActivities.add(KkConstants.GCActivities.NUTRITION_ACTIVITY); + } else { + listOfDifficultActivities.remove(KkConstants.GCActivities.NUTRITION_ACTIVITY); + } + }); + difficultRecap = view.findViewById(R.id.difficult_recap_session); difficultRecap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -246,7 +265,7 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { materialsScheduledUsedNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { materialsScheduledUsedYes.setChecked(false); teachingLearningMaterialsUsed = false; } @@ -257,10 +276,10 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { materialsScheduledUsedYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ - materialsScheduledUsedNo.setChecked(false); - teachingLearningMaterialsUsed = true; - } + if (b) { + materialsScheduledUsedNo.setChecked(false); + teachingLearningMaterialsUsed = true; + } } }); @@ -269,9 +288,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { activityWelcome.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { activitiesTookPlace.add(WELCOME_AND_FREE_PLAY); - }else{ + } else { activitiesTookPlace.remove(WELCOME_AND_FREE_PLAY); } @@ -321,6 +340,19 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { } }); + activityNutrition = view.findViewById(R.id.nutrition_activity); + + activityNutrition.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + activitiesTookPlace.add(KkConstants.GCActivities.NUTRITION_ACTIVITY); + } else { + activitiesTookPlace.remove(KkConstants.GCActivities.NUTRITION_ACTIVITY); + } + } + }); + activityRecap = view.findViewById(R.id.recap_session); activityRecap.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -384,7 +416,7 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { activitiesDifficultNo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { activitiesDifficultYes.setChecked(false); anyDifficultActivities = false; } @@ -394,7 +426,7 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { activitiesDifficultYes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { activitiesDifficultNo.setChecked(false); anyDifficultActivities = true; } @@ -407,9 +439,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { topicLanguage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { topicsCovered.add(TOPIC_LANGUAGE); - }else{ + } else { activitiesTookPlace.remove(TOPIC_LANGUAGE); } @@ -419,9 +451,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { topicCognitive.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { topicsCovered.add(TOPIC_COGNITIVE); - }else{ + } else { topicsCovered.remove(TOPIC_COGNITIVE); } } @@ -431,9 +463,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { topicSocialemotional.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { topicsCovered.add(TOPIC_SOCIAL_EMOTIONAL); - }else{ + } else { topicsCovered.remove(TOPIC_SOCIAL_EMOTIONAL); } } @@ -443,9 +475,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { topicCreativity.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { topicsCovered.add(TOPIC_CREATIVITY); - }else{ + } else { topicsCovered.remove(TOPIC_CREATIVITY); } } @@ -455,9 +487,9 @@ public void onCheckedChanged(CompoundButton compoundButton, boolean b) { topicFormalTeaching.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { - if (b){ + if (b) { topicsCovered.add(TOPIC_FORMAL_TEACHING); - }else{ + } else { topicsCovered.remove(TOPIC_FORMAL_TEACHING); } } @@ -484,6 +516,8 @@ public void onClick(View view) { etDurationInHours = view.findViewById(R.id.et_session_duration); + etDurationMinutes = view.findViewById(R.id.et_session_duration_minutes); + progressBar = view.findViewById(R.id.progress_bar); } @@ -492,7 +526,7 @@ private void saveGroupSession() { presenter().saveGroupSession(sessionModel); } - private void difficultActivitiesLayoutController(boolean isDifficult){ + private void difficultActivitiesLayoutController(boolean isDifficult) { difficultActivitiesList.setVisibility(isDifficult ? View.VISIBLE : View.GONE); } @@ -517,7 +551,9 @@ public void getSessionDetails() { sessionModel.setCaregiversBroughtMaterials(caregiversBroughtMaterials); sessionModel.setTopicsCovered(topicsCovered); String durationString = etDurationInHours != null ? etDurationInHours.getText().toString().trim() : ""; - sessionModel.setDurationInHours(!durationString.isEmpty() ? Integer.parseInt(durationString): 0); + String durationMinutesString = etDurationMinutes != null ? etDurationMinutes.getText().toString().trim() : ""; + sessionModel.setDurationInHours(!durationString.isEmpty() ? Integer.parseInt(durationString) : 0); + sessionModel.setDurationInMinutes(!durationMinutesString.isEmpty() ? Integer.parseInt(durationMinutesString) : 0); //Toast.makeText(getContext(), "Group Session Information Recorded", Toast.LENGTH_SHORT).show(); } @@ -545,7 +581,7 @@ public void finishGroupSession() { requireActivity().finish(); } - private boolean validateFields(){ + private boolean validateFields() { boolean isValid = true; @@ -596,18 +632,12 @@ private boolean validateFields(){ if (durationString.isEmpty()) { isValid = false; etDurationInHours.setError("Please enter session duration"); - } else { - int duration = Integer.parseInt(durationString); - if (duration <= 0) { - isValid = false; - etDurationInHours.setError("Duration must be greater than 0"); - } } return isValid; } - private void createSessionObject(){ + private void createSessionObject() { } diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcRegistrationStageFragment.java b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcRegistrationStageFragment.java index cb0540255..b6e318ef3 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcRegistrationStageFragment.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/GcRegistrationStageFragment.java @@ -338,7 +338,7 @@ public void onNothingSelected(AdapterView adapterView) { spNoSessionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { - if (i == 4){ + if (i == 5){ etOtherReasonLayout.setVisibility(View.VISIBLE); }else{ etOtherReasonLayout.setVisibility(View.GONE); diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionDialogFragment.java b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionDialogFragment.java index 1498fee2a..59636e793 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionDialogFragment.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionDialogFragment.java @@ -2,9 +2,11 @@ import android.app.Dialog; import android.content.Context; +import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; +import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; @@ -29,10 +31,17 @@ public class SelectChildForGroupSessionDialogFragment extends DialogFragment { private RecyclerView who_came_with_the_child_lv; + private RecyclerView came_with_pc_lv; + private RecyclerView lv_caregiver_representative; private TextView who_came_with_child_tv; + private TextView tv_caregiver_representative; + private KKCustomAdapter came_with_pc_lv_adapter; private KKCustomAdapter selected_group_lv_adapter; + private KKCustomAdapterMultiSelectList cg_rep_lv_adapter; + private KKCustomAdapterMultiSelectList who_came_with_the_child_lv_adapter; + private int selectedPosition1 = -1; private int selectedPosition2 = -1; private int selectedPosition3 = -1; @@ -43,8 +52,14 @@ public class SelectChildForGroupSessionDialogFragment extends DialogFragment { private final boolean childrenDividedIntoGroups; + private EditText cg_rep_lv_other; + + private EditText who_came_with_the_child_lv_other; + SelectChildForGroupSessionRegisterFragment.DialogDismissListener dialogDismissListener; + String[] groupItems; + public SelectChildForGroupSessionDialogFragment(String selectedChildBaseEntityId, String primaryCareGiverName, boolean childrenDividedIntoGroups, SelectChildForGroupSessionRegisterFragment.DialogDismissListener listener) { this.selectedChildBaseEntityId = selectedChildBaseEntityId; this.primaryCareGiverName = primaryCareGiverName; @@ -58,16 +73,30 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity()); LayoutInflater inflater = requireActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_fragment_childselection, null); + TextView came_with_pc_tv = view.findViewById(R.id.came_with_pc); came_with_pc_tv.setText(String.format(getString(R.string.primary_care_give_dialog_gs), primaryCareGiverName)); builder.setView(view); - RecyclerView came_with_pc_lv = view.findViewById(R.id.came_with_pc_lv); + came_with_pc_lv = view.findViewById(R.id.came_with_pc_lv); who_came_with_the_child_lv = view.findViewById(R.id.who_came_with_the_child_lv); + + lv_caregiver_representative = view.findViewById(R.id.cg_rep_lv); + lv_caregiver_representative.setVisibility(View.GONE); + lv_caregiver_representative.setScrollContainer(false); + tv_caregiver_representative = view.findViewById(R.id.cg_rep_tv); + tv_caregiver_representative.setVisibility(View.GONE); + TextView selected_group = view.findViewById(R.id.selected_group); RecyclerView selected_group_lv = view.findViewById(R.id.selected_group_lv); selected_group_lv.setScrollContainer(false); + cg_rep_lv_other = view.findViewById(R.id.cg_rep_lv_other); + cg_rep_lv_other.setVisibility(View.GONE); + + who_came_with_the_child_lv_other = view.findViewById(R.id.who_came_with_the_child_lv_other); + who_came_with_the_child_lv_other.setVisibility(View.GONE); + if (childrenDividedIntoGroups) { selected_group_lv.setVisibility(View.VISIBLE); selected_group.setVisibility(View.VISIBLE); @@ -80,18 +109,19 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { came_with_pc_lv_adapter = new KKCustomAdapter(getResources().getStringArray(R.array.select_child_option), requireContext()); ArrayList multiSelectListItems = new ArrayList<>(); - for(String item : getResources().getStringArray(R.array.multi_select_accompany_child_option)){ - multiSelectListItems.add(new MultiSelectListItemModel(item, false)); - } - KKCustomAdapterMultiSelectList who_came_with_the_child_lv_adapter = new KKCustomAdapterMultiSelectList(multiSelectListItems, requireContext()); + who_came_with_the_child_lv_adapter = new KKCustomAdapterMultiSelectList(setMultiSelectListItems(multiSelectListItems), requireContext()); - String[] groupItems = getResources().getStringArray(R.array.group_session_groups); + groupItems = getResources().getStringArray(R.array.group_session_groups); selected_group_lv_adapter = new KKCustomAdapter(groupItems, requireContext()); - came_with_pc_lv.setAdapter(came_with_pc_lv_adapter); who_came_with_the_child_lv.setAdapter(who_came_with_the_child_lv_adapter); selected_group_lv.setAdapter(selected_group_lv_adapter); + ArrayList multiSelectListItems1 = new ArrayList<>(); + cg_rep_lv_adapter = new KKCustomAdapterMultiSelectList(setMultiSelectListItems(multiSelectListItems1), requireContext()); + lv_caregiver_representative.setAdapter(cg_rep_lv_adapter); + lv_caregiver_representative.setLayoutManager(new LinearLayoutManager(requireContext())); + came_with_pc_lv.setLayoutManager(new LinearLayoutManager(requireContext())); who_came_with_the_child_lv.setLayoutManager(new LinearLayoutManager(requireContext())); selected_group_lv.setLayoutManager(new LinearLayoutManager(requireContext())); @@ -105,6 +135,12 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { who_came_with_the_child_lv_adapter.setOnItemSelectedListener(position -> { selectedPosition3 = position; who_came_with_the_child_lv_adapter.setSelectedPosition(position); + checkForOtherItemSelected(isOtherItemSelected(who_came_with_the_child_lv_adapter.getSelectedItems()), who_came_with_the_child_lv_other); + }); + + cg_rep_lv_adapter.setOnItemSelectedListener(position -> { + cg_rep_lv_adapter.setSelectedPosition(position); + checkForOtherItemSelected(isOtherItemSelected(cg_rep_lv_adapter.getSelectedItems()), cg_rep_lv_other); }); selected_group_lv_adapter.setOnItemSelectedListener(position -> { @@ -112,42 +148,84 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { selected_group_lv_adapter.setSelectedPosition(position); }); - builder.setPositiveButton(R.string.ok, (dialog, which) -> { - if (selectedPosition1 == -1) { - Toast.makeText(requireContext(), "Caregiver information missing", Toast.LENGTH_SHORT).show(); - dialogDismissListener.onFailure(); - dialog.dismiss(); - } + builder.setPositiveButton(R.string.ok, null); + + builder.setNegativeButton(R.string.cancel, (dialog, which) -> { + dialogDismissListener.onFailure(); + dialog.dismiss(); + }); + + return builder.create(); + } - if (selectedPosition2 == -1 && childrenDividedIntoGroups) { - Toast.makeText(requireContext(), "Child missing the group", Toast.LENGTH_SHORT).show(); - dialogDismissListener.onFailure(); - dialog.dismiss(); + @Override + public void onResume() { + AlertDialog dialog = (AlertDialog) getDialog(); + assert dialog != null; + dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() + { + @Override + public void onClick(View v) + { + if (selectedPosition1 == -1) { + dialogValidationFail(dialog, getString(R.string.came_with_pc_lv)); + }else if (selectedPosition2 == -1 && childrenDividedIntoGroups) { + dialogValidationFail(dialog, getString(R.string.selected_group_lv)); + }else { + handleSuccess(dialog); + } } + }); + super.onResume(); + } - if (dialogListener != null && (selectedPosition2 != -1 || !childrenDividedIntoGroups) && selectedPosition1 != -1) { + void handleSuccess(DialogInterface dialogInterface){ + String otherCompanion = who_came_with_the_child_lv_other.getText().toString(); + if(selectedPosition1 == 0){ + if(who_came_with_the_child_lv_adapter.getSelectedItems().isEmpty()){ + dialogValidationFail(dialogInterface, getString(R.string.who_came_with_the_child_lv_error)); + }else if(isOtherItemSelected(who_came_with_the_child_lv_adapter.getSelectedItems()) && otherCompanion.isEmpty()){ + dialogValidationFail(dialogInterface, getString(R.string.who_came_with_the_child_lv_other_error)); + }else{ dialogListener.onSelectComeWithPrimaryCareGiver( - selectedPosition1 == 0, + true, selectedChildBaseEntityId, who_came_with_the_child_lv_adapter.getSelectedItems(), + otherCompanion.isEmpty() ? null : otherCompanion, !childrenDividedIntoGroups ? "Not in groups" : groupItems[selectedPosition2] ); - dialogDismissListener.onSuccess(); - dialog.dismiss(); + dialogValidationSuccess(dialogInterface); + } + }else if(selectedPosition1 == 1){ + String otherCaregiverRepresentative = cg_rep_lv_other.getText().toString(); + if(cg_rep_lv_adapter.getSelectedItems().isEmpty()){ + dialogValidationFail(dialogInterface, getString(R.string.cg_rep_lv_error)); + }else if(isOtherItemSelected(cg_rep_lv_adapter.getSelectedItems()) && otherCaregiverRepresentative.isEmpty()){ + dialogValidationFail(dialogInterface,getString(R.string.cg_rep_lv_other_error)); + }else if(isOtherItemSelected(who_came_with_the_child_lv_adapter.getSelectedItems()) && otherCompanion.isEmpty()){ + dialogValidationFail(dialogInterface, getString(R.string.who_came_with_the_child_lv_other_error)); }else{ - Toast.makeText(requireContext(), "Missing information for the child", Toast.LENGTH_SHORT).show(); - dialogDismissListener.onFailure(); - dialog.dismiss(); + dialogListener.onSelectComeWithoutPrimaryCareGiver( + false, + selectedChildBaseEntityId, + cg_rep_lv_adapter.getSelectedItems(), + otherCaregiverRepresentative.isEmpty() ? null : otherCaregiverRepresentative, + who_came_with_the_child_lv_adapter.getSelectedItems(), + otherCompanion.isEmpty() ? null : otherCompanion, + !childrenDividedIntoGroups ? "Not in groups" : groupItems[selectedPosition2]); + dialogValidationSuccess(dialogInterface); } + } + } - }); - - builder.setNegativeButton(R.string.cancel, (dialog, which) -> { - dialogDismissListener.onFailure(); - dialog.dismiss(); - }); + void dialogValidationFail(DialogInterface dialogInterface,String message){ + Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show(); + dialogDismissListener.onFailure(); + } - return builder.create(); + void dialogValidationSuccess(DialogInterface dialogInterface){ + dialogDismissListener.onSuccess(); + dialogInterface.dismiss(); } @Override @@ -163,17 +241,61 @@ public void onAttach(@NonNull Context context) { private void modifyChildCameWith(boolean hide) { if (hide) { + //Child came with the care giver + tv_caregiver_representative.setVisibility(View.GONE); + lv_caregiver_representative.setVisibility(View.GONE); who_came_with_child_tv.setText(R.string.who_came_with_the_child_yes); + cg_rep_lv_other.setVisibility(View.GONE); } else { + //Child did not come with the caregiver + tv_caregiver_representative.setVisibility(View.VISIBLE); + lv_caregiver_representative.setVisibility(View.VISIBLE); who_came_with_child_tv.setText(R.string.who_came_with_the_child_no); + checkForOtherItemSelected(isOtherItemSelected(cg_rep_lv_adapter.getSelectedItems()), cg_rep_lv_other); } } public interface DialogListener { void onSelectComeWithPrimaryCareGiver( boolean isComeWithPrimaryCareGiver, - String selectedChildBaseEntityId, List selectedAccompanyingCaregivers, + String selectedChildBaseEntityId, + List selectedAccompanyingCaregivers, + String otherCompanion, String selectedGroup); + + void onSelectComeWithoutPrimaryCareGiver( + boolean isComeWithPrimaryCareGiver, + String selectedChildBaseEntityId, + List selectedCaregiverRepresentatives, + String otherCaregiverRepresentative, + List selectedAccompanyingCaregiverRepresentatives, + String otherCompanion, + String selectedGroup); + } + + private ArrayList setMultiSelectListItems(ArrayList multiSelectListItems){ + for(String item : getResources().getStringArray(R.array.multi_select_accompany_child_option)){ + multiSelectListItems.add(new MultiSelectListItemModel(item, false)); + } + return multiSelectListItems; + } + + public boolean isOtherItemSelected(List list) { + for (MultiSelectListItemModel item : list) { + if (item.getName().equals(getString(R.string.cg_rep_lv_other)) && item.isSelected()) { + return true; + } + } + return false; + } + + private void checkForOtherItemSelected(boolean isOtherItemSelected, EditText editText){ + if(isOtherItemSelected){ + editText.setVisibility(View.VISIBLE); + }else{ + editText.setVisibility(View.GONE); + editText.getText().clear(); + } } } diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionRegisterFragment.java b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionRegisterFragment.java index ea520fb55..7f373d22a 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionRegisterFragment.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/fragment/SelectChildForGroupSessionRegisterFragment.java @@ -106,17 +106,36 @@ private String getClientCareGiverName(CommonPersonObjectClient client) { @Override - public void onSelectComeWithPrimaryCareGiver(boolean isComeWithPrimaryCareGiver, String selectedChildBaseEntityId, List selectedAccompanyingCaregivers, String groupPlaced) { + public void onSelectComeWithPrimaryCareGiver(boolean isComeWithPrimaryCareGiver, String selectedChildBaseEntityId, List selectedAccompanyingCaregivers, String otherCompanion, String groupPlaced) { Timber.d("The Child with id %s Come with Primary Care Giver: %s", selectedChildBaseEntityId, isComeWithPrimaryCareGiver); - List listOfAccompanyingRelatives = new ArrayList<>(); - for (MultiSelectListItemModel multiSelectListItemModel : selectedAccompanyingCaregivers) { - listOfAccompanyingRelatives.add(getTranslatedAccompanyingRelatives(multiSelectListItemModel.getName())); - } + List listOfAccompanyingRelatives = getTranslatedNames(selectedAccompanyingCaregivers); + childRegisterProvider.updateChildSelectionStatus(selectedChildBaseEntityId, + isComeWithPrimaryCareGiver, + listOfAccompanyingRelatives, + otherCompanion, + GroupSessionTranslationsUtils.getTranslatedGroupPlaced(groupPlaced), + null,null); + } + @Override + public void onSelectComeWithoutPrimaryCareGiver(boolean isComeWithPrimaryCareGiver, String selectedChildBaseEntityId, List selectedCaregiverRepresentatives, String otherCaregiverRepresentative, List selectedAccompanyingCaregiverRepresentatives, String otherCompanion, String groupPlaced) { + List listOfAccompanyingRelatives = getTranslatedNames(selectedAccompanyingCaregiverRepresentatives);; + List listOfCaregiverRepresentatives = getTranslatedNames(selectedCaregiverRepresentatives); childRegisterProvider.updateChildSelectionStatus(selectedChildBaseEntityId, isComeWithPrimaryCareGiver, listOfAccompanyingRelatives, - GroupSessionTranslationsUtils.getTranslatedGroupPlaced(groupPlaced)); + otherCompanion, + GroupSessionTranslationsUtils.getTranslatedGroupPlaced(groupPlaced), + listOfCaregiverRepresentatives, + otherCaregiverRepresentative); + } + + private List getTranslatedNames(List items) { + List translatedNames = new ArrayList<>(); + for (MultiSelectListItemModel item : items) { + translatedNames.add(getTranslatedAccompanyingRelatives(item.getName())); + } + return translatedNames; } private String getTranslatedAccompanyingRelatives(String name) { diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/model/GroupSessionModel.java b/opensrp-chw/src/kk/java/org/smartregister/chw/model/GroupSessionModel.java index 289710489..5667e8d50 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/model/GroupSessionModel.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/model/GroupSessionModel.java @@ -28,6 +28,7 @@ public class GroupSessionModel { private List topicsCovered; private int durationInHours; + private int durationInMinutes; private boolean childrenDividedInGroups; public GroupSessionModel(){ @@ -178,4 +179,10 @@ public boolean isAnyDifficultActivities() { return anyDifficultActivities; } + public void setDurationInMinutes(int minutes) { + this.durationInMinutes = minutes; + } + public int getDurationInMinutes() { + return durationInMinutes; + } } diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/model/SelectedChildGS.java b/opensrp-chw/src/kk/java/org/smartregister/chw/model/SelectedChildGS.java index 63d08545b..8a99b3adb 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/model/SelectedChildGS.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/model/SelectedChildGS.java @@ -14,6 +14,12 @@ public class SelectedChildGS { private List accompanyingRelatives = null; + private List careGiverRepresentatives; + + private String otherCaregiverRepresentative; + + private String otherCompanion; + public SelectedChildGS(String childBaseEntityId, ChildStatus childSelectionStatus, boolean cameWithPrimaryCareGiver, String groupPlaced) { this.childBaseEntityId = childBaseEntityId; this.childSelectionStatus = childSelectionStatus; @@ -61,6 +67,29 @@ public void setAccompanyingRelatives(List accompanyingRelatives) { this.accompanyingRelatives = accompanyingRelatives; } + public List getCareGiverRepresentatives() { + return careGiverRepresentatives; + } + + public void setCareGiverRepresentatives(List careGiverRepresentatives) { + this.careGiverRepresentatives = careGiverRepresentatives; + } + + public String getOtherCaregiverRepresentative() { + return otherCaregiverRepresentative; + } + + public void setOtherCaregiverRepresentative(String otherCaregiverRepresentative) { + this.otherCaregiverRepresentative = otherCaregiverRepresentative; + } + + public String getOtherCompanion() { + return otherCompanion; + } + + public void setOtherCompanion(String otherCompanion) { + this.otherCompanion = otherCompanion; + } public enum ChildStatus { SELECTED, diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/provider/SelectChildForGroupSessionFragmentProvider.java b/opensrp-chw/src/kk/java/org/smartregister/chw/provider/SelectChildForGroupSessionFragmentProvider.java index 4a5a5bb8c..9dd580687 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/provider/SelectChildForGroupSessionFragmentProvider.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/provider/SelectChildForGroupSessionFragmentProvider.java @@ -19,6 +19,7 @@ import org.smartregister.chw.core.holders.RegisterViewHolder; import org.smartregister.chw.core.utils.ChildDBConstants; import org.smartregister.chw.holders.SelectChildGSViewHolder; +import org.smartregister.chw.model.MultiSelectListItemModel; import org.smartregister.chw.model.SelectedChildGS; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.commonregistry.CommonRepository; @@ -70,11 +71,14 @@ public HashMap getSelectedChildList() { return childList; } - public void updateChildSelectionStatus(String baseEntityId, boolean cameWithCareGiver, List accompanyingRelatives, String groupPlaced) { + public void updateChildSelectionStatus(String baseEntityId, boolean cameWithCareGiver, List accompanyingRelatives, String otherCompanion, String groupPlaced, List selectedCaregiverRepresentatives, String otherCaregiverRepresentative) { if (childList.containsKey(baseEntityId)) { Objects.requireNonNull(childList.get(baseEntityId)).setCameWithPrimaryCareGiver(cameWithCareGiver); Objects.requireNonNull(childList.get(baseEntityId)).setGroupPlaced(groupPlaced); Objects.requireNonNull(childList.get(baseEntityId)).setAccompanyingRelatives(accompanyingRelatives); + Objects.requireNonNull(childList.get(baseEntityId)).setOtherCompanion(otherCompanion); + Objects.requireNonNull(childList.get(baseEntityId)).setCareGiverRepresentatives(selectedCaregiverRepresentatives); + Objects.requireNonNull(childList.get(baseEntityId)).setOtherCaregiverRepresentative(otherCaregiverRepresentative); } } diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/util/KKAppHealthUtils.java b/opensrp-chw/src/kk/java/org/smartregister/chw/util/KKAppHealthUtils.java new file mode 100644 index 000000000..c0118a5a9 --- /dev/null +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/util/KKAppHealthUtils.java @@ -0,0 +1,18 @@ +package org.smartregister.chw.util; + +import android.view.View; + +import org.smartregister.util.AppHealthUtils; + +/** + * Author issyzac on 27/09/2023 + */ +public class KKAppHealthUtils extends AppHealthUtils { + + public KKAppHealthUtils(View view) { + super(view); + } + + + +} diff --git a/opensrp-chw/src/kk/java/org/smartregister/chw/util/KkConstants.java b/opensrp-chw/src/kk/java/org/smartregister/chw/util/KkConstants.java index c92420ff7..ef028da7c 100644 --- a/opensrp-chw/src/kk/java/org/smartregister/chw/util/KkConstants.java +++ b/opensrp-chw/src/kk/java/org/smartregister/chw/util/KkConstants.java @@ -130,6 +130,7 @@ public static class GCActivities { public static final String REVIEW_PREVIOUS_WEEK = "review_of_the_week"; public static final String ACTIVITY_1 = "activity_1"; public static final String ACTIVITY_2 = "activity_2"; + public static final String NUTRITION_ACTIVITY = "nutrition"; public static final String RECAP_SESSION = "recap_session"; public static final String CLOSING_SONG = "closing_song"; } @@ -157,6 +158,8 @@ public static class GCJsonKeys { public static final String GC_SESSION_ID = "session_id"; public static final String GC_SESSION_PLACE = "session_place"; public static final String GC_SESSION_DURATION = "session_duration"; + + public static final String GC_SESSION_DURATION_MINUTES = "session_duration_minutes"; public static final String GC_ACTIVITIES_TOOK_PLACE = "activities_took_place"; public static final String GC_DIVIDE_CHILDREN_DIFFERENT_AGE_GROUPS = "divide_children_different_age_groups"; @@ -173,7 +176,9 @@ public static class GCJsonKeys { public static final String GC_ALL_CAREGIVERS_PRESENT = "all_caregivers_present"; public static final String GC_CHILD_GROUP_PLACED = "child_group_placed"; public static final String GC_CHILD_CAME_WITH_OTHER_PEOPLE = "other_people_present"; - + public static final String GC_CHILD_CAME_WITH_OTHER_PEOPLE_OTHER = "other_people_present_other"; + public static final String GC_CAREGIVER_REPRESENTATIVES = "care_giver_representatives"; + public static final String GC_CAREGIVER_REPRESENTATIVES_OTHER = "care_giver_representatives_other"; } } diff --git a/opensrp-chw/src/kk/res/layout/dialog_fragment_childselection.xml b/opensrp-chw/src/kk/res/layout/dialog_fragment_childselection.xml index 823b3faaf..d9df29b72 100644 --- a/opensrp-chw/src/kk/res/layout/dialog_fragment_childselection.xml +++ b/opensrp-chw/src/kk/res/layout/dialog_fragment_childselection.xml @@ -99,23 +99,67 @@ android:divider="@color/transparent" /> + android:isScrollContainer="false" + android:overScrollMode="never"/> + + + + + + + + + + + + Hapana - Baba wa mtoto/Mpenzi wa mama - Ndugu wa mtoto (chin ya miaka 5) + Baba wa mtoto/Mwenza wa mama + Ndugu wa mtoto (chini ya miaka 5) Ndugu wa mtoto (miaka 5 au zaidi) Bibi wa mtoto Babu wa mtoto @@ -40,6 +40,7 @@ Kituo cha uhamasishaji na kutoa huduma za chanjo Shule ya primari Chini ya mti + Sehemu ya Ibada Ugawanywaji wa watoto kwenye makundi diff --git a/opensrp-chw/src/kk/res/values-sw/strings.xml b/opensrp-chw/src/kk/res/values-sw/strings.xml index 01ffb508f..e27fcaeb2 100644 --- a/opensrp-chw/src/kk/res/values-sw/strings.xml +++ b/opensrp-chw/src/kk/res/values-sw/strings.xml @@ -154,8 +154,9 @@ Taarifa za mahudhurio ya mtoto Je mtoto amekuja na mlezi wake %s? Je mtoto aliwekwa kwenye grupu gani? + Mtu gani ambae alikuja kwa niaba ya mlezi wa mtoto? Ukiachana na mama mzazi wa mtoto, ni walezi gani wengine ambao walihudhuria? - Watu gani wengine ambao walikuja kwa niaba ya mlezi wa mtoto? + Ukiachana na mlezi ambaye alikuja kwa niaba ya mzazi wa mtoto, ni walezi gani wengine ambao walihudhuria? Chagua Mtoto Aliyehudhuria Je uliwatenganisha watoto kwenye makundi tofauti? Tarehe ya kipindi @@ -204,5 +205,13 @@ Tafadhali chagua kama watoto waligawanywa kwenye makundi au la Tafadhali chagua sababu za kipindi kutokutokea Muda wa kipingi kwenye saa na dakika - + Mwingine + Mlezi mwingine + Mtu mwingine + Tafadhari chagua mtu ambae alikuja kwa niaba ya mlezi wa mtoto + Tafadhari jaza mtu mwingine ambae alikuja kwa niaba ya mlezi wa mtoto + Tafadhari chagua walezi/watu wengine waliohudhuria + Tafadhari jaza mlezi/mtu mwingine aliyehudhuria + Tafadhari bainisha kama mtoto amekuja na mlezi wake + Tafadhari chagua kundi la mototo \ No newline at end of file diff --git a/opensrp-chw/src/kk/res/values/array.xml b/opensrp-chw/src/kk/res/values/array.xml index 3cfab9ca0..906baa290 100644 --- a/opensrp-chw/src/kk/res/values/array.xml +++ b/opensrp-chw/src/kk/res/values/array.xml @@ -43,7 +43,8 @@ Participant house Outreach vaccination point Primary School - Under the tree> + Under the tree + Place of worship Divided children into different age groups? diff --git a/opensrp-chw/src/kk/res/values/strings.xml b/opensrp-chw/src/kk/res/values/strings.xml index ce2b381fb..f928c8263 100644 --- a/opensrp-chw/src/kk/res/values/strings.xml +++ b/opensrp-chw/src/kk/res/values/strings.xml @@ -174,7 +174,8 @@ Did the child come with their caregiver %s? Select the group Which other people were present beyond the caregiver? - What is the child\' relationship to the adult that came on behalf of primary caregiver + What is the child\'s relationship to the adult that came on behalf of primary caregiver + Which other people were present beyond the person who came on behalf of the Primary Care giver? Select Child Present Did you divide children into different age groups? Select session date @@ -223,5 +224,13 @@ Please indicate the reason for the session to not take place Please indicate whether children were divided into groups or not Session Duration in Hours and Minutes - + Other + Other caregiver + Other companion + Caregiver representatives missing + Other caregiver representative missing + The companions of caregiver missing + Other companion of caregiver missing + Caregiver information missing + Child missing the group \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/domain/CleanEDIStatus.java b/opensrp-chw/src/main/java/org/smartregister/chw/domain/CleanEDIStatus.java new file mode 100644 index 000000000..958ecbeb8 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/domain/CleanEDIStatus.java @@ -0,0 +1,21 @@ +package org.smartregister.chw.domain; + +/** + * Author issyzac on 27/09/2023 + */ +public enum CleanEDIStatus { + + CLEANED ("CLEANED"), + PENDING ("PENDING"); + + private String value; + + private CleanEDIStatus(String value){ + this.value = value; + } + + public String value(){ + return this.value; + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyProfileInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyProfileInteractor.java index 13dbf337f..81b65cf7c 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyProfileInteractor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyProfileInteractor.java @@ -2,8 +2,23 @@ import androidx.annotation.VisibleForTesting; +import org.json.JSONArray; +import org.json.JSONObject; import org.smartregister.chw.core.interactor.CoreFamilyProfileInteractor; +import org.smartregister.clientandeventmodel.Client; +import org.smartregister.clientandeventmodel.Event; +import org.smartregister.domain.db.EventClient; +import org.smartregister.family.contract.FamilyProfileContract; +import org.smartregister.family.domain.FamilyEventClient; import org.smartregister.family.util.AppExecutors; +import org.smartregister.family.util.JsonFormUtils; +import org.smartregister.family.util.Utils; +import org.smartregister.view.activity.DrishtiApplication; + +import java.util.Collections; +import java.util.Date; + +import timber.log.Timber; public class FamilyProfileInteractor extends CoreFamilyProfileInteractor { @@ -16,4 +31,89 @@ public FamilyProfileInteractor() { super(); } + @Override + public void saveRegistration(FamilyEventClient familyEventClient, String jsonString, boolean isEditMode, FamilyProfileContract.InteractorCallBack callBack) { + Runnable runnable = new Runnable() { + public void run() { + final boolean isSaved = FamilyProfileInteractor.this.saveRegistration(familyEventClient, jsonString, isEditMode); + FamilyProfileInteractor.this.appExecutors.mainThread().execute(new Runnable() { + public void run() { + callBack.onRegistrationSaved(isEditMode, isSaved, familyEventClient); + } + }); + } + }; + this.appExecutors.diskIO().execute(runnable); + } + + private boolean saveRegistration(FamilyEventClient familyEventClient, String jsonString, boolean isEditMode) { + try { + Client baseClient = familyEventClient.getClient(); + Event baseEvent = familyEventClient.getEvent(); + JSONObject eventJson = null; + JSONObject clientJson = null; + + if (baseClient != null) { + clientJson = new JSONObject(JsonFormUtils.gson.toJson(baseClient)); + if (isEditMode) { + JsonFormUtils.mergeAndSaveClient(this.getSyncHelper(), baseClient); + } else { + this.getSyncHelper().addClient(baseClient.getBaseEntityId(), clientJson); + } + } + + if (baseEvent != null) { + eventJson = new JSONObject(JsonFormUtils.gson.toJson(baseEvent)); + this.getSyncHelper().addEvent(baseEvent.getBaseEntityId(), eventJson); + } + + String newOpenSRPId; + if (isEditMode) { + if (baseClient != null) { + newOpenSRPId = baseClient.getIdentifier(Utils.metadata().uniqueIdentifierKey); + if (newOpenSRPId != null) { + newOpenSRPId.replace("-", ""); + String currentOpenSRPId = JsonFormUtils.getString(jsonString, "current_opensrp_id").replace("-", ""); + if (!newOpenSRPId.equals(currentOpenSRPId)) { + this.getUniqueIdRepository().open(currentOpenSRPId); + } + } + } + } else if (baseClient != null) { + newOpenSRPId = baseClient.getIdentifier(Utils.metadata().uniqueIdentifierKey); + this.getUniqueIdRepository().close(newOpenSRPId); + + //Note: EDI ID registration event is only created during first registration + //of the client. During editing we will not create another registration event + + //EDI ID registration fields + JSONObject form = new JSONObject(jsonString); + JSONArray fields = JsonFormUtils.fields(form); + + String baseEntityId = baseClient.getBaseEntityId(); + String ediId = JsonFormUtils.getFieldValue(fields, "edi_id"); + + //Process EDI ID registration event + org.smartregister.chw.util.JsonFormUtils.processEdiRegistrationEvent(baseEntityId, ediId, clientJson, + DrishtiApplication.getInstance().getContext().allSharedPreferences(), isEditMode); + + } + + if (baseClient != null || baseEvent != null) { + newOpenSRPId = JsonFormUtils.getFieldValue(jsonString, "photo"); + JsonFormUtils.saveImage(baseEvent.getProviderId(), baseClient.getBaseEntityId(), newOpenSRPId); + } + + long lastSyncTimeStamp = this.getAllSharedPreferences().fetchLastUpdatedAtDate(0L); + Date lastSyncDate = new Date(lastSyncTimeStamp); + org.smartregister.domain.Event domainEvent = (org.smartregister.domain.Event)JsonFormUtils.gson.fromJson(eventJson.toString(), org.smartregister.domain.Event.class); + org.smartregister.domain.Client domainClient = (org.smartregister.domain.Client)JsonFormUtils.gson.fromJson(clientJson.toString(), org.smartregister.domain.Client.class); + this.processClient(Collections.singletonList(new EventClient(domainEvent, domainClient))); + this.getAllSharedPreferences().saveLastUpdatedAtDate(lastSyncDate.getTime()); + return true; + } catch (Exception var13) { + Timber.e(var13); + return false; + } + } } diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyRegisterInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyRegisterInteractor.java index 2057a11ff..b59883e58 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyRegisterInteractor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/FamilyRegisterInteractor.java @@ -16,6 +16,7 @@ import org.smartregister.family.domain.FamilyEventClient; import org.smartregister.family.util.JsonFormUtils; import org.smartregister.family.util.Utils; +import org.smartregister.view.activity.DrishtiApplication; import java.util.ArrayList; import java.util.Date; @@ -108,6 +109,20 @@ private boolean saveRegistration(List familyEventClientList, } } + if (baseClient != null && !baseClient.getClientType().equalsIgnoreCase("Family")){ + + //EDI ID registration fields + JSONObject form = new JSONObject(jsonString); + JSONArray fields = JsonFormUtils.fields(form); + + String baseEntityId = baseClient.getBaseEntityId(); + String ediId = JsonFormUtils.getFieldValue(fields, "edi_id"); + + //Process EDI ID registration event + org.smartregister.chw.util.JsonFormUtils.processEdiRegistrationEvent(baseEntityId, ediId, clientJson, + DrishtiApplication.getInstance().getContext().allSharedPreferences(), isEditMode); + } + if (baseClient != null || baseEvent != null) { imageLocation = null; if (i == 0) { diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/GroupSessionInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/GroupSessionInteractor.java index 80c0dd2c0..0bc300627 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/GroupSessionInteractor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/GroupSessionInteractor.java @@ -304,6 +304,15 @@ private void processChildPopulatableFields(JSONObject field, GroupSessionModel s case KkConstants.GCJsonKeys.GC_CHILD_CAME_WITH_OTHER_PEOPLE: field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, selectedChildGS.getAccompanyingRelatives()); break; + case KkConstants.GCJsonKeys.GC_CAREGIVER_REPRESENTATIVES: + field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, selectedChildGS.getCareGiverRepresentatives()); + break; + case KkConstants.GCJsonKeys.GC_CAREGIVER_REPRESENTATIVES_OTHER: + field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, selectedChildGS.getOtherCaregiverRepresentative()); + break; + case KkConstants.GCJsonKeys.GC_CHILD_CAME_WITH_OTHER_PEOPLE_OTHER: + field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, selectedChildGS.getOtherCompanion()); + break; default: break; } @@ -327,6 +336,9 @@ private void processPopulatableFields(JSONObject field, GroupSessionModel sessio case KkConstants.GCJsonKeys.GC_SESSION_DURATION: field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, sessionModel.getDurationInHours()); break; + case KkConstants.GCJsonKeys.GC_SESSION_DURATION_MINUTES: + field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, sessionModel.getDurationInMinutes()); + break; case KkConstants.GCJsonKeys.GC_ACTIVITIES_TOOK_PLACE: field.put(org.smartregister.chw.util.JsonFormUtils.VALUE, sessionModel.getActivitiesTookPlace()); break; diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginInteractor.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginInteractor.java index 4baa21018..77fcdd273 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginInteractor.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginInteractor.java @@ -1,9 +1,18 @@ package org.smartregister.chw.interactor; +import androidx.work.PeriodicWorkRequest; +import androidx.work.WorkManager; +import androidx.work.WorkRequest; + +import org.smartregister.CoreLibrary; import org.smartregister.chw.contract.LoginJobScheduler; +import org.smartregister.chw.job.IdentifierCleanerWorker; +import org.smartregister.job.DuplicateCleanerWorker; import org.smartregister.login.interactor.BaseLoginInteractor; import org.smartregister.view.contract.BaseLoginContract; +import java.util.concurrent.TimeUnit; + /*** * @author rkodev @@ -23,11 +32,22 @@ public LoginInteractor(BaseLoginContract.Presenter loginPresenter) { @Override protected void scheduleJobsPeriodically() { scheduler.scheduleJobsPeriodically(); + //Schedule your jobs here + } @Override protected void scheduleJobsImmediately() { super.scheduleJobsImmediately(); scheduler.scheduleJobsImmediately(); + scheduleIdCleanerWorker(); + } + + private void scheduleIdCleanerWorker(){ + WorkRequest identifierCleaner = new PeriodicWorkRequest.Builder(IdentifierCleanerWorker.class, 1, TimeUnit.MINUTES) + .build(); + WorkManager.getInstance(CoreLibrary.getInstance().context().applicationContext()).enqueue(identifierCleaner); + } + } \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java index 7f5637d6e..eff8ce756 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/interactor/LoginJobSchedulerProvider.java @@ -53,6 +53,9 @@ public void scheduleJobsPeriodically() { if (BuildConfig.USE_UNIFIED_REFERRAL_APPROACH) DocumentConfigurationServiceJob.scheduleJob(DocumentConfigurationServiceJob.TAG,TimeUnit.MINUTES.toMinutes(BuildConfig.DATA_SYNC_DURATION_MINUTES), getFlexValue(BuildConfig.DATA_SYNC_DURATION_MINUTES)); + + + } @Override diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/job/IdentifierCleanerWorker.java b/opensrp-chw/src/main/java/org/smartregister/chw/job/IdentifierCleanerWorker.java new file mode 100644 index 000000000..db3857bf4 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/job/IdentifierCleanerWorker.java @@ -0,0 +1,54 @@ +package org.smartregister.chw.job; + +import android.content.Context; + +import androidx.annotation.NonNull; +import androidx.work.WorkManager; +import androidx.work.Worker; +import androidx.work.WorkerParameters; + +import org.smartregister.CoreLibrary; +import org.smartregister.chw.domain.CleanEDIStatus; +import org.smartregister.chw.repository.KKEventClientRepository; + +import timber.log.Timber; + +/** + * Author issyzac on 27/09/2023 + */ +public class IdentifierCleanerWorker extends Worker { + + private Context context; + public static final String TAG = "IdentifierCleanerWorker"; + KKEventClientRepository repository; + + public IdentifierCleanerWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { + super(context, workerParams); + this.context = context; + repository = new KKEventClientRepository(); + } + + @NonNull + @Override + public Result doWork() { + CleanEDIStatus cleanEDIStatus = null; + try { + cleanEDIStatus = DoClean(); + } catch (Exception e) { + e.printStackTrace(); + } + Timber.i("Doing some cleaning work"); + + // Remove worker if everything has been cleaned + if (cleanEDIStatus != null && cleanEDIStatus.equals(CleanEDIStatus.CLEANED)) + WorkManager.getInstance(context).cancelWorkById(this.getId()); + + return Result.success(); + } + + private CleanEDIStatus DoClean() throws Exception { + // Call repository to clean the IDs + return repository.removeEdiIdsFromClients(); + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/repository/EdiIdCleanUpRepository.java b/opensrp-chw/src/main/java/org/smartregister/chw/repository/EdiIdCleanUpRepository.java new file mode 100644 index 000000000..2b5f47752 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/repository/EdiIdCleanUpRepository.java @@ -0,0 +1,56 @@ +package org.smartregister.chw.repository; + +import android.annotation.SuppressLint; +import android.database.Cursor; +import android.util.Log; + +import org.smartregister.repository.BaseRepository; + +import java.util.HashMap; +import java.util.Map; + +import timber.log.Timber; + +/** + * Created by Kassim Sheghembe on 2023-09-27 + */ +public class EdiIdCleanUpRepository extends BaseRepository { + + private static final String BASE_ENTITY_ID = "baseEntityId"; + + public static final String CLIENTS_WITH_EDI_IDS_SQL = "WITH clients AS (" + + "SELECT " + + "baseEntityId, " + + "COALESCE(json_extract(json, '$.identifiers.edi_id'), json_extract(json, '$.identifiers.mother_edi_id')) as edi_id " + + "FROM client " + + ")" + + "select * from clients where edi_id is not null"; + + public Map clientsWithEdiIds() { + + Map ediIds = new HashMap<>(); + + Cursor cursor = null; + + try { + cursor = getReadableDatabase().rawQuery(CLIENTS_WITH_EDI_IDS_SQL, new String[]{}); + + while (cursor.moveToNext()) { + @SuppressLint("Range") String baseEntityId = cursor.getString(cursor.getColumnIndex(BASE_ENTITY_ID)); + @SuppressLint("Range") String ediId = cursor.getString(cursor.getColumnIndex("edi_id")); + + ediIds.put(baseEntityId, ediId); + } + + } catch (Exception e) { + Log.e("ERRRRORRRRR", e.getMessage()); + Timber.e(e); + } + finally { + if (cursor != null && !cursor.isClosed()) + cursor.close(); + } + + return ediIds; + } +} \ No newline at end of file diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/repository/KKEventClientRepository.java b/opensrp-chw/src/main/java/org/smartregister/chw/repository/KKEventClientRepository.java new file mode 100644 index 000000000..3adfacd76 --- /dev/null +++ b/opensrp-chw/src/main/java/org/smartregister/chw/repository/KKEventClientRepository.java @@ -0,0 +1,91 @@ +package org.smartregister.chw.repository; + +import static org.smartregister.chw.util.JsonFormUtils.processEdiRegistrationEvent; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.json.JSONObject; +import org.smartregister.AllConstants; +import org.smartregister.Context; +import org.smartregister.chw.application.ChwApplication; +import org.smartregister.chw.domain.CleanEDIStatus; +import org.smartregister.domain.Event; +import org.smartregister.domain.Client; +import org.smartregister.domain.Obs; +import org.smartregister.domain.db.EventClient; +import org.smartregister.family.FamilyLibrary; +import org.smartregister.repository.AllSharedPreferences; +import org.smartregister.repository.BaseRepository; +import org.smartregister.repository.EventClientRepository; +import org.smartregister.util.JsonFormUtils; +import org.smartregister.util.Utils; +import org.smartregister.view.activity.DrishtiApplication; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import timber.log.Timber; + +/** + * Author issyzac on 27/09/2023 + */ +public class KKEventClientRepository extends EventClientRepository { + + public KKEventClientRepository(){} + + public CleanEDIStatus removeEdiIdsFromClients() throws Exception { + + String username = Context.getInstance().userService().getAllSharedPreferences().fetchRegisteredANM(); + + EdiIdCleanUpRepository ediIdCleanUpRepository = new EdiIdCleanUpRepository(); + + Map clientsWithEdiIds = ediIdCleanUpRepository.clientsWithEdiIds(); + + if (clientsWithEdiIds.size() == 0) + return CleanEDIStatus.CLEANED; + + //TODO: Change to Firebase events + Timber.e("%d duplicates for provider: %s - %s", clientsWithEdiIds.size(), username, ediIdCleanUpRepository.toString()); + + for (Map.Entry clientWithEdiId : clientsWithEdiIds.entrySet()) { + + String baseEntityId = clientWithEdiId.getKey(); + String ediId = clientWithEdiId.getValue(); + + JSONObject clientJson = getClientByBaseEntityId(baseEntityId); + JSONObject identifiers = clientJson.getJSONObject(AllConstants.IDENTIFIERS); + + String identifierLabel = identifiers.has("edi_id") ? "edi_id" + : identifiers.has("mother_edi_id") ? "mother_edi_id" : ""; + + if (!identifierLabel.equals("")){ + identifiers.remove(identifierLabel); + updateClientObject(clientJson, identifiers, baseEntityId, ediId); + } + + } + + return CleanEDIStatus.CLEANED; + + } + + private void updateClientObject(JSONObject clientJson, JSONObject identifiers, String baseEntityId, String ediID){ + try { + clientJson.put(AllConstants.IDENTIFIERS, identifiers); + + // Update client Object + addorUpdateClient(baseEntityId, clientJson); + + //Process new EDI ID registration event + processEdiRegistrationEvent(baseEntityId, ediID, clientJson, DrishtiApplication.getInstance().getContext().allSharedPreferences(), false); + + } + catch (Exception e){ + e.printStackTrace(); + } + + } + +} diff --git a/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java b/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java index 047d3a84b..23aabbaf5 100644 --- a/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java +++ b/opensrp-chw/src/main/java/org/smartregister/chw/util/JsonFormUtils.java @@ -10,6 +10,7 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Triple; import org.jetbrains.annotations.NotNull; +import org.joda.time.DateTime; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -25,6 +26,7 @@ import org.smartregister.commonregistry.CommonPersonObject; import org.smartregister.commonregistry.CommonPersonObjectClient; import org.smartregister.domain.Photo; +import org.smartregister.domain.db.EventClient; import org.smartregister.domain.tag.FormTag; import org.smartregister.family.FamilyLibrary; import org.smartregister.family.domain.FamilyEventClient; @@ -38,11 +40,13 @@ import org.smartregister.util.AssetHandler; import org.smartregister.util.FormUtils; import org.smartregister.util.ImageUtils; +import org.smartregister.view.activity.DrishtiApplication; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -83,83 +87,64 @@ public static Event tagSyncMetadata(AllSharedPreferences allSharedPreferences, E return event; } + public static void processEdiRegistrationEvent(String baseEntityId, String ediID, JSONObject clientJson, AllSharedPreferences sharedPreferences, boolean isEditMode){ - - /** - * @issyzac - * Removed from the family library to get the family details from the second step of the form instead of the - * first as implemented in the library - * @param allSharedPreferences - * @param jsonString - * @return - */ - public static FamilyEventClient processFamilyUpdateForm(AllSharedPreferences allSharedPreferences, String jsonString) { try { - String familyStep = org.smartregister.family.util.Utils.getCustomConfigs("family_form_image_step"); - Triple registrationFormParams = StringUtils.isBlank(familyStep) ? validateParameters(jsonString, "step1") : validateParameters(jsonString, familyStep); - if (!(Boolean)registrationFormParams.getLeft()) { - return null; - } else { - JSONObject jsonForm = (JSONObject)registrationFormParams.getMiddle(); - JSONArray fields = (JSONArray)registrationFormParams.getRight(); - String entityId = getString(jsonForm, "entity_id"); - if (StringUtils.isBlank(entityId)) { - entityId = generateRandomUUIDString(); - } - lastInteractedWith(fields); - dobUnknownUpdateFromAge(fields); - Client baseClient = org.smartregister.util.JsonFormUtils.createBaseClient(fields, formTag(allSharedPreferences), entityId); - baseClient.setLastName("Family"); - baseClient.setBirthdate(new Date(0L)); - baseClient.setGender("Male"); - baseClient.setClientType("Family"); - Event baseEvent = org.smartregister.util.JsonFormUtils.createEvent(fields, getJSONObject(jsonForm, "metadata"), formTag(allSharedPreferences), entityId, org.smartregister.family.util.Utils.metadata().familyRegister.registerEventType, org.smartregister.family.util.Utils.metadata().familyRegister.tableName); - tagSyncMetadata(allSharedPreferences, baseEvent); - return new FamilyEventClient(baseClient, baseEvent); - } - } catch (Exception var9) { - Timber.e(var9); - return null; + EventClientRepository eventClientRepository = new EventClientRepository(); + String encounterType = isEditMode ? "Update Client Edi ID" : "Register Client Edi ID"; + + org.smartregister.domain.Event event = (new org.smartregister.domain.Event()) + .withBaseEntityId(baseEntityId) + .withEventType(encounterType) + .withEventDate(new DateTime()) + .withEntityType("client") + .withFormSubmissionId(org.smartregister.util.JsonFormUtils.generateRandomUUIDString()); + + //Add EDI ID as observation to the registration event + org.smartregister.domain.Obs edi_id_obs = new org.smartregister.domain.Obs(); + edi_id_obs.setFieldCode("edi_id"); + edi_id_obs.setFieldType("concept"); + edi_id_obs.setFieldDataType("text"); + edi_id_obs.setParentCode(""); + edi_id_obs.setValue(ediID); + edi_id_obs.setFormSubmissionField("edi_id"); + edi_id_obs.setHumanReadableValue(ediID); + + event.addObs(edi_id_obs); + + eventClientRepository.addEvent(baseEntityId, eventClientRepository.convertToJson(tagSyncMetadata(sharedPreferences, event))); + + ChwApplication.getInstance().getClientProcessor().processClient(Collections.singletonList(new EventClient(event, eventClientRepository.convert(clientJson, org.smartregister.domain.Client.class)))); + + }catch (Exception e){ + e.printStackTrace(); } + } - /** - * @issyzac - * Removed from the family library to get the head of the house (Pregnant mother in Kizazi Kijacho) from the third step and not the second as - * originally implemented - * - * @param allSharedPreferences - * @param jsonString - * @param familyBaseEntityId - * @return - */ - public static FamilyEventClient processFamilyHeadRegistrationForm(AllSharedPreferences allSharedPreferences, String jsonString, String familyBaseEntityId) { - try { - String familyStep = org.smartregister.family.util.Utils.getCustomConfigs("family_member_form_image_step"); - Triple registrationFormParams = StringUtils.isBlank(familyStep) ? validateParameters(jsonString, "step2") : validateParameters(jsonString, familyStep); - if (!(Boolean)registrationFormParams.getLeft()) { - return null; - } else { - JSONObject jsonForm = (JSONObject)registrationFormParams.getMiddle(); - JSONArray fields = (JSONArray)registrationFormParams.getRight(); - String entityId = getString(jsonForm, "entity_id"); - if (StringUtils.isBlank(entityId)) { - entityId = generateRandomUUIDString(); - } + public static org.smartregister.domain.Event tagSyncMetadata(AllSharedPreferences allSharedPreferences, org.smartregister.domain.Event event) { + String providerId = allSharedPreferences.fetchRegisteredANM(); + event.setProviderId(providerId); + event.setLocationId(locationId(allSharedPreferences)); + event.setChildLocationId(allSharedPreferences.fetchCurrentLocality()); + event.setTeam(allSharedPreferences.fetchDefaultTeam(providerId)); + event.setTeamId(allSharedPreferences.fetchDefaultTeamId(providerId)); - lastInteractedWith(fields); - dobUnknownUpdateFromAge(fields); - Client baseClient = org.smartregister.util.JsonFormUtils.createBaseClient(fields, formTag(allSharedPreferences), entityId); - baseClient.addRelationship(org.smartregister.family.util.Utils.metadata().familyMemberRegister.familyRelationKey, familyBaseEntityId); - Event baseEvent = org.smartregister.util.JsonFormUtils.createEvent(fields, getJSONObject(jsonForm, "metadata"), formTag(allSharedPreferences), entityId, org.smartregister.family.util.Utils.metadata().familyMemberRegister.registerEventType, org.smartregister.family.util.Utils.metadata().familyMemberRegister.tableName); - tagSyncMetadata(allSharedPreferences, baseEvent); - return new FamilyEventClient(baseClient, baseEvent); - } - } catch (Exception var10) { - Timber.e(var10); - return null; + event.setClientApplicationVersion(FamilyLibrary.getInstance().getApplicationVersion()); + event.setClientDatabaseVersion(FamilyLibrary.getInstance().getDatabaseVersion()); + + return event; + } + + protected static String locationId(AllSharedPreferences allSharedPreferences) { + String providerId = allSharedPreferences.fetchRegisteredANM(); + String userLocationId = allSharedPreferences.fetchUserLocalityId(providerId); + if (StringUtils.isBlank(userLocationId)) { + userLocationId = allSharedPreferences.fetchDefaultLocalityId(providerId); } + + return userLocationId; } public static Pair processChildRegistrationForm(AllSharedPreferences allSharedPreferences, String jsonString) { @@ -264,347 +249,6 @@ private static void processChildEnrollMent(JSONObject jsonForm, JSONArray fields } - private static String processValueWithChoiceIds(JSONObject jsonObject, String value) { - try { - //spinner - if (jsonObject.has("openmrs_choice_ids")) { - JSONObject choiceObject = jsonObject.getJSONObject("openmrs_choice_ids"); - - for (int i = 0; i < choiceObject.names().length(); i++) { - if (value.equalsIgnoreCase(choiceObject.getString(choiceObject.names().getString(i)))) { - value = choiceObject.names().getString(i); - } - } - - - }//checkbox - else if (jsonObject.has(Constants.JSON_FORM_KEY.OPTIONS)) { - JSONArray option_array = jsonObject.getJSONArray(Constants.JSON_FORM_KEY.OPTIONS); - for (int i = 0; i < option_array.length(); i++) { - JSONObject option = option_array.getJSONObject(i); - if (value.contains(option.getString("key"))) { - option.put("value", "true"); - } - } - } - - } catch (Exception e) { - Timber.e(e); - } - return value; - } - - protected static void processPopulatableFields(CommonPersonObjectClient client, JSONObject jsonObject) throws JSONException { - - switch (jsonObject.getString(org.smartregister.family.util.JsonFormUtils.KEY).toLowerCase()) { - case Constants.JSON_FORM_KEY.DOB_UNKNOWN: - jsonObject.put(org.smartregister.family.util.JsonFormUtils.READ_ONLY, false); - JSONObject optionsObject = jsonObject.getJSONArray(Constants.JSON_FORM_KEY.OPTIONS).getJSONObject(0); - optionsObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), Constants.JSON_FORM_KEY.DOB_UNKNOWN, false)); - - break; - case DBConstants.KEY.DOB: - - String dobString = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.DOB, false); - if (StringUtils.isNotBlank(dobString)) { - Date dob = Utils.dobStringToDate(dobString); - if (dob != null) { - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, dd_MM_yyyy.format(dob)); - } - } - - break; - - case Constants.KEY.PHOTO: - - Photo photo = ImageUtils.profilePhotoByClientID(client.getCaseId(), Utils.getProfileImageResourceIDentifier()); - if (StringUtils.isNotBlank(photo.getFilePath())) { - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, photo.getFilePath()); - } - - break; - - case DBConstants.KEY.UNIQUE_ID: - - String uniqueId = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.UNIQUE_ID, false); - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, uniqueId.replace("-", "")); - - break; - - case "fam_name": - - String fam_name = Utils.getValue(client.getColumnmaps(), DBConstants.KEY.FIRST_NAME, false); - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, fam_name); - - break; - - case DBConstants.KEY.VILLAGE_TOWN: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.VILLAGE_TOWN, false)); - - break; - - case DBConstants.KEY.QUATER_CLAN: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.QUATER_CLAN, false)); - - break; - - case DBConstants.KEY.STREET: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.STREET, false)); - - break; - - case DBConstants.KEY.LANDMARK: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.LANDMARK, false)); - - break; - - case DBConstants.KEY.FAMILY_SOURCE_INCOME: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.FAMILY_SOURCE_INCOME, false)); - - break; - - case ChwDBConstants.NEAREST_HEALTH_FACILITY: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), ChwDBConstants.NEAREST_HEALTH_FACILITY, false)); - - break; - - case DBConstants.KEY.GPS: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.GPS, false)); - - break; - - case ChwDBConstants.EVENT_DATE: - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), ChwDBConstants.EVENT_DATE, false)); - - break; - - default: - - Timber.e("ERROR:: Unprocessed Form Object Key " + jsonObject.getString(org.smartregister.family.util.JsonFormUtils.KEY)); - - break; - - } - - if (jsonObject.getString(org.smartregister.family.util.JsonFormUtils.KEY).equalsIgnoreCase(DBConstants.KEY.DOB)) { - - jsonObject.put(org.smartregister.family.util.JsonFormUtils.READ_ONLY, false); - JSONObject optionsObject = jsonObject.getJSONArray(Constants.JSON_FORM_KEY.OPTIONS).getJSONObject(0); - optionsObject.put(org.smartregister.family.util.JsonFormUtils.VALUE, Utils.getValue(client.getColumnmaps(), DBConstants.KEY.DOB, false)); - - } - } - - public static Vaccine tagSyncMetadata(AllSharedPreferences allSharedPreferences, Vaccine vaccine) { - String providerId = allSharedPreferences.fetchRegisteredANM(); - vaccine.setAnmId(providerId); - vaccine.setLocationId(locationId(allSharedPreferences)); - vaccine.setChildLocationId(allSharedPreferences.fetchCurrentLocality()); - vaccine.setTeam(allSharedPreferences.fetchDefaultTeam(providerId)); - vaccine.setTeamId(allSharedPreferences.fetchDefaultTeamId(providerId)); - return vaccine; - } - - public static ServiceRecord tagSyncMetadata(AllSharedPreferences allSharedPreferences, ServiceRecord serviceRecord) { - String providerId = allSharedPreferences.fetchRegisteredANM(); - serviceRecord.setAnmId(providerId); - serviceRecord.setLocationId(locationId(allSharedPreferences)); - serviceRecord.setChildLocationId(allSharedPreferences.fetchCurrentLocality()); - serviceRecord.setTeam(allSharedPreferences.fetchDefaultTeam(providerId)); - serviceRecord.setTeamId(allSharedPreferences.fetchDefaultTeamId(providerId)); - return serviceRecord; - } - - /** - * @param familyID - * @param allSharedPreferences - * @param jsonObject - * @param providerId - * @return Returns a triple object DateOfDeath as String, BaseEntityID , List of Events that should be processed - */ - public static Triple, String, List> processRemoveMemberEvent(String familyID, AllSharedPreferences allSharedPreferences, JSONObject jsonObject, String providerId) { - - try { - - List events = new ArrayList<>(); - - Triple registrationFormParams = validateParameters(jsonObject.toString()); - - if (!registrationFormParams.getLeft()) { - return null; - } - - Date dod = null; - - - JSONObject metadata = getJSONObject(registrationFormParams.getMiddle(), METADATA); - String memberID = getString(registrationFormParams.getMiddle(), ENTITY_ID); - - JSONArray fields = new JSONArray(); - - int x = 0; - while (x < registrationFormParams.getRight().length()) { - //JSONObject obj = registrationFormParams.getRight().getJSONObject(x); - String myKey = registrationFormParams.getRight().getJSONObject(x).getString(KEY); - - if (myKey.equalsIgnoreCase(org.smartregister.chw.util.Constants.FORM_CONSTANTS.REMOVE_MEMBER_FORM.DATE_MOVED) || - myKey.equalsIgnoreCase(org.smartregister.chw.util.Constants.FORM_CONSTANTS.REMOVE_MEMBER_FORM.REASON) - ) { - fields.put(registrationFormParams.getRight().get(x)); - } - if (myKey.equalsIgnoreCase(org.smartregister.chw.util.Constants.FORM_CONSTANTS.REMOVE_MEMBER_FORM.DATE_DIED)) { - fields.put(registrationFormParams.getRight().get(x)); - try { - dod = dd_MM_yyyy.parse(registrationFormParams.getRight().getJSONObject(x).getString(VALUE)); - } catch (Exception e) { - Timber.d(e.toString()); - } - } - x++; - } - - String encounterType = getString(jsonObject, ENCOUNTER_TYPE); - - String eventType; - String tableName; - - if (encounterType.equalsIgnoreCase(org.smartregister.chw.util.Constants.EventType.REMOVE_CHILD)) { - eventType = org.smartregister.chw.util.Constants.EventType.REMOVE_CHILD; - tableName = org.smartregister.chw.util.Constants.TABLE_NAME.CHILD; - } else if (encounterType.equalsIgnoreCase(org.smartregister.chw.util.Constants.EventType.REMOVE_FAMILY)) { - eventType = org.smartregister.chw.util.Constants.EventType.REMOVE_FAMILY; - tableName = org.smartregister.chw.util.Constants.TABLE_NAME.FAMILY; - } else { - eventType = org.smartregister.chw.util.Constants.EventType.REMOVE_MEMBER; - tableName = org.smartregister.chw.util.Constants.TABLE_NAME.FAMILY_MEMBER; - } - - Event eventMember = JsonFormUtils.createEvent(fields, metadata, formTag(allSharedPreferences), memberID, - eventType, - tableName - ); - JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), eventMember); - events.add(eventMember); - - - return Triple.of(Pair.create(dod, encounterType), memberID, events); - } catch (Exception e) { - Timber.e(e.toString()); - return null; - } - } - - public static FamilyMember getFamilyMemberFromRegistrationForm(String jsonString, String familyBaseEntityId, String entityID) throws JSONException { - FamilyMember member = new FamilyMember(); - - Triple registrationFormParams = validateParameters(jsonString); - if (!registrationFormParams.getLeft()) { - return null; - } - - JSONArray fields = registrationFormParams.getRight(); - - member.setFamilyID(familyBaseEntityId); - member.setMemberID(entityID); - member.setPhone(getJsonFieldValue(fields, org.smartregister.chw.util.Constants.JsonAssets.FAMILY_MEMBER.PHONE_NUMBER)); - member.setOtherPhone(getJsonFieldValue(fields, org.smartregister.chw.util.Constants.JsonAssets.FAMILY_MEMBER.OTHER_PHONE_NUMBER)); - member.setEduLevel(getJsonFieldValue(fields, org.smartregister.chw.util.Constants.JsonAssets.FAMILY_MEMBER.HIGHEST_EDUCATION_LEVEL)); - member.setPrimaryCareGiver( - getJsonFieldValue(fields, org.smartregister.chw.util.Constants.JsonAssets.PRIMARY_CARE_GIVER).equalsIgnoreCase("Yes") || - getJsonFieldValue(fields, org.smartregister.chw.util.Constants.JsonAssets.IS_PRIMARY_CARE_GIVER).equalsIgnoreCase("Yes") - ); - member.setFamilyHead(false); - - return member; - } - - public static Pair, List> processFamilyUpdateRelations(Context context, FamilyMember familyMember, String lastLocationId) throws Exception { - List clients = new ArrayList<>(); - List events = new ArrayList<>(); - - - ECSyncHelper syncHelper = ChwApplication.getInstance().getEcSyncHelper(); - JSONObject clientObject = syncHelper.getClient(familyMember.getFamilyID()); - Client familyClient = syncHelper.convert(clientObject, Client.class); - if (familyClient == null) { - String birthDate = clientObject.getString("birthdate"); - if (StringUtils.isNotBlank(birthDate)) { - birthDate = birthDate.replace("-00:44:30", getTimeZone()); - clientObject.put("birthdate", birthDate); - } - - familyClient = syncHelper.convert(clientObject, Client.class); - } - - Map> relationships = familyClient.getRelationships(); - - if (familyMember.getPrimaryCareGiver()) { - relationships.put(org.smartregister.chw.util.Constants.RELATIONSHIP.PRIMARY_CAREGIVER, toStringList(familyMember.getMemberID())); - familyClient.setRelationships(relationships); - } - - if (familyMember.getFamilyHead()) { - relationships.put(org.smartregister.chw.util.Constants.RELATIONSHIP.FAMILY_HEAD, toStringList(familyMember.getMemberID())); - familyClient.setRelationships(relationships); - } - - clients.add(familyClient); - - - JSONObject metadata = FormUtils.getInstance(context) - .getFormJson(Utils.metadata().familyRegister.formName) - .getJSONObject(org.smartregister.family.util.JsonFormUtils.METADATA); - - metadata.put(org.smartregister.family.util.JsonFormUtils.ENCOUNTER_LOCATION, lastLocationId); - - FormTag formTag = new FormTag(); - formTag.providerId = Utils.context().allSharedPreferences().fetchRegisteredANM(); - formTag.appVersion = FamilyLibrary.getInstance().getApplicationVersion(); - formTag.databaseVersion = FamilyLibrary.getInstance().getDatabaseVersion(); - - Event eventFamily = JsonFormUtils.createEvent(new JSONArray(), metadata, formTag, familyMember.getFamilyID(), - org.smartregister.chw.util.Constants.EventType.UPDATE_FAMILY_RELATIONS, - Utils.metadata().familyRegister.tableName); - JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), eventFamily); - - - Event eventMember = JsonFormUtils.createEvent(new JSONArray(), metadata, formTag, familyMember.getMemberID(), org.smartregister.chw.util.Constants.EventType.UPDATE_FAMILY_MEMBER_RELATIONS, - Utils.metadata().familyMemberRegister.tableName); - JsonFormUtils.tagSyncMetadata(Utils.context().allSharedPreferences(), eventMember); - - eventMember.addObs(new Obs("concept", "text", org.smartregister.chw.util.Constants.FORM_CONSTANTS.CHANGE_CARE_GIVER.PHONE_NUMBER.CODE, "", - toList(familyMember.getPhone()), new ArrayList<>(), null, DBConstants.KEY.PHONE_NUMBER)); - - eventMember.addObs(new Obs("concept", "text", org.smartregister.chw.util.Constants.FORM_CONSTANTS.CHANGE_CARE_GIVER.OTHER_PHONE_NUMBER.CODE, org.smartregister.chw.util.Constants.FORM_CONSTANTS.CHANGE_CARE_GIVER.OTHER_PHONE_NUMBER.PARENT_CODE, - toList(familyMember.getOtherPhone()), new ArrayList<>(), null, DBConstants.KEY.OTHER_PHONE_NUMBER)); - - eventMember.addObs(new Obs("concept", "text", org.smartregister.chw.util.Constants.FORM_CONSTANTS.CHANGE_CARE_GIVER.HIGHEST_EDU_LEVEL.CODE, "", - toList(getEducationLevels(context).get(familyMember.getEduLevel())), toList(familyMember.getEduLevel()), null, DBConstants.KEY.HIGHEST_EDU_LEVEL)); - - - events.add(eventFamily); - events.add(eventMember); - - return Pair.create(clients, events); - } - - public static String getTimeZone() { - Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), - Locale.getDefault()); - Date currentLocalTime = calendar.getTime(); - DateFormat date = new SimpleDateFormat("Z"); - String localTime = date.format(currentLocalTime); - return localTime.substring(0, 3) + ":" + localTime.substring(3, 5); - } - /** * Returns a value from json form field *