Groovy web console

subscribe to the feed Subscribe
to this
site

Test 1

Published 3 months ago by Andres Narvaez with tags Tailorsoft
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 parse_orders = new JsonSlurper().parse(url_Json) 

/**  
* Return total amount of units for a product from all orders.  
*  
* @param id_product The product's id to get all the units from all orders.  
* @param orders_array the orders taken from url_json by the "orders" key . 
* @return Double Total amount of units from all orders for a product .
*/
def Add_orders (id_product, orders_array){
    total_order_product = 0
    orders_array.items.each{
        it.each{
            if (it.productId == id_product) {total_order_product+=it.quantity}
        }
    }
    return(total_order_product)
}

/**  
* Prints each table row with product name, amount of units ordered, orders total price for each product
*  
* @param products_array The products id, name and price  
* @param orders_array The orders taken from url_json by the "orders" key .  
*/
def Display_totals (products_array,orders_array){
    products_array.each{

    total = (Double.parseDouble(it.price)*Add_orders(it.id, orders_array))

    String format = "%-20s%-10s%s%n"; 
    System.out.printf(format,it.name , Add_orders(it.id, orders_array),total.round(2))
    println "+--------------+---------+------------+";
    }
}


// Print the table header
println "+--------------+---------+------------+"
println "| Product      |  Orders |      Total |"
println "+--------------+---------+------------+"
//print the table body
Display_totals(parse_orders.products, parse_orders.orders)