Groovy web console

subscribe to the feed Subscribe
to this
site

Tailorsoft test

Published 4 months ago by Alejandro Salgado
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper  

//Class to represent the information related to a product
class ProductRecord{     
    def product     
    def quantity 

    ProductRecord(product){         
        quantity = 0         
        this.product = product
    }      

    void update_quantity(quantity){         
        this.quantity += quantity     
    }      
    
    float get_total(){
        quantity * Float.valueOf(product.price)
    }

    void print_as_table(){
        println String.format("| %12s | %7d | %10.2f |", product.name, quantity, get_total())        
    }
}

//Class to handle multiple product records
class ProductRecordList{     
    def product_records = []

    def add_product_record(product_record){
        product_records.push( product_record )
    }      

    def update_record_quantity(id, quantity){
        for( product_record in product_records ) if( product_record.product.id == id ) product_record.update_quantity( quantity )
    }      

    def print_as_table(){
        println "+--------------+---------+------------+";
        println "| Product      |  Orders |      Total |";
        println "+--------------+---------+------------+";
        for(product_record in product_records) product_record.print_as_table()
        println "+--------------+---------+------------+";
    } 
}    

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

//Collect table information
def prod_rec_list = new ProductRecordList()  
for( product in json_data.products) prod_rec_list.add_product_record( new ProductRecord(product) )
for( order in json_data.orders ) for( item in order.items ) prod_rec_list.update_record_quantity( item.productId, item.quantity )  

//Print table
prod_rec_list.print_as_table()