Groovy web console

subscribe to the feed Subscribe
to this
site

ProductInformationTable

Published 2 weeks ago by Carlos José Cortés Rivera
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 jsonText = new JsonSlurper().parse(url_Json); // Get the JSON data to String
def products = jsonText.get("products"); //Get the products information
def orders = jsonText.get("orders"); //Get the orders information

class ProductLine{
    private    String id;
    private    String name;
    private    int quantity;
    private    float price;
    private    int orders;
    
    ProductLine(String id, String name, float price){
        this.id = id;
        this.name = name;
        this.quantity = 0; // Initially, the product quantity is zero
        this.price = price;
        this.orders = 0; // Initially, the product is not included in any order
    }
        
    public String getId(){
        return    this.id;
    }
    public void addOrder(){
        this.orders++;
    }
    public void addQuantity(int quantity){
        this.quantity += quantity;
    }
}

//Define an instance of ProductLine Class
List <ProductLine> data = new ArrayList<ProductLine>();

//Get the product information and save it in the table information
products.each {data.add(new ProductLine(it .id, it.name, Float.parseFloat(it.price)))};


//Process orders info in order to have the count of product and their prices in each order
orders.each{
    it.items.each{
        data.stream().forEach{pl -> 
                                if(pl.getId() == it.productId) {
                                    //If the product is present in the order, increment the quantity and include the product in the table information
                                    pl.addQuantity(it.quantity);
                                    pl.addOrder();
                                    } 
                             }
        };
};

// Print the table header
println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";
//Print the table content
data.each{
    println "| " + it.name + "        " + it.orders + "         " + (it.quantity * it.price).round(2);
println "+--------------+---------+------------+";
}