Groovy web console

subscribe to the feed Subscribe
to this
site

TailorSoft

Published 1 month ago by Abbas with tags Tailorsoft
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper;
import groovy.json.JsonSlurper.*;
import org.apache.groovy.json.internal.LazyMap;
 
def url_Json = new URL("https://www.tailorsoft.co/sample.json")

println "+--------------+---------+------------+";
println "| Product      |  Orders |      Total |";
println "+--------------+---------+------------+";

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

def parsedReciepts = new RecieptsJsonParser().parseJson(getJson);


interface JsonParser{
     Object parseJson(LazyMap jsonString);
}

class Reciept {
    String order;
    String product;
    Double total;
    public Reciept(String order, String product, Double total){
        this.order = order;
        this.product = product;
        this.total = total;
    }
}

class RecieptsJsonParser implements JsonParser{
    Object parseJson(LazyMap jsonString){
        List<Object> orders = jsonString.orders.items.flatten()
        jsonString.products.each { prod ->
            (orders.findAll { it.productId == prod.id }.sum { it.quantity } ?: 0).with { o ->
                println '| ' + prod.name.padRight(13) + '| ' + o.toString().center(8) + '|' +
                     (new BigDecimal(prod.price) * o).toString().padLeft(11) + ' |'
    }
    println "+--------------+---------+------------+"
}
    }
}