Groovy web console

subscribe to the feed Subscribe
to this
site

Billing Test Groovy

Published 1 month ago by Mateo Arroyave with tags Java Groovy Table
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")
//Getting data from Endpoint
def response = new JsonSlurper().parseText( url_Json.text )  
//Mapping products and orders in differents Lists
def products = response.products
def orders = response.orders
// Print the table header
println "+--------------+--------------+----------------+";
println "|   Products   |    Orders    |     Total      |";
println "+--------------+--------------+----------------+";
//Defining the cell width
def width= 14
//Reading each product and find the orders for it
products.each {product -> 
    def totalOrders = 0
    def totalSpent = 0
//Reading each order to find how many product were ordered 
    orders.each {order ->
        def items = order.items
        items.each {item ->
 //Comparing the item in the order with the product to calculate the totals and the times it was ordered
            if(item.productId.equals(product.id)) {
                totalOrders++
                totalSpent = totalSpent + (Double.valueOf(item.quantity) * Double.valueOf(product.price))
            }
        }
    }  
//printing the table without the products that wasn't ordered
    print "|"
    printf('%-'+width- product.name.length()+'s',product.name)
    print "|"+totalOrders
    printf('%'+width+'s',"|")
if(totalOrders != 0) {
    printf('%'+(width)- totalSpent.intValue().toString().length()+'s','$'+ totalSpent.intValue() +",")
    printf('%1.2s',(totalSpent.toString().substring(totalSpent.toString().indexOf('.')+1)+"0"))    
}else{
    printf('%'+(width+1)+'s','$'+ totalSpent.intValue() +",")
    printf('%1.2s',(totalSpent.toString().substring(totalSpent.toString().indexOf('.')+1)))  
}
print "|\n"
println "+--------------+--------------+----------------+";
}