Skip to content

Commit

Permalink
AC-1048: Migrate addeditprovider package from MVP to MVVM architecture (
Browse files Browse the repository at this point in the history
  • Loading branch information
amrsalah3 authored Oct 26, 2022
1 parent 6d74d26 commit 971ce1c
Show file tree
Hide file tree
Showing 23 changed files with 607 additions and 679 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ Call<FormCreate> formCreate(@Path("uuid") String uuid,
* @return the call
*/
@POST("provider/{uuid}")
Call<Provider> UpdateProvider(@Path("uuid") String uuid,
Call<Provider> updateProvider(@Path("uuid") String uuid,
@Body Provider provider);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import com.openmrs.android_sdk.library.listeners.retrofitcallbacks.DefaultResponseCallback;
import com.openmrs.android_sdk.library.models.Provider;
import com.openmrs.android_sdk.library.models.Resource;
import com.openmrs.android_sdk.library.models.ResultType;
import com.openmrs.android_sdk.library.models.Results;
import com.openmrs.android_sdk.utilities.NetworkUtils;
import com.openmrs.android_sdk.utilities.ToastUtil;
Expand Down Expand Up @@ -129,97 +130,92 @@ public Observable<List<Provider>> getProviders() {
}

/**
* Add provider.
* Add new provider to the database.
*
* @param provider the provider
* @param callback the callback
* @param provider the provider to be added
* @return Observable ResultType of the operation being locally success, all success, or fail
*/
public void addProvider(Provider provider, DefaultResponseCallback callback) {

if (NetworkUtils.isOnline()) {
restApi.addProvider(provider).enqueue(new Callback<Provider>() {
@Override
public void onResponse(@NotNull Call<Provider> call, @NotNull Response<Provider> response) {
if (response.isSuccessful()) {
//offline adding provider
providerRoomDao.addProvider(response.body());

ToastUtil.success(context.getString(R.string.add_provider_success_msg));
logger.e("Adding Provider Successful " + response.raw());
callback.onResponse();
}
}

@Override
public void onFailure(@NotNull Call<Provider> call, @NotNull Throwable t) {
logger.e("Failed to add provider. Error: " + t.getMessage());
callback.onErrorResponse(context.getString(R.string.add_provider_failure_msg));
}
});
} else {

//offline addition operation
long providerId = providerRoomDao.addProvider(provider);

//delegate to the workManager
Data data = new Data.Builder().putLong("id", providerId).build();

callback.onResponse();

Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
workManager.enqueue(new OneTimeWorkRequest.Builder(AddProviderWorker.class).setConstraints(constraints).setInputData(data).build());
public Observable<ResultType> addProvider(Provider provider) {
return createObservableIO(() -> {
if (!NetworkUtils.isOnline()) {
// If not online, add provider locally.
long providerId = providerRoomDao.addProvider(provider);

// Delegate to the WorkManager.
Data data = new Data.Builder()
.putLong("id", providerId)
.build();
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
workManager.enqueue(new OneTimeWorkRequest.Builder(AddProviderWorker.class)
.setConstraints(constraints)
.setInputData(data)
.build()
);

logger.i("Provider will be synced to the server when device gets connected to network");
return ResultType.AddProviderLocalSuccess;
}

//toast about deferred provider creation
ToastUtil.notify(context.getString(R.string.offline_provider_add));
logger.e("provider will be synced to the server when device gets connected to network");
}
// Otherwise (online), add provider remotely.
Response<Provider> response = restApi.addProvider(provider).execute();
if (response.isSuccessful()) {
// Add provider to the database.
providerRoomDao.addProvider(response.body());
logger.i("Adding provider succeeded " + response.raw());
return ResultType.AddProviderSuccess;
} else {
logger.e("Failed to add provider. Error: " + response.message());
throw new Exception("Failed to add provider. Error: " + response.message());
}
});
}

/**
* Update provider.
* Update exiting provider in the database.
*
* @param provider the provider
* @param callback the callback
* @return Observable ResultType of the operation being locally success, all success, or fail
*/
public void updateProvider(Provider provider, DefaultResponseCallback callback) {

if (NetworkUtils.isOnline()) {
restApi.UpdateProvider(provider.getUuid(), provider).enqueue(new Callback<Provider>() {
@Override
public void onResponse(@NotNull Call<Provider> call, @NotNull Response<Provider> response) {
if (response.isSuccessful()) {

//offline update operation
providerRoomDao.updateProviderByUuid(response.body().getDisplay(), provider.getId(), response.body().getPerson(), response.body().getUuid(),
response.body().getIdentifier());

ToastUtil.success(context.getString(R.string.edit_provider_success_msg));
logger.e("Editing Provider Successful " + response.raw());
callback.onResponse();
}
}

@Override
public void onFailure(@NotNull Call<Provider> call, @NotNull Throwable t) {
logger.e("Failed to edit provider. Error: " + t.getMessage());
callback.onErrorResponse(context.getString(R.string.edit_provider_failure_msg));
}
});
} else {

//offline update operation
providerRoomDao.updateProviderByUuid(provider.getDisplay(), provider.getId(), provider.getPerson(), provider.getUuid(), provider.getIdentifier());
callback.onResponse();

//delegate to the WorkManager for this work
Data data = new Data.Builder().putString("uuid", provider.getUuid()).build();
Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
workManager.enqueue(new OneTimeWorkRequest.Builder(UpdateProviderWorker.class).setConstraints(constraints).setInputData(data).build());
public Observable<ResultType> updateProvider(Provider provider) {
return createObservableIO(() -> {
if (!NetworkUtils.isOnline()) {
// If not online, update provider locally.
providerRoomDao.updateProviderByUuid(provider.getDisplay(), provider.getId(),
provider.getPerson(), provider.getUuid(), provider.getIdentifier());

// Delegate to the WorkManager.
Data data = new Data.Builder()
.putString("uuid", provider.getUuid())
.build();
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
workManager.enqueue(new OneTimeWorkRequest.Builder(UpdateProviderWorker.class)
.setConstraints(constraints)
.setInputData(data)
.build()
);

logger.e("Updated provider will be synced to the server when device gets connected to network");
return ResultType.UpdateProviderLocalSuccess;
}

//toast about deferred provider updation
ToastUtil.success(context.getString(R.string.offline_provider_edit));
logger.e("updated provider will be synced to the server when device gets connected to network");
}
// Otherwise (online), update provider remotely.
Response<Provider> response = restApi.updateProvider(provider.getUuid(), provider).execute();
if (response.isSuccessful()) {
// Update provider in the database.
providerRoomDao.updateProviderByUuid(response.body().getDisplay(), provider.getId(),
response.body().getPerson(), response.body().getUuid(),
response.body().getIdentifier());
logger.e("Updating provider succeeded " + response.raw());
return ResultType.UpdateProviderSuccess;
} else {
logger.e("Failed to update provider. Error: " + response.message());
throw new Exception("Failed to update provider. Error: " + response.message());
}
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

package com.openmrs.android_sdk.library.api.workers.provider;

import java.io.IOException;

import retrofit2.Response;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
Expand All @@ -32,10 +35,6 @@
import com.openmrs.android_sdk.utilities.NetworkUtils;
import com.openmrs.android_sdk.utilities.ToastUtil;

import java.io.IOException;

import retrofit2.Response;

/**
* The type Update provider worker.
*/
Expand Down Expand Up @@ -81,7 +80,7 @@ public Result doWork() {
private boolean updateProvider(RestApi restApi, Provider provider) {
if (NetworkUtils.isOnline()) {
try {
Response<Provider> response = restApi.UpdateProvider(provider.getUuid(), provider).execute();
Response<Provider> response = restApi.updateProvider(provider.getUuid(), provider).execute();
if (response.isSuccessful()) {
providerRoomDao.updateProviderByUuid(response.body().getDisplay(), provider.getId(), response.body().getPerson(), response.body().getUuid(),
response.body().getIdentifier());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ enum class OperationType {
PatientVitalsFetching,
PatientDeleting,
LastViewedPatientsFetching,
ProviderRegistering,
ProviderUpdating
}

enum class ResultType {
Expand All @@ -34,5 +36,9 @@ enum class ResultType {
PatientUpdateError,
EncounterSubmissionSuccess,
EncounterSubmissionLocalSuccess,
EncounterSubmissionError
EncounterSubmissionError,
AddProviderSuccess,
AddProviderLocalSuccess,
UpdateProviderSuccess,
UpdateProviderLocalSuccess,
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,7 @@ object ApplicationConstants {
const val FORM_FIELDS_LIST_BUNDLE = "formFieldsListBundle"
const val PATIENT_QUERY_BUNDLE = "patientQuery"
const val PATIENTS_START_INDEX = "patientsStartIndex"
const val PROVIDER_ID_BUNDLE = "providerID"
const val EXISTING_PROVIDERS_BUNDLE = "existingProviders"
const val PROVIDER_BUNDLE = "providerID"
const val ALLERGY_UUID = "allergy_uuid"
const val PATIENT_UUID = "patient_uuid"
}
Expand Down
2 changes: 1 addition & 1 deletion openmrs-client/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@
android:parentActivityName=".activities.dashboard.DashboardActivity"
android:theme="@style/AppThemeOrig" />
<activity
android:name=".activities.providermanagerdashboard.addprovider.AddProviderActivity"
android:name=".activities.addeditprovider.AddEditProviderActivity"
android:label="@string/title_provider_info"
android:parentActivityName=".activities.providermanagerdashboard.ProviderManagerDashboardActivity"
android:theme="@style/AppThemeOrig"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.mobile.activities.addeditprovider

import android.os.Bundle
import com.openmrs.android_sdk.library.models.Provider
import com.openmrs.android_sdk.utilities.ApplicationConstants.BundleKeys.PROVIDER_BUNDLE
import dagger.hilt.android.AndroidEntryPoint
import org.openmrs.mobile.R
import org.openmrs.mobile.activities.ACBaseActivity

@AndroidEntryPoint
class AddEditProviderActivity : ACBaseActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_provider)

supportActionBar?.run {
elevation = 0f
setDisplayHomeAsUpEnabled(true)
setTitle(R.string.title_provider_info)
}

val providerToEdit: Provider? = intent.getSerializableExtra(PROVIDER_BUNDLE) as? Provider
// Create fragment
var addProviderFragment = supportFragmentManager.findFragmentById(R.id.activity_add_provider_content_frame) as AddEditProviderFragment?
if (addProviderFragment == null) {
addProviderFragment = AddEditProviderFragment.newInstance(providerToEdit)
}
if (!addProviderFragment.isActive) {
addFragmentToActivity(supportFragmentManager, addProviderFragment, R.id.activity_add_provider_content_frame)
}
}
}
Loading

0 comments on commit 971ce1c

Please sign in to comment.