Skip to content
Snippets Groups Projects
Select Git revision
  • b6e361bddf920be06e39ba8ba45899fa059bb83f
  • main default
2 results

stats.go

Blame
  • stats.go 2.15 KiB
    /**
     * stats.go
     *
     * COPYRIGHT: FUNDACIÓN TECNALIA RESEARCH & INNOVATION, 2022.
     */
    
    package model
    
    type PercentageMetric struct {
    	Total float64 `json:"total"` // in tons
    	Percentage float64 `json:"percentage,omitempty"` // in %
    }
    
    type PriceMetric struct {
    	Minimum float64 `json:"min"`
    	Maximum float64 `json:"max"`
    	Average float64 `json:"avg"`
    }
    
    // Total or per company
    // Refined stats which will be returned
    type Stats struct {
    	TotalSlag float64 `json:"total"` // in tons
    	Reused PercentageMetric `json:"reused"`
    	Discarded PercentageMetric `json:"discarded"`
    	Price PriceMetric `json:"price"`
    }
    
    // Total or per company
    // Raw stored stats
    type RawStats struct {
    	TotalSlag float64 `json:"total"` // in tons
    	SlagReused float64 `json:"reused"` // in tons
    	SlagDiscarded float64 `json:"discarded"` // in tons
    	TotalPrice float64 `json:"totalPrice"` // in €
    	BidAmount uint32 `json:"bidAmount"` // in units
    	MinPrice float64 `json:"minPrice"` // in €
    	MaxPrice float64 `json:"maxPrice"` // in €
    }
    
    func toTons(quantity uint32, units string) (float64) {
    	amount := float64(quantity)
    	if units == "kg" {
    		amount /= 1000.0
    	}
    	return amount
    }
    
    func (raw *RawStats) RegisterSlag(quantity uint32, units string) {
    	raw.TotalSlag += toTons(quantity, units)
    }
    
    func (raw *RawStats) UpgradeSell(quantity uint32, price float32, units string) {
    	raw.SlagReused += toTons(quantity, units)
    	raw.TotalPrice += float64(price)
    	raw.BidAmount += 1
    
    	convertedPrice := float64(price)
    	if convertedPrice < raw.MinPrice {
    		raw.MinPrice = convertedPrice
    	}
    
    	if raw.MaxPrice < convertedPrice {
    		raw.MaxPrice = convertedPrice
    	}
    } 
    
    func (raw *RawStats) RefineStats() (*Stats) {
    	ret := new(Stats)
    	ret.TotalSlag = raw.TotalSlag
    
    	ret.Reused.Total = raw.SlagReused
    	if ret.TotalSlag > 0 && ret.Reused.Total > 0 {
    		ret.Reused.Percentage = ret.Reused.Total / ret.TotalSlag
    	}
    
    	ret.Discarded.Total = raw.SlagDiscarded
    	if ret.TotalSlag > 0 && ret.Discarded.Total > 0 {
    		ret.Discarded.Percentage = ret.Discarded.Total / ret.TotalSlag
    	}
    
    	ret.Price.Minimum = raw.MinPrice
    	ret.Price.Maximum = raw.MaxPrice
    	if raw.BidAmount > 0 {
    		ret.Price.Average = raw.TotalPrice / float64(raw.BidAmount)
    	}
    
    	return ret
    }