Groovy web console

subscribe to the feed Subscribe
to this
site

TailorSoftTest

Published 1 month ago by David Tolosa with tags groovy json
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import groovy.json.JsonGenerator
import java.util.stream.*

Main m = new Main()
m.processJson('https://www.tailorsoft.co/sample.json')


class Main{
    void processJson(String address){

        URL fileJson = address.toURL()

        String jsonText = fileJson.text
        def json = new JsonSlurper().parseText(jsonText )
        def products = json.products
        def orders = json.orders
        def map = products.stream().collect(Collectors.toMap({p->p['id']},{p->p}))

        Report report = new Report()

        for(def order : orders){
            def items = order.items
            for(def item:items){
                if(report.findProduct(item.productId)){
                    report.addOrder(item.productId,item.quantity)
                }else{
                    def product = map.get(item.productId)
                    Row row=Row.create(product.name,item.productId,Double.parseDouble(product.price),item.quantity)
                    report.addProduct(row)
                }
            }
        }
        def listaa = report.getReports()
        String spaces = "                ";
        println "+------------------+-------------+--------------+"
        println "|    Product       |    Orders   |    Total     |"
        println "+------------------+-------------+--------------+"
        listaa.each{
            k,v ->
            print "|    "+v.name+spaces.substring(0,14-v.name.size())
            print "|    "+v.quantity+spaces.substring(0,8)
            print "|    "+v.total+spaces.substring(0,7)
            println "|"
            println "+------------------+-------------+--------------+"
        }
    }
}

class Row{

    String name,id
    int quantity=0,total=0,value=0
    
    private Row(String name,String id,double value,int quantity){
        this.name=name
        this.id=id
        this.value=value
        addQuantity(quantity)
    }

    static Row create(String name,String id,double value,int quantity){
        return new Row(name,id,value,quantity)
    }

    void addQuantity(int v){
        quantity+=v;
        total+=(v*value)
    }
}

class Report{

    def list = [:]

    void addOrder(String id,int quantity){
        list.get(id).addQuantity(quantity)
    }
    boolean findProduct(String id){
        return list.containsKey(id)
    }
    void addProduct(Row row){
        list.put(row.id,row)
    }
    def getReports(){
        return list
    }
}