Skip to content

Commit

Permalink
Merge pull request #877 from opensrp/fix-locationpicker-bug
Browse files Browse the repository at this point in the history
Locationpicker - Use Default Location Name If Untranslated
  • Loading branch information
qiarie authored Sep 15, 2022
2 parents bb913d1 + 942f76c commit a9b06f4
Show file tree
Hide file tree
Showing 7 changed files with 188 additions and 62 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION_NAME=5.0.5-SNAPSHOT
VERSION_NAME=5.0.6-SNAPSHOT
VERSION_CODE=1
GROUP=org.smartregister
POM_SETTING_DESCRIPTION=OpenSRP Client Core Application
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package org.smartregister.cursoradapter;

import static android.os.Looper.getMainLooper;

import android.database.Cursor;
import android.os.Handler;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;

import org.smartregister.commonregistry.CommonPersonObject;
import org.smartregister.commonregistry.CommonPersonObjectClient;
Expand Down Expand Up @@ -42,7 +46,10 @@ public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, Cursor cursor) {
if (listItemProvider.isFooterViewHolder(viewHolder)) {
listItemProvider.getFooterView(viewHolder, getCurrentPageCount(), getTotalPageCount(), hasNextPage(), hasPreviousPage());
// make sure counts are updated before updating the view
(new Handler(getMainLooper())).post(() -> {
listItemProvider.getFooterView(viewHolder, getCurrentPageCount(), getTotalPageCount(), hasNextPage(), hasPreviousPage());
});
} else {
CommonPersonObject personinlist = commonRepository.readAllcommonforCursorAdapter(cursor);
CommonPersonObjectClient pClient = new CommonPersonObjectClient(personinlist.getCaseId(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

package org.smartregister.repository;

import static org.smartregister.AllConstants.ROWID;

import android.content.ContentValues;
import android.database.Cursor;
import android.text.TextUtils;
Expand Down Expand Up @@ -52,8 +54,6 @@

import timber.log.Timber;

import static org.smartregister.AllConstants.ROWID;

/**
* Created by keyman on 27/07/2017.
*/
Expand Down Expand Up @@ -354,12 +354,13 @@ public Boolean checkIfExistsByFormSubmissionId(Table table, String
return false;
}

private boolean populateStatement(SQLiteStatement statement, Table table, JSONObject
jsonObject, Map<String, Integer> columnOrder) {
private boolean populateStatement(SQLiteStatement statement, Table table, JSONObject jsonObject, Map<String, Integer> columnOrder) {
if (statement == null)
return false;

statement.clearBindings();
List columns;

try {
if (table.equals(clientTable)) {
columns = Arrays.asList(client_column.values());
Expand All @@ -373,10 +374,24 @@ private boolean populateStatement(SQLiteStatement statement, Table table, JSONOb

List<? extends Column> otherColumns = new ArrayList(columns);
if (!otherColumns.isEmpty()) {
otherColumns.removeAll(Arrays.asList(client_column.json, client_column.updatedAt, client_column.syncStatus, client_column.validationStatus, client_column.baseEntityId,
client_column.residence, client_column.locationId, client_column.clientType,
event_column.json, event_column.updatedAt, event_column.syncStatus, event_column.validationStatus, event_column.baseEntityId, event_column.eventId
, event_column.planId, event_column.taskId));
otherColumns.removeAll(Arrays.asList(
client_column.json,
client_column.updatedAt,
client_column.syncStatus,
client_column.validationStatus,
client_column.baseEntityId,
client_column.residence,
client_column.locationId,
client_column.clientType,
event_column.json,
event_column.updatedAt,
event_column.syncStatus,
event_column.validationStatus,
event_column.baseEntityId,
event_column.eventId,
event_column.planId,
event_column.taskId
));
}

for (Column column : otherColumns) {
Expand Down Expand Up @@ -2142,32 +2157,39 @@ public void markEventAsTaskUnprocessed(String formSubmissionId) {
}
}

public void markEventsAsSynced(Map<String, Object> syncedEventsClients) {
markEventsAsSynced(syncedEventsClients, null, null);
}

@SuppressWarnings("unchecked")
public void markEventsAsSynced(Map<String, Object> syncedEvents) {
public void markEventsAsSynced(Map<String, Object> syncedEventsClients, Set<String> failedEvents, Set<String> failedClients) {
try {
List<JSONObject> clients =
syncedEvents.containsKey(AllConstants.KEY.CLIENTS) ? (List<JSONObject>) syncedEvents.get(
AllConstants.KEY.CLIENTS) : null;
List<JSONObject> events =
syncedEvents.containsKey(AllConstants.KEY.EVENTS) ? (List<JSONObject>) syncedEvents.get(
AllConstants.KEY.EVENTS) : null;
List<JSONObject> clients = syncedEventsClients.containsKey(AllConstants.KEY.CLIENTS)
? (List<JSONObject>) syncedEventsClients.get(AllConstants.KEY.CLIENTS)
: null;

List<JSONObject> events = syncedEventsClients.containsKey(AllConstants.KEY.EVENTS)
? (List<JSONObject>) syncedEventsClients.get(AllConstants.KEY.EVENTS)
: null;

if (clients != null && !clients.isEmpty()) {
for (JSONObject client : clients) {
String baseEntityId = client.getString(client_column.baseEntityId.name());
markClientAsSynced(baseEntityId);
if (failedClients == null || !failedClients.contains(baseEntityId))
markClientAsSynced(baseEntityId);
}
}

if (events != null && !events.isEmpty()) {
for (JSONObject event : events) {
String formSubmissionId = event.getString(event_column.formSubmissionId.name());
markEventAsSynced(formSubmissionId);
if (failedEvents == null || !failedEvents.contains(formSubmissionId))
markEventAsSynced(formSubmissionId);
}
}
} catch (Exception e) {
Timber.e(e);
}

}

protected List<Client> fetchClients(String query, String[] params) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
package org.smartregister.sync.intent;

import static org.smartregister.AllConstants.COUNT;
import static org.smartregister.AllConstants.PerformanceMonitoring.ACTION;
import static org.smartregister.AllConstants.PerformanceMonitoring.CLIENT_PROCESSING;
import static org.smartregister.AllConstants.PerformanceMonitoring.EVENT_SYNC;
import static org.smartregister.AllConstants.PerformanceMonitoring.FETCH;
import static org.smartregister.AllConstants.PerformanceMonitoring.PUSH;
import static org.smartregister.AllConstants.PerformanceMonitoring.TEAM;
import static org.smartregister.util.PerformanceMonitoringUtils.addAttribute;
import static org.smartregister.util.PerformanceMonitoringUtils.clearTraceAttributes;
import static org.smartregister.util.PerformanceMonitoringUtils.initTrace;
import static org.smartregister.util.PerformanceMonitoringUtils.startTrace;
import static org.smartregister.util.PerformanceMonitoringUtils.stopTrace;

import android.content.Context;
import android.content.Intent;
import android.util.Pair;
Expand Down Expand Up @@ -37,29 +50,20 @@

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import timber.log.Timber;

import static org.smartregister.AllConstants.COUNT;
import static org.smartregister.AllConstants.PerformanceMonitoring.ACTION;
import static org.smartregister.AllConstants.PerformanceMonitoring.CLIENT_PROCESSING;
import static org.smartregister.AllConstants.PerformanceMonitoring.EVENT_SYNC;
import static org.smartregister.AllConstants.PerformanceMonitoring.FETCH;
import static org.smartregister.AllConstants.PerformanceMonitoring.PUSH;
import static org.smartregister.AllConstants.PerformanceMonitoring.TEAM;
import static org.smartregister.util.PerformanceMonitoringUtils.addAttribute;
import static org.smartregister.util.PerformanceMonitoringUtils.clearTraceAttributes;
import static org.smartregister.util.PerformanceMonitoringUtils.initTrace;
import static org.smartregister.util.PerformanceMonitoringUtils.startTrace;
import static org.smartregister.util.PerformanceMonitoringUtils.stopTrace;

public class SyncIntentService extends BaseSyncIntentService {
public static final String SYNC_URL = "/rest/event/sync";
protected static final int EVENT_PULL_LIMIT = 250;
protected static final int EVENT_PUSH_LIMIT = 50;
private static final String ADD_URL = "rest/event/add";
private static final String FAILED_CLIENTS = "failed_clients";
private static final String FAILED_EVENTS = "failed_events";
private Context context;
private HTTPAgent httpAgent;
private SyncUtils syncUtils;
Expand All @@ -72,7 +76,7 @@ public class SyncIntentService extends BaseSyncIntentService {
protected ValidateAssignmentHelper validateAssignmentHelper;
private long totalRecords;
private int fetchedRecords = 0;
private int totalRecordsCount = 0 ;
private int totalRecordsCount = 0;
//this variable using to track the sync request goes along with add events/clients
private boolean isEmptyToAdd = true;

Expand Down Expand Up @@ -307,35 +311,35 @@ private boolean pushECToServer(EventClientRepository db) {
int totalEventCount = db.getUnSyncedEventsCount();
int eventsUploadedCount = 0;


String baseUrl = CoreLibrary.getInstance().context().configuration().dristhiBaseURL();
if (baseUrl.endsWith(context.getString(R.string.url_separator))) {
baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf(context.getString(R.string.url_separator)));
}

for (int i = 0; i < syncUtils.getNumOfSyncAttempts(); i++) {
Map<String, Object> pendingEvents = db.getUnSyncedEvents(getEventBatchSize());
Map<String, Object> pendingEventsClients = db.getUnSyncedEvents(getEventBatchSize());

if (pendingEvents.isEmpty()) {
if (pendingEventsClients.isEmpty()) {
break;
}
// create request body
JSONObject request = new JSONObject();
try {
if (pendingEvents.containsKey(AllConstants.KEY.CLIENTS)) {
Object value = pendingEvents.get(AllConstants.KEY.CLIENTS);
if (pendingEventsClients.containsKey(AllConstants.KEY.CLIENTS)) {
Object value = pendingEventsClients.get(AllConstants.KEY.CLIENTS);
request.put(AllConstants.KEY.CLIENTS, value);

if (value instanceof List) {
eventsUploadedCount += ((List) value).size();
}
}
if (pendingEvents.containsKey(AllConstants.KEY.EVENTS)) {
request.put(AllConstants.KEY.EVENTS, pendingEvents.get(AllConstants.KEY.EVENTS));
if (pendingEventsClients.containsKey(AllConstants.KEY.EVENTS)) {
request.put(AllConstants.KEY.EVENTS, pendingEventsClients.get(AllConstants.KEY.EVENTS));
}
} catch (JSONException e) {
Timber.e(e);
}

isEmptyToAdd = false;
String jsonPayload = request.toString();
startEventTrace(PUSH, eventsUploadedCount);
Expand All @@ -344,24 +348,62 @@ private boolean pushECToServer(EventClientRepository db) {
baseUrl,
ADD_URL),
jsonPayload);

if (response.isFailure()) {
Timber.e("Events sync failed.");
isSuccessfulPushSync = false;
} else {
db.markEventsAsSynced(pendingEvents);
// do not mark items in list of failed events/clients as synced
Set<String> failedClients = null;
Set<String> failedEvents = null;

String responseData = response.payload();
if (StringUtils.isNotEmpty(responseData)) {
try {
JSONObject failedEventClients = new JSONObject(responseData);
failedClients = getFailed(FAILED_CLIENTS, failedEventClients);
failedEvents = getFailed(FAILED_EVENTS, failedEventClients);
} catch (JSONException e) {
Timber.e(e);
}
}

db.markEventsAsSynced(pendingEventsClients, failedEvents, failedClients);

Timber.i("Events synced successfully.");

stopTrace(eventSyncTrace);
updateProgress(eventsUploadedCount, totalEventCount);

if((totalEventCount - eventsUploadedCount) > 0)
if ((totalEventCount - eventsUploadedCount) > 0)
pushECToServer(db);

break;
}
}

return isSuccessfulPushSync;
}

private Set<String> getFailed(String recordType, JSONObject failedEventClients) {
Set<String> set = null;

try {
JSONArray failed = failedEventClients.getJSONArray(recordType);

if (failed.length() > 0) {
set = new HashSet<>();
for (int i = 0; i < failed.length(); i++) {
set.add(failed.getString(i));
}
}
} catch (JSONException e) {
Timber.e(e);
}

return set;
}

private void startEventTrace(String action, int count) {
SyncConfiguration configs = CoreLibrary.getInstance().getSyncConfiguration();
if (configs.firebasePerformanceMonitoringEnabled()) {
Expand Down Expand Up @@ -490,8 +532,7 @@ protected String getFormattedBaseUrl() {
return baseUrl;
}

protected Integer getEventBatchSize(){
protected Integer getEventBatchSize() {
return EVENT_PUSH_LIMIT;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -992,7 +992,7 @@ public static String getTranslatedLocation(String locationName) {
String key = getLocationKeyFromName(locationName);
String translatedLocationName = getTranslatedIdentifier(key);

return StringUtils.isNotEmpty(translatedLocationName) ? translatedLocationName : locationName;
return StringUtils.isNotEmpty(translatedLocationName) && !translatedLocationName.equals(key) ? translatedLocationName : locationName;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ public void init() {
Collections.sort(sortedLocations);
sortedLocations.add(0, defaultLocation);

List<String> translatedLocations = sortedLocations.stream().map(e -> {
return Utils.getTranslatedLocation(e);
}).collect(Collectors.toList());
List<String> translatedLocations = sortedLocations.stream().map(Utils::getTranslatedLocation).collect(Collectors.toList());

serviceLocationsAdapter = new ServiceLocationsAdapter(context, translatedLocations);
locationsLV.setAdapter(serviceLocationsAdapter);
Expand Down
Loading

0 comments on commit a9b06f4

Please sign in to comment.