Groovy web console

subscribe to the feed Subscribe
to this
site

mini-shoping

Published 2 weeks ago by Cristian Danilo Ordoñez with tags 0.1
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
println "+--------------+---------+------------+"
println "| Product      |  Orders |      Total |"
println "+--------------+---------+------------+"

def response = new JsonSlurper().parseText(url_Json.text)
def productos = response.products
def ordenes = response.orders

def obtenerOrdenesPorProducto(productId, orders){
    def ordersByProduct = []
    orders.each{order ->
        def orderTrace =  order.items.find{it.productId == productId}
        if (orderTrace != null){
            ordersByProduct.add([orderId: order.id, quantity: orderTrace.quantity])
        }
    }
    return ordersByProduct
}

def obtenerResumenProducto(producto, orders){
    if (producto == null || orders == null) return [:]
    def summary = [name: producto.name]
    def ordersByProduct = obtenerOrdenesPorProducto(producto.id, orders)
    summary.orders = ordersByProduct.size()
    summary.ordersList = ordersByProduct.collect{entry -> entry.orderId}
    def quantity = ordersByProduct.sum { it.quantity }
    summary.totalSpent = quantity != null? quantity*producto.price.toBigDecimal() : 0
    return summary
}

def printSummary(resumen){
    println "| ${resumen.name}      |  ${resumen.orders} |      ${resumen.totalSpent} |"
    println "---------------------------------------"
}

productos.each{producto -> 
    printSummary(obtenerResumenProducto(producto, ordenes))
}