Groovy web console

subscribe to the feed Subscribe
to this
site

Tailoring Coding Test

Published 1 month ago by Reinaldo Otálvaro with tags codeChallenge
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 jsonSlurper = new JsonSlurper()

def orders_map = [:]
def json_object = jsonSlurper.parseText(url_Json.getText())

//getting products and save them into a map with order details
for(product in json_object.products){
    Product prod = new Product(product.id, product.name, product.price as float)
    ProductSales ps = new ProductSales()
    ps.setProduct(prod)
    orders_map.put(product.id, ps)
}

//getting products and save them into a map with order details
for(order in json_object.orders){
    
    for(item in order.items){
        ProductSales ps = orders_map.get(item.productId)
        ps.setTotalAmount(ps.getTotalAmount() + item.quantity as float)
        orders_map.put(item.productId, ps)
    }
    
}

// Print the table header
println "+---------------+-------+--------+";
println "| Product       |Orders |Total   |";
println "+---------------+-------+--------+";


//get detailed values saved at map
for(entry in orders_map){
    ProductSales ps = entry.value
    println "| " + ps.getProduct().getName() +"\t|  " + ps.getTotalAmount() + "\t|" + ps.calculateTotalValue().trunc(2) +"\t |"
}

class Product{
    String id
    String name
    float price

    Product(id, name, price){
        this.id = id
        this.price = price
        this.name = name
    }
}

class ProductSales{
    Integer ordersNumber = 0
    float totalAmount = 0
    Product product

    float calculateTotalValue(){
        return totalAmount * this.product.getPrice()
    }

}