Groovy web console

subscribe to the feed Subscribe
to this
site

TailorSoft test

Published 1 month ago by Santiago Penilla with tags Developer test
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")
def objJson = new JsonSlurper().parseText(url_Json.text);
def itemfromOrders = objJson.orders.items.flatten(); 

def detailOfSales = objJson.products.collect { 
    products -> 
        def countSales = itemfromOrders.findAll{ it.productId == products.id}.sum{ it.quantity} ?:0
        def countOrders = itemfromOrders.findAll{ it.productId == products.id}.count{ it.productId} ?:0
    [ 
      name: products.name, 
      totalOrders: countOrders, 
      totalSales: new BigDecimal(products.price)*countSales 
    ]
}
// Print the table header
println "+--------------+----------+------------+";
println "| Product      |   Orders |      Total |";
println "+--------------+----------+------------+";
detailOfSales.each{
println "| ${it.name.padRight(13)}| ${it.totalOrders.toString().padLeft(8)} |${it.totalSales.toString().padLeft(11)} |"
}
println "+--------------+----------+------------+";