Remove write to stdout
[ckanext-ga-report.git] / ckanext / ga_report / controller.py
blob:a/ckanext/ga_report/controller.py -> blob:b/ckanext/ga_report/controller.py
--- a/ckanext/ga_report/controller.py
+++ b/ckanext/ga_report/controller.py
@@ -21,7 +21,7 @@
     return '%s %s' % (calendar.month_name[d.tm_mon], d.tm_year)
 
 
-def _month_details(cls):
+def _month_details(cls, stat_key=None):
     '''
     Returns a list of all the periods for which we have data, unfortunately
     knows too much about the type of the cls being passed as GA_Url has a
@@ -32,9 +32,12 @@
     months = []
     day = None
 
-    vals = model.Session.query(cls.period_name,cls.period_complete_day)\
-        .filter(cls.period_name!='All').distinct(cls.period_name)\
-        .order_by("period_name desc").all()
+    q = model.Session.query(cls.period_name,cls.period_complete_day)\
+        .filter(cls.period_name!='All').distinct(cls.period_name)
+    if stat_key:
+        q=  q.filter(cls.stat_name==stat_key)
+
+    vals = q.order_by("period_name desc").all()
     if vals and vals[0][1]:
         day = int(vals[0][1])
         ordinal = 'th' if 11 <= day <= 13 \
@@ -203,7 +206,7 @@
 
         # Get the month details by fetching distinct values and determining the
         # month names from the values.
-        c.months, c.day = _month_details(GA_Stat)
+        c.months, c.day = _month_details(GA_Stat, "Downloads")
 
         # Work out which month to show, based on query params of the first item
         c.month_desc = 'all months'
@@ -216,12 +219,15 @@
         q = q.filter(GA_Stat.period_name==c.month) if c.month else q
         q = q.order_by("ga_stat.value::int desc")
 
+        data = collections.defaultdict(int)
         for entry in q.all():
             r = model.Session.query(model.Resource).filter(model.Resource.url==entry.key).first()
-            if r:
-                c.downloads.append((r,entry.value))
-            else:
-                log.info("Failed to find resource for %s" % entry.key)
+            if not r:
+                continue
+            data[r] += int(entry.value)
+
+        c.downloads = [(k,v,) for k,v in data.iteritems()]
+        c.downloads = sorted(c.downloads, key=operator.itemgetter(1), reverse=True)
 
         return render('ga_report/site/downloads.html')