Groovy web console

subscribe to the feed Subscribe
to this
site

Groovy TailorSfot test

Published 4 weeks ago by Frayba Otalora with tags Groovy Test
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper

//Save the information of products in a Map using the id as a key
static getProducts (products, map) {
    products?.each {
        map.put(it.id, [name: it.name, orderAmount: 0, price: new BigDecimal(it.price), total: 0.0])
    }
}

//calculate the total value of each product according to all the orders generated
static getItems (items, map) {
    items?.each {
        map[it.productId].total += (map[it.productId].price * it.quantity)
        map[it.productId].orderAmount += 1

    }
}


try {
    def url_Json = new URL("https://www.tailorsoft.co/sample.json")
    def map = [:]

    def response = new JsonSlurper().parseText(url_Json.text)

    getProducts(response?.products, map)

    getItems (response?.orders?.items?.flatten(), map)


    if (map) {
// Print the table header
        println "+--------------+---------+------------+";
        println "| Product      |  Orders |      Total |";
        println "+--------------+---------+------------+";
        map.each { key, val ->
            println val.name.padRight(15, ' ') + "|" + val.orderAmount.toString().padLeft(5, ' ') + "\t |" + val.total.toString().padLeft(11, ' ')
        }
    } else {
        println "Not information to display"
    }
}
catch (Exception e) {
    println("Something went wrong: ${e}")
}