Groovy web console

subscribe to the feed Subscribe
to this
site

Test Tailorsoft

Published 2 weeks ago by Daniel Rua
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 jsonSlurper = new JsonSlurper()
def connection = url_Json.openConnection();
def statusCode = connection.getResponseCode();
def mapProductNameById = [:]
def mapPriceById = [:]
def mapOrdersByProduct = [:]
def mapTotalByProduct = [:]

if (statusCode.equals(200)) {
    def data = connection.getInputStream().getText()
    def json = jsonSlurper.parseText(data)
    def products = (List) json.products
    def orders = (List) json.orders
    mapProductNameById = products.collectEntries { [it.id, it.name] }
    mapPriceById = products.collectEntries { [it.id, it.price] }
    mapOrdersByProduct = countOrdersByProduct(orders)
    mapTotalByProduct = countNumberOfProducts(orders)
    println mapProductNameById
    println mapPriceById
    println mapTotalByProduct
}

def countOrdersByProduct(List orders) {
    def map = [:]
    orders.each { order ->
        order.items.each { item ->
            if (map.containsKey(item.productId)) map[item.productId] = map[item.productId] + 1
            else map[item.productId] = 1
        }
    }
    return map
}

def countNumberOfProducts(List orders) {
    def map = [:]
    orders.each { order ->
        order.items.each { item ->
            if (map.containsKey(item.productId)) map[item.productId] = map[item.productId] + item.quantity
            else map[item.productId] = item.quantity
        }
    }
    return map
}

Double calculateValue(Integer quantity, Double price) {
    if (quantity == null || price == null) {
        return 0
    }
    return quantity * price
}

def formatProductName(String productName) {
    String.format("%s \t", productName)
}

def formatOrders(Map mapOrdersByProduct, String productId) {
    def numberOrders = mapOrdersByProduct.get(productId) == null ? 0 : mapOrdersByProduct.get(productId)
    String.format("%s \t", numberOrders)
}

def formatTotalSpent(String productId,  Map mapTotalByProduct, Map mapPriceById) {
    def value = calculateValue(mapTotalByProduct.get(productId), Double.parseDouble(mapPriceById.get(productId)))
    String.format("%.2f \t", value)
}

// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";
mapProductNameById.each { key, val ->
    printf("| %s | %s | %s |", formatProductName(val), formatOrders(mapOrdersByProduct, key), formatTotalSpent(key, mapTotalByProduct, mapPriceById))
    println()
}