Groovy web console

subscribe to the feed Subscribe
to this
site

reportOrders

Published 1 month ago by Juvenal Barrios
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
def url_Json = new URL("https://www.tailorsoft.co/sample.json")

class Report { String product = ""
               int cant
               double total }

ArrayList<Report> reports = new ArrayList<Report>(4);
 
// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";
 
 
def item = new JsonSlurper().parseText(url_Json.text);
def orders = item.orders.items.flatten();


reports = item.products.collect {
    products ->
        r = new Report()
        r.product = products.name

        def cant = orders.findAll { it.productId == products.id}.sum { it.quantity } ?:0
        r.cant = orders.findAll { it.productId == products.id}.count {it.productId} ?:0
        r.total = new BigDecimal(products.price) * cant
    [ name: r.product, orders: r.cant, total: r.total ]
}
 
reports.each{ 
    println "|${it.name.padRight(14)}| ${it.orders.toString().center(8)}|${it.total.toString().padLeft(11)} |"
    println "+--------------+---------+------------+"; 
}