in src/api-server/src/main/java/com/google/abmedge/apiserver/ApiServerController.java [201:254]
public ResponseEntity<String> pay(@RequestBody PayRequest payRequest) {
BigDecimal totalCost = new BigDecimal(0);
String responseStr;
List<PurchaseItem> requestedItemList = payRequest.getItems();
List<PurchaseItem> purchaseItems = new ArrayList<>();
List<PaymentUnit> payUnits = new ArrayList<>();
if (requestedItemList.isEmpty()) {
return new ResponseEntity<>("", HttpStatus.OK);
}
Map<String, Long> itemIdsToCountMap =
requestedItemList.stream()
.collect(Collectors.toMap(pi -> pi.getItemId().toString(), PurchaseItem::getItemCount));
try {
Optional<List<Item>> optionalItemList = getItemDetails(itemIdsToCountMap);
if (optionalItemList.isEmpty()) {
return new ResponseEntity<>(
"Failed to fetch items details", HttpStatus.INTERNAL_SERVER_ERROR);
}
List<Item> itemList = optionalItemList.get();
int totalItemsRetrieved = itemList.size();
int totalItemsRequested = itemIdsToCountMap.size();
if (totalItemsRetrieved != totalItemsRequested) {
LOGGER.warn(
String.format(
"There is a mismatch between number of items requested and retrieved - %s/%s",
totalItemsRetrieved, totalItemsRequested));
}
for (Item item : itemList) {
UUID id = item.getId();
BigDecimal itemCount = new BigDecimal(itemIdsToCountMap.get(id.toString()));
BigDecimal totalItemCost = item.getPrice().multiply(itemCount);
totalCost = totalCost.add(totalItemCost);
PurchaseItem purchaseItem = new PurchaseItem(id, itemIdsToCountMap.get(id.toString()));
PaymentUnit paymentUnit = new PaymentUnit(id, item.getName(), itemCount, totalItemCost);
purchaseItems.add(purchaseItem);
payUnits.add(paymentUnit);
}
boolean updatedItemDetails = updateItemDetails(purchaseItems);
if (!updatedItemDetails) {
return new ResponseEntity<>(
"Failed to update purchased item information", HttpStatus.INTERNAL_SERVER_ERROR);
}
Optional<String> optionalBill =
makePayment(payRequest.getType(), payRequest.getPaidAmount(), totalCost, payUnits);
if (optionalBill.isEmpty()) {
return new ResponseEntity<>(
"Failed to process payment for the order", HttpStatus.INTERNAL_SERVER_ERROR);
}
responseStr = optionalBill.get();
} catch (IOException | InterruptedException e) {
return new ResponseEntity<>("FAILED", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(responseStr, HttpStatus.OK);
}