Groovy web console

subscribe to the feed Subscribe
to this
site

Alejandro Test

Published 2 months ago by Alejandro
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper 
class EntryList{
    def entries = []

    def add_entry(entry){
        entries.push( entry )
    }

    def get_entry(id){
        for( entry in entries ) if ( entry.product.id == id ) return entry
    }

    def print(){
        // Print the table header
        println "+--------------+---------+------------+";
        println "| Product      |  Orders |      Total |";
        println "+--------------+---------+------------+";
        
        for(entry in entries) 
            println "| " + entry.product.name + "     |  " + entry. num_orders + " |      " + (entry.num_orders* Float.valueOf(entry.product.price)) + " |";
    }
}

class Entry{
    def product
    def num_orders

    Entry(prod){
        num_orders = 0
        product = prod
    }

    void update_quantity(quantity){
        num_orders += quantity
    }

    String toString(){
        "$product.name $num_orders $num_orders*$product.price"
    }
}

def url_json = new URL("https://www.tailorsoft.co/sample.json")
def json_data = new JsonSlurper().parseText(url_json.text)

def entry_list = new EntryList()

for( product in json_data.products) entry_list.add_entry( new Entry(product) )

for( order in json_data.orders )
    for( item in order.items )
        entry_list.get_entry( item.productId ).update_quantity( item.quantity )

entry_list.print()