use of io.snabble.sdk.utils.SimpleJsonCallback in project Android-SDK by snabble.
the class ReceiptsApi method get.
/**
* Fetch receipts from the backend, parsed as a list of {@link ReceiptInfo}
*/
public void get(final ReceiptUpdateCallback receiptUpdateCallback) {
final Snabble snabble = Snabble.getInstance();
String url = snabble.getReceiptsUrl();
if (url != null) {
Request request = new Request.Builder().get().url(url).build();
if (snabble.getProjects().size() == 0) {
receiptUpdateCallback.failure();
return;
}
OkHttpClient okHttpClient = snabble.getProjects().get(0).getOkHttpClient();
okHttpClient.newCall(request).enqueue(new SimpleJsonCallback<ApiReceipt>(ApiReceipt.class) {
@Override
public void success(ApiReceipt apiReceipt) {
List<Project> projects = snabble.getProjects();
HashMap<String, Project> projectsById = new HashMap<>();
for (Project project : projects) {
projectsById.put(project.getId(), project);
}
List<ReceiptInfo> result = new ArrayList<>();
for (ApiOrder apiOrder : apiReceipt.orders) {
ApiLink apiLink = apiOrder.links.get("receipt");
if (apiLink == null) {
continue;
}
Project project = projectsById.get(apiOrder.project);
if (project != null) {
PriceFormatter priceFormatter = project.getPriceFormatter();
try {
String url = apiLink.href;
if (url == null || url.equals("")) {
url = null;
}
ReceiptInfo receiptInfo = new ReceiptInfo(apiOrder.id, apiOrder.project, simpleDateFormat.parse(apiOrder.date).getTime(), url != null ? snabble.absoluteUrl(url) : null, apiOrder.shopName, priceFormatter.format(apiOrder.price));
result.add(receiptInfo);
} catch (ParseException e) {
Logger.e("Could not parse ReceiptInfo: " + e.getMessage());
}
}
}
Collections.sort(result, (o1, o2) -> {
Date date1 = new Date(o1.timestamp);
Date date2 = new Date(o2.timestamp);
return -date1.compareTo(date2);
});
receiptUpdateCallback.success(result.toArray(new ReceiptInfo[0]));
}
@Override
public void error(Throwable t) {
receiptUpdateCallback.failure();
}
});
} else {
receiptUpdateCallback.failure();
}
}
Aggregations