#!/usr/bin/python

# A script to draw graphs showing the number of confirmed reports
# created each month, and those of which that have been fixed.  This
# script expects to find a file called 'problems.csv' in the current
# directory which should be generated by:
#
#       DIR=`pwd` rake data:create_problem_spreadsheet

import csv
import datetime
from collections import defaultdict

import itertools

status_types = ('confirmed', 'fixed')

counts = {}
for status_type in status_types:
    counts[status_type] = defaultdict(int)

today = datetime.date.today()
latest_month = earliest_month = (today.year, today.month)

maximum_count = -1

with open('problems.csv') as fp:
    reader = csv.DictReader(fp, delimiter=',', quotechar='"')
    for row in reader:
        d = datetime.datetime.strptime(row['Created'],
                                       '%H:%M %d %b %Y')
        ym = (d.year, d.month)
        earliest_month = min(earliest_month, ym)
        if row['Status'] == 'confirmed':
            counts['confirmed'][ym] += 1
        elif row['Status'] == 'fixed':
            counts['fixed'][ym] += 1
        maximum_count = max(maximum_count, counts['fixed'][ym], counts['confirmed'][ym])

def months_between(earlier, later):
    """A generator for iterating over months represented as (year, month) tuples"""
    year = earlier[0]
    month = earlier[1]
    while True:
        yield (year, month)
        if month == 12:
            year = year + 1
            month = 1
        else:
            month += 1
        if (year, month) > later:
            return

all_months = list(months_between(earliest_month, latest_month))
months = len(all_months)

# Make sure that there's at least a zero count for each month we're
# considering:
for d in counts.values():
    for ym in all_months:
        d[ym] += 0

with open('monthly-breakdown.csv', 'w') as fp:
    writer = csv.writer(fp)
    writer.writerow(['Month', 'Confirmed', 'Fixed'])
    for ym in all_months:
        writer.writerow(["%d-%02d" % (ym[0], ym[1]),
                         counts['confirmed'][ym],
                         counts['fixed'][ym]])

Add a simple script to generate monthly confirmed / fixed counts