## 05 Revenue per Territory.r

minDate <- "2015-01-01"
kCols.prod <- c("product_description", "product")
       stop("Rick, note to self\n\nAdd more product here ... and do you want to aggregate by it??\n\nAre you aggregating it correctly?\n\n(file:  05 Revenue per Territory.r)")
kCols.country <- c("region_group", "country_code", "country_name")
kCols <- c("month", "product_description", "product", "country_code")
colsToAgg <- c("total_tracks", "rightholders_tracks", "payable_usd")
productsUsing.forRevshare <- c("A", "P", "PD", "U")


DT.total_revshare <- aggregateDT(DT.revshare, by=kCols, colsToAgg=colsToAgg)
info.bak <- getInfo(DT.total_revshare)
DT.total_revshare <- DT.total_revshare[month >= minDate]

setInfo(DT.total_revshare, info = appendInfo(orig.info=info.bak, new.info=paste0("With month >= ", minDate)))
getInfo(DT.total_revshare)

DT.total_revshare[, product := as.character(product)]
DT.total_revshare[, product_description := as.character(product_description)]
DT.total_revshare[product %ni% c(productsUsing.forRevshare), c("product", "product_description") := list("ZZ", "All Other Products")]
DT.total_revshare[, ]

addCountryInfo_(DT.total_revshare, colsToBring=c("country_name", "region_group"))
DT.total_revshare[, region_group := as.character(region_group)]
DT.total_revshare[country_code == "US", region_group := "USA"]
DT.total_revshare[country_code == "CA", region_group := NA_character_]
DT.total_revshare[is.na(region_group), region_group := "z OTHER"]

DT.total_revshare[, 1, keyby=list(country_name, region_group)][, .N, by=region_group]

DT.super_total <- aggregateDT(DT.total_revshare, by=kCols.prod, colsToAgg=colsToAgg)
DT.super_total[, USD_per_stream := payable_usd / rightholders_tracks]

DT.super_total_by_ctry <- aggregateDT(DT.total_revshare, by=c(kCols.prod, "region_group"), colsToAgg=colsToAgg)
DT.super_total_by_ctry[, USD_per_stream := payable_usd / rightholders_tracks]

f.super_total <- out.p("Spotify Rev by Product Avg 2015", ext="csv")
f.super_total_by_ctry <- out.p("Spotify Rev by Product and Territory Avg 2015", ext="csv")

write.csv(x=DT.super_total, file=f.super_total, row.names=FALSE)
write.csv(x=DT.super_total_by_ctry, file=f.super_total_by_ctry, row.names=FALSE)

f.super_total
f.super_total_by_ctry
