Groovy web console

subscribe to the feed Subscribe
to this
site

Test_Tailorsoft

Published 1 month ago by Santiago Caranton
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper 

//Source of data
def url_Json = new URL("https://www.tailorsoft.co/sample.json")

def obj = new JsonSlurper().parseText(url_Json.text)

//Converting json objects to java objects
ArrayList<Product> products = loadProducts(obj.products);
ArrayList<Order> orders = loadOrders(obj.orders);
//Creating table with the objects loaded
table = calculateSalesTable(products, orders);
//Printing table
printSalesTable(table);

//This method prints the table with format
public void printSalesTable(data){
    //Here we add words to the row, this helps to format
    ArrayList<String> words = new ArrayList<String>(["Products","Orders","Total"]);
    //Then we send them to the method who does the job
    //Note: if there are no words it means it's a "separator" row
    println(constructRow(null));
    println(constructRow(words));
    println(constructRow(null));
    //We do the same thing above but with the data from our table
    for(row in data){
        println(constructRow(null));
        words.clear()
        words.add(row.product);
        words.add(String.valueOf(row.orders));
        words.add(row.totalDollars);
        println(constructRow(words));
        println(constructRow(null));
    }
}

//This methods creates a formatted row depending if it has words
public String constructRow( ArrayList<String> words){
    //This numbers are the space between cell and cell
    int c2=15,c3=30,c4=40;
    String output=""
    //Here we construct a "separator" row
    if(words==null){
        output+="+";
        for(int i=1;i<c4;i++){
            if(i==c2||i==c3){
                output+="+";
            }
            else{
                output+="-";
            }
        }
        output+="+";
    }
    //If we have words, then we need to calculate the remaining space
    else{
        output+="|";
        output+=" "+words.get(0);
        int actualWord=1;
        for(int i=words.get(0).length()+2;i<c4;i++){
            if(i==c2||i==c3){
                output+="|";
                output+=" "+words.get(actualWord);
                i+=words.get(actualWord).length()+1;
                actualWord++;
                
            }
            else{
                output+=" ";
            }
        }
        output+="|";
    }  
    //At the end, we return a formatted row
    return output;
}

//This method takes all the products and orders to create a table with them
public calculateSalesTable(ArrayList<Product> products, ArrayList<Order> orders){
    total = [:];
    total['table'] = [];
    int totalOr;
    String totalDollars;
    HashMap<String, Integer> totalOrders = new HashMap<String,Integer>();
    HashMap<String, String> totalQuantity = new HashMap<String,String>();
    //First we go trough all orders to identify wich products have multiple quantities
    for(Order order: orders){
        for(Item item: order.getItems()){
            if(!totalOrders.containsKey(item.getProductId())){
                totalOrders.put(item.getProductId(),1)
                totalQuantity.put(item.getProductId(),item.getQuantity());
            }
            else{
                totalOrders.replace(item.getProductId(),totalOrders.get(item.getProductId())+1)
                totalQuantity.replace(item.getProductId(),totalQuantity.get(item.getProductId())+item.getQuantity());
            }
            
        }
    }
    //Then we calculate for each product its amount spent depending on the quantities calculated before
    for(Product product : products){
        //If the product dont exists in the map it means it has no quantities
        if(!totalOrders.containsKey(product.getId())){
            totalOr=0;
            totalDollars="\$0.00"
        }else{
            //If exists we multiply the price of the product with his quantity with a method
            totalOr = totalOrders.get(product.getId());
            totalDollars = String.format("\$%.2f",calculateTotalDollars(product,totalQuantity.get(product.getId())))
        }
        //We create a "row" with the ifo (product name, # of orders and total)
        total['table'].add(["product":product.getName(),"orders":totalOr,"totalDollars":totalDollars]);
    }
    //Finally we return a table with all the rows
    return total['table'];
}

public double calculateTotalDollars(Product product, Integer quantity){
    double price = Double.parseDouble(product.getPrice());
    return price*quantity;
}

//These three methods convert json objects to java objets
public ArrayList<Product> loadProducts(ArrayList products){
    ArrayList<Product> allProducts = new ArrayList<Product>();
    for(int i=0; i<products.size();i++){
        allProducts.add(new Product(products.get(i).id, products.get(i).name, products.get(i).price));
    }
    return allProducts; 
}

public ArrayList<Item> loadItems(ArrayList items){
    ArrayList<Item> allItems = new ArrayList<Item>();
    for(int i=0; i<items.size(); i++){
        allItems.add(new Item(items.get(i).productId, items.get(i).quantity));
    }
    return allItems;
}

public ArrayList<Order> loadOrders(ArrayList orders){
    ArrayList<Order> allOrders = new ArrayList<Order>();
    for(int i=0; i<orders.size();i++){
        allOrders.add(new Order(orders.get(i).id, loadItems(orders.get(i).items)));
    }
    return allOrders;
}

//These three classes represents the info from the json 
class Product{
    private String id;
    private String name;
    private String price;
    
    public Product(String id, String name, String price){
        this.id=id;
        this.name=name;
        this.price=price;
    }

    public String getId(){
        return this.id;
    }

    public String getName(){
        return this.name;
    }

    public String getPrice(){
        return this.price;
    }
    
   public String setId(String id){
        this.id = id;
    }
    
    public String setName(String name){
        this.name = name;
    }

    public void setPrice(String price){
        this.price=price;
    }
}

class Item{
    private String productId;
    private Integer quantity;
    
    public Item(String productId, Integer quantity){
        this.productId=productId;
        this.quantity=quantity
    }

    public String getProductId(){
        return this.productId;
    }

    public Integer getQuantity(){
        return this.quantity;
    }

    public setProductId(String productId){
        this.productId = productId;
    }

    public setQuantity(Integer quantity){
        this.quantity = quantity;
    }
}

class Order{
    private String id;
    private ArrayList<Item> items;
    
    public Order(String id, ArrayList<Item> items){
        this.id=id;
        this.items=items
    }

    public String getId(){
        return this.id;
    }

    public ArrayList<Item> getItems(){
        return this.items;
    }

    public void setId(String id){
        this.id = id;
    }

    public void setItems(ArrayList<Product> items){
        this.items = items;
    }
}