Groovy web console

subscribe to the feed Subscribe
to this

Andres's TailorSoft Test

Published 3 weeks ago by Andres Rojas with tags Tailorsoft groovy test
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
def urlJson = new URL("")

// Print the table header
println "+------------------+-------------+----------------+";
println "| Product          |  Orders     |          Total |";
println "+------------------+-------------+----------------+";

//Get and parse data from url
def urlInfo = new JsonSlurper().parseText(urlJson.text);

//Get the differents nodes
def productNode = urlInfo.products
def ordersNode = urlInfo.orders

//Get the property items of all orders, I assume that each order only has the product once
def ItemsPropOrders = ordersNode.collectMany({item -> item.items})

//Group by Product, each item property is one order, then the size of group is the Number of orders placed for that product
def GroupInfo = ItemsPropOrders.groupBy({item -> item.productId})

// I create a collection with the necessary data for each product according to the grouping
def DetailInfo = GroupInfo.collect({key, val -> [product: key, orders: val.size(), quantity: val.quantity.sum()] })

// Define variables to use in the loop
def SpecificInfo, calcTotal, TotalString

// Iterate the collection of products to take into account those that are not present in orders
for(def product : productNode){
    // Search Info the product on orders
    SpecificInfo = DetailInfo.find({row -> row.product ==})
    if(SpecificInfo != null){
        //If found info print the info and calculate the total
        calcTotal = new Double(SpecificInfo.quantity) * new Double(product.price)
        TotalString = "US\$" + calcTotal.round(2).toString()
        println "|" + + "|" + SpecificInfo.orders.toString().padRight(13) + "|" +
            TotalString.padLeft(16) + "|";
        println "+------------------+-------------+----------------+";
        //If not found info on orders print the info with 0
        println "|" + + "|0            |          US\$0.0|";
        println "+------------------+-------------+----------------+";