Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy Test - Product Orders

Published 3 weeks ago by Juan Torres with tags groovy test
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.text.DecimalFormat

import groovy.json.JsonSlurper

class OrderDetail {
    String productName
    double productPrice
    int orderNumbers
    double total
}

/**
 * Display all the products with the following columns:
 * 1. Name of the product.
 * 2. Number of orders placed for that product.
 * 3. Total dollars spent on that product across all orders.
 */

// Get the JSON from the URL
def url_Json = new URL("https://www.tailorsoft.co/sample.json")
// Parse the JSOn to a result structure
def result = new JsonSlurper().parse(url_Json)
// Print the Json content
// println result
	
// Map to consolidate the order detail by product.
def productsMap = [string:OrderDetail]

// Loop de products to have an Inventory and value by product
result.products.each{ value ->
	def orderDetail = new OrderDetail();
	orderDetail.productName = value.name
	orderDetail.productPrice = value.price as double // set as double to be summed
	productsMap.put(value.id, orderDetail)
}

// Loop the Orders to get the detail by product
result.orders.each{ order ->   
	order.items.each{item ->
  OrderDetail detail = productsMap.get(item.productId);
  detail.orderNumbers = detail.orderNumbers + item.quantity // Count the number of Orders
  detail.total = detail.total + (detail.productPrice*item.quantity) // Consolidate the total price
  //println """ ${detail.productName} ${detail.orderNumbers} ${detail.total} """ 
  productsMap[item.productId] = detail as OrderDetail;
	}
}
  
// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";

DecimalFormat df = new DecimalFormat("#.00");
for (Map.Entry<String, OrderDetail> entry : productsMap.entrySet()) {
	if (entry.getKey() == "string") {
  continue;
	}
	
	OrderDetail value = entry.getValue();
	
	printf("|%14s|", value.productName) 
	printf("%9s|", value.orderNumbers);
	printf("%12s|\n", df.format(value.total));	
}
println "+--------------+---------+------------+";