Groovy web console

subscribe to the feed Subscribe
to this
site

Technical test

Published 1 month ago by John Edison Rincon Barrios
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper 
try { 
    def url_Json = new URL("https://www.tailorsoft.co/sample.json")
    def response = new JsonSlurper().parse(url_Json)

    def productsDataTable = loadDataTable(response)
    
    printDataTable(productsDataTable)

  
}catch(Exception e){
    println "Error getting data"
    println e
}

def Object loadDataTable(Object response){

    def products = response.products;
    def orders = response.orders.collectMany{order -> order.items.collect { item -> [ order: order.id ] + item }};
    
    def productsDataTable = response.products.collect{product ->
        def ordersByProduct = orders.findAll{order -> order.productId.equals(product.id)}
        def countProductOrders = ordersByProduct.size()
        def quantity = ordersByProduct.groupBy{order -> order.id}.collect{order -> order.value.sum{ order1 ->order1.quantity}}[0]
        
        def double total = 0
        if(quantity ){
            total = quantity.multiply(Float.parseFloat(product.price));
        } 
        return [productId: product.id, productName:product.name, countproductOrders:countProductOrders, total:total ]}

    return productsDataTable;
}

def printDataTable(Object productsDataTable){
  // Print the table header
    println "+--------------+---------+------------+";
    println "| Product      |  Orders |      Total |";
    println "+--------------+---------+------------+";

  // Print the table body
    productsDataTable.each{ product ->
        printf('|%14s|%9s|%12s|\n', product.productName, product.countproductOrders , product.total.round(8))
        println "+--------------+---------+------------+";
    }    
}