Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft Test

Published 1 month ago by Jefferson Alexander Diaz Pava
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");
 
// Print the table header
def parseJson = new JsonSlurper().parse(url_Json);

println "+---------------------+---------------------+----------------------+";
println "| "+printWithSpaces("Product")+"| "+printWithSpaces("Orders")+"|  "+printWithSpaces("Total")+"|";
println "+---------------------+---------------------+----------------------+";

for(prods in parseJson.products){
    def ord = parseJson.orders.items.find { it.value.productId == "p1"}
    def cantOrd = 0;
    def sumTotal = 0.0;
    def pds = parseJson.orders.items;
    for(pord in pds){
        def orderValid = (pord.find{it.productId==prods.id})
        if(orderValid  != null){
           cantOrd++;
           sumTotal += orderValid.quantity * Float.parseFloat(prods.price);
        }
    }
    def sumwithDecimals=String.format("%.2f", sumTotal);

    println "| "+printWithSpaces(prods.name)+"| "+printWithSpaces(cantOrd+"")+"| \$"+printWithSpaces(""+sumwithDecimals)+"|";
}


def printWithSpaces(def data){
    def whiteSpaces = "";
    def spaces = 20- data.length();
    for(i = 0; i <spaces; i++){
        whiteSpaces = whiteSpaces + " ";
    }
    return data+whiteSpaces ;
}