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

AC-1045: Migrate formadmission package from MVP to MVVM architecture #967

Merged
merged 1 commit into from
Oct 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.openmrs.android_sdk.library.api.repository

import com.openmrs.android_sdk.library.dao.PatientDAO
import com.openmrs.android_sdk.library.dao.VisitDAO
import com.openmrs.android_sdk.library.databases.AppDatabaseHelper
import com.openmrs.android_sdk.library.models.Encounter
import com.openmrs.android_sdk.library.models.EncounterType
import com.openmrs.android_sdk.library.models.Encountercreate
import com.openmrs.android_sdk.library.models.ResultType
import com.openmrs.android_sdk.utilities.NetworkUtils
import com.openmrs.android_sdk.utilities.execute
import rx.Observable
import javax.inject.Inject
import javax.inject.Singleton
import java.util.concurrent.Callable

@Singleton
class EncounterRepository @Inject constructor() : BaseRepository() {

/**
* Saves an encounter to local database and to server when online.
*
* @param encounterCreate the Encountercreate object submit
* @return ResultType of operation result: full success, local success, or error.
*/
fun saveEncounter(encounterCreate: Encountercreate): Observable<ResultType> {
return AppDatabaseHelper.createObservableIO(Callable {
val patient = PatientDAO().findPatientByID(encounterCreate.patientId.toString())
val activeVisit = VisitDAO().getActiveVisitByPatientId(encounterCreate.patientId).execute()
if (patient == null || activeVisit == null || encounterCreate.synced) {
return@Callable ResultType.EncounterSubmissionError
}

encounterCreate.visit = activeVisit.uuid
val encId = encounterCreate.id
if (encId == null || getEncounterCreateFromDB(encId).execute() == null) {
encounterCreate.id = saveEncounterCreateToDB(encounterCreate).execute()
}

if (patient.isSynced && NetworkUtils.isOnline()) {
restApi.createEncounter(encounterCreate).execute().run {
if (isSuccessful) {
val encounter: Encounter = body()!!
encounter.encounterType = EncounterType(encounterCreate.formname)
for (i in encounterCreate.observations.indices) {
encounter.observations[i].displayValue = encounterCreate.observations[i].value
}

// Update the visit linked to this encounter
activeVisit.encounters += encounter
VisitDAO().saveOrUpdate(activeVisit, encounterCreate.patientId!!).execute()

updateEncounterCreate(encounterCreate.apply { synced = true }).execute()

return@Callable ResultType.EncounterSubmissionSuccess
} else {
throw Exception("syncEncounter error: ${message()}")
}
}
} else {
// Update patient locally
patient.addEncounters(encounterCreate.id)
PatientDAO().updatePatient(patient.id!!, patient)
// EncounterService will run to upload the encounter when online
return@Callable ResultType.EncounterSubmissionLocalSuccess
}
})
}

/**
* Gets EncounterCreate object from database by its ID
*
* @param id id of the EncounterCreate to be fetched
* @return EncounterCreate object found
*/
fun getEncounterCreateFromDB(id: Long): Observable<Encountercreate?> {
return AppDatabaseHelper.createObservableIO(Callable {
return@Callable db.encounterCreateRoomDAO().getCreatedEncountersByID(id)
})
}

/**
* Saves Encountercreate object to database to be used to create an encounter in the server later.
*
* @param encounterCreate the EncounterCreate to be saved
* @return the id of the entry saved to the database
*/
fun saveEncounterCreateToDB(encounterCreate: Encountercreate): Observable<Long> {
return AppDatabaseHelper.createObservableIO(Callable {
return@Callable db.encounterCreateRoomDAO().addEncounterCreated(encounterCreate)
})
}

/**
* Updates an existing encounterCreate object in the database.
*
* @param encounterCreate the EncounterCreate to be updated
* @return the number of updated rows in the database
*/
fun updateEncounterCreate(encounterCreate: Encountercreate): Observable<Unit> {
return AppDatabaseHelper.createObservableIO(Callable {
return@Callable db.encounterCreateRoomDAO().updateExistingEncounter(encounterCreate)
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ class FormRepository @Inject constructor() : BaseRepository() {
})
}

/**
* Fetches a resource form by the form's name.
*
* @param name the form name
* @return an observable form resource entity
*/
fun fetchFormResourceByName(name: String): Observable<FormResourceEntity> {
return AppDatabaseHelper.createObservableIO(Callable {
return@Callable db.formResourceDAO().getFormResourceByName(name)
})
}

/**
* Creates a form.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,29 @@

package com.openmrs.android_sdk.library.api.repository;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import static com.openmrs.android_sdk.library.databases.AppDatabaseHelper.createObservableIO;
import static com.openmrs.android_sdk.utilities.ApplicationConstants.API.FULL;
import static com.openmrs.android_sdk.utilities.ApplicationConstants.API.REST_ENDPOINT;
import static com.openmrs.android_sdk.utilities.ApplicationConstants.API.TAG_ADMISSION_LOCATION;

import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.HashSet;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;

import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;

import com.openmrs.android_sdk.R;
import com.openmrs.android_sdk.library.OpenMRSLogger;
import com.openmrs.android_sdk.library.OpenmrsAndroid;
import com.openmrs.android_sdk.library.api.RestApi;
import com.openmrs.android_sdk.library.api.workers.provider.AddProviderWorker;
import com.openmrs.android_sdk.library.api.workers.provider.DeleteProviderWorker;
Expand All @@ -34,30 +47,23 @@
import com.openmrs.android_sdk.library.models.Provider;
import com.openmrs.android_sdk.library.models.Resource;
import com.openmrs.android_sdk.library.models.Results;
import com.openmrs.android_sdk.utilities.ApplicationConstants;
import com.openmrs.android_sdk.utilities.NetworkUtils;
import com.openmrs.android_sdk.utilities.ToastUtil;

import org.jetbrains.annotations.NotNull;

import java.util.HashSet;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
* The type Provider repository.
*/
@Singleton
public class ProviderRepository extends BaseRepository {

ProviderRoomDAO providerRoomDao;

/**
* Instantiates a new Provider repository.
*/
@Inject
public ProviderRepository() {
providerRoomDao = db.providerRoomDAO();
}
Expand All @@ -84,70 +90,43 @@ public void setProviderRoomDao(ProviderRoomDAO providerRoomDao) {
/**
* Gets providers.
*
* @return the providers
* @return a list of providers
*/
public LiveData<List<Provider>> getProviders() {

MutableLiveData<List<Provider>> providerLiveData = new MutableLiveData<>();
if (NetworkUtils.isOnline()) {
restApi.getProviderList().enqueue(new Callback<Results<Provider>>() {
@Override
public void onResponse(@NotNull Call<Results<Provider>> call, @NotNull Response<Results<Provider>> response) {
if (response.isSuccessful()) {
if (!response.body().getResults().isEmpty()) {
List<Provider> serversList = response.body().getResults();

List<String> providerUuids = providerRoomDao.getCurrentUUIDs().blockingGet();
HashSet<String> checkUuids = new HashSet<>();

for (String element : providerUuids) {
if (element != null)
checkUuids.add(element);
}

providerUuids.clear();
providerUuids = null;

for (Provider provider : serversList) {
if (checkUuids.contains(provider.getUuid()) == false) {
providerRoomDao.addProvider(provider);
}

checkUuids.remove(provider.getUuid());
}

for (String uuid : checkUuids) {
providerRoomDao.deleteByUuid(uuid);
}

providerLiveData.setValue(providerRoomDao.getProviderList().blockingGet());
} else {
providerLiveData.setValue(providerRoomDao.getProviderList().blockingGet());
public Observable<List<Provider>> getProviders() {
return createObservableIO(() -> {
// If not online, fetch providers locally
if (!NetworkUtils.isOnline()) {
ToastUtil.notify(context.getString(R.string.offline_provider_fetch));
logger.e("offline providers fetched couldn't sync with the database device offline");
return providerRoomDao.getProviderList().blockingGet();
}
providerRoomDao.deleteAll();
// Otherwise (online), fetch remote providers
Response<Results<Provider>> response = restApi.getProviderList().execute();
if (response.isSuccessful()) {
List<Provider> serverList = response.body().getResults();
if (!serverList.isEmpty()) {
// Sync local DB with server's providers
List<String> providerUuids = providerRoomDao.getCurrentUUIDs().blockingGet();
HashSet<String> checkUuids = new HashSet<>(providerUuids);

for (Provider provider : serverList) {
if (!checkUuids.contains(provider.getUuid())) {
providerRoomDao.addProvider(provider);
}
} else {
logger.e("Reading providers failed. Response: " + response.errorBody());
ToastUtil.error(OpenmrsAndroid.getInstance().getString(R.string.unable_to_fetch_providers));
providerLiveData.setValue(providerRoomDao.getProviderList().blockingGet());
checkUuids.remove(provider.getUuid());
}
// Remove local providers that are not present in server now
for (String uuid : checkUuids) {
providerRoomDao.deleteByUuid(uuid);
}
}
} else {
logger.e("Error fetching providers from the server: " + response.errorBody().string());
}

@Override
public void onFailure(@NotNull Call<Results<Provider>> call, @NotNull Throwable t) {
logger.e("Reading providers failed.", t);
ToastUtil.error(OpenmrsAndroid.getInstance().getString(R.string.unable_to_fetch_providers));
providerLiveData.setValue(providerRoomDao.getProviderList().blockingGet());
}
});
} else {

// offline data synced
providerLiveData.setValue(providerRoomDao.getProviderList().blockingGet());

//offline notify
ToastUtil.notify(context.getString(R.string.offline_provider_fetch));
logger.e("offline providers fetched couldnt sync with the database device offline");
}
return providerLiveData;
return providerRoomDao.getProviderList().blockingGet();
});
}

/**
Expand Down Expand Up @@ -296,57 +275,28 @@ public void onFailure(@NotNull Call<ResponseBody> call, @NotNull Throwable t) {
* Gets location.
*
* @param url the url
* @return the location
* @return a list of location entities
*/
public LiveData<List<LocationEntity>> getLocation(String url) {
MutableLiveData<List<LocationEntity>> locations = new MutableLiveData<>();
if (NetworkUtils.hasNetwork()) {
String locationEndPoint = url + ApplicationConstants.API.REST_ENDPOINT + "location";
Call<Results<LocationEntity>> call =
restApi.getLocations(locationEndPoint, ApplicationConstants.API.TAG_ADMISSION_LOCATION, ApplicationConstants.API.FULL);
call.enqueue(new Callback<Results<LocationEntity>>() {
@Override
public void onResponse(Call<Results<LocationEntity>> call, Response<Results<LocationEntity>> response) {
if (response.isSuccessful()) {
locations.setValue(response.body().getResults());
} else {
locations.setValue(null);
}
}

@Override
public void onFailure(Call<Results<LocationEntity>> call, Throwable t) {
locations.setValue(null);
}
});
} else {
locations.setValue(null);
}
return locations;
public Observable<List<LocationEntity>> getLocations(String url) {
return createObservableIO(() -> {
String locationEndPoint = url + REST_ENDPOINT + "location";
Response<Results<LocationEntity>> response =
restApi.getLocations(locationEndPoint, TAG_ADMISSION_LOCATION, FULL).execute();
if (response.isSuccessful()) return response.body().getResults();
else throw new Exception("fetch provider location error: " + response.message());
});
}

/**
* Gets encounter roles.
*
* @return the encounter roles
* @return a list of resources of encounter roles
*/
public LiveData<List<Resource>> getEncounterRoles() {
MutableLiveData<List<Resource>> encounterRoles = new MutableLiveData<>();
restApi.getEncounterRoles().enqueue(new Callback<Results<Resource>>() {
@Override
public void onResponse(Call<Results<Resource>> call, Response<Results<Resource>> response) {
if (response.isSuccessful()) {
encounterRoles.setValue(response.body().getResults());
} else {
encounterRoles.setValue(null);
}
}

@Override
public void onFailure(Call<Results<Resource>> call, Throwable t) {
encounterRoles.setValue(null);
}
public Observable<List<Resource>> getEncounterRoles() {
return createObservableIO(() -> {
Response<Results<Resource>> response = restApi.getEncounterRoles().execute();
if (response.isSuccessful()) return response.body().getResults();
else throw new Exception("fetch encounter roles error: " + response.message());
});
return encounterRoles;
}
}
Loading