Time tracking and reporting with Toggl

Home / Time tracking and reporting with Toggl

I use Toggl (https://toggl.com/) to track my daily time. It’s a nice system that is free with lots of reports and such. However, one report that I needed is not available. Fortunately, there is a nice API available to extract your data as needed.


The report that I needed was one that would give me weekly summaries of project time for a given calendar month. Toggl has monthly, daily, and weekly reports. The monthly report would group/sum all time for the month by project without a weekly break-down. The weekly report does not let you select partial weeks. So, you wind up, potentially, with weeks from multiple months in the report. The daily report shows all daily time without grouping.

After a quick review of their API, I decided to use their detail report output with some some simple LINQ grouping to generate my monthly reports with weekly summaries. To quickly prototype my report, I whipped up a simple LINQpad program to output a Bootstrap styled table.

The code is pretty simple, although there is a fair bit of cruft to make the Http calls and to perform some Log4Net setup. You only need to enter your API token from your Toggl account settings and then change the date indicating which month you’d like to report on. Within the code, I use LINQ groping and such to summarize the times by week. Toggl’s API returns durations as milliseconds, so time durations are easy to work with. I use the TimeSpan class to format the duration outputs.

void Main()
{
    var token = "YOURTOKENHERE:api_token"; // <---- put your token here. in the format "XXXXXXXXXXXXX:api_token"
	var date = new DateTime(2016,8,1); // <-- set your date here
	
    var startdate = date.ToString("yyyy-MM-dd");
	var enddate = date.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");

    var apiService = new ApiService();
    var detailUrl = "https://toggl.com/reports/api/v2/details";
    var workspaceUrl = "https://www.toggl.com/api/v8/workspaces";

    // Get the first workspace.
    dynamic workspaces = apiService.GetFromApi<dynamic>(workspaceUrl, null, token);
    var workspace = (string)workspaces[0].id;

    var dict = new Dictionary<string, string>() { { "since", startdate }, { "until", enddate }, { "workspace_id", workspace }, { "user_agent", "api_test" } };
    DetailReport report = apiService.GetFromApi<DetailReport>(detailUrl, dict, token);

    // Group by week, year
    var group = report.Data.GroupBy(x => new { Project = x.Project, Week = x.Week }).ToList();

	var output = group.Select(g => {
		var ts = TimeSpan.FromMilliseconds(g.Sum(p => p.Duration));
		var obj = new { Project = g.Key.Project, Week = g.Key.Week, Duration = string.Format("{0:000}:{1:00}:{2:00}",(int)ts.TotalHours, (int)ts.Minutes, (int)ts.Seconds) };
		return obj;
	})
	.OrderBy(x => x.Week)
	.ToList();
	
	var total = TimeSpan.FromMilliseconds(report.Data.Sum(p => p.Duration));
	output.Add(new {Project = "", Week = "", Duration = ""});
	output.Add(new { Project = "Summary", Week = "", Duration = string.Format("{0:000}:{1:00}:{2:00}",(int)total.TotalHours, (int)total.Minutes, (int)total.Seconds)});
	
	var table = @"<html><head><link rel=""stylesheet"" type=""text/css"" href=""https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css""/></head><body><div class=""container""><table class=""table""><thead class=""thead-default""><tr><th>Project</th><th>Week</th><th>Duration</th></tr></thead><tbody>";
	table += string.Join("", output
		.GroupBy(x => x.Week)
		.Select((g, i) => {
			var rowClass = i % 2 == 0 ? "bg-success" : "bg-info";
			var groupStr = string.Join("", g.Select(x => { var str =string.Format(@"<tr class=""{0}""><td>{1}</td><td>{2}</td><td>{3}</td></tr>", rowClass, x.Project, x.Week, x.Duration); return str; }).ToList());
			return groupStr;
		}));
	table += @"</tbody></table></div></body></html>";
	Util.RawHtml(table).Dump();
}

public class DetailReport
{
    [JsonProperty("total_grand")]
    public long TotalGrand { get; set; }

    [JsonProperty("total_billable")]
    public decimal? TotalBillable { get; set; }

    [JsonProperty("currency")]
    public string Currency { get; set; }

    [JsonProperty("amount")]
    public string Amount { get; set; }

    [JsonProperty("total_count")]
    public int TotalCount { get; set; }

    [JsonProperty("per_page")]
    public int PerPage { get; set; }

    [JsonProperty("data")]
    public List<DetailRow> Data { get; set; }
}
public class DetailRow
{
    private int _durationMilliseconds = 0;
    private TimeSpan _durationTimespan = TimeSpan.FromSeconds(0);
    private DateTime _start;
    private DateTime _end;
    private string _week;

    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("pid")]
    public string PID { get; set; }
    [JsonProperty("tid")]
    public string TID { get; set; }
    [JsonProperty("uid")]
    public string UID { get; set; }
    [JsonProperty("description")]
    public string Description { get; set; }
    [JsonProperty("start")]
    public DateTime Start
    {
        get { return _start; }
        set
        {
            _start = value;
            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            _week = string.Format("{0}-{1}", value.Year, ciCurr.Calendar.GetWeekOfYear(value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));
        }
    }
    [JsonProperty("end")]
    public DateTime End { get; set; }
    [JsonProperty("updated")]
    public DateTime? Updated { get; set; }

    [JsonProperty("dur")]
    public int Duration
    {
        get { return _durationMilliseconds; }
        set { _durationMilliseconds = value; _durationTimespan = TimeSpan.FromMilliseconds(value); }
    }

    public TimeSpan DurationSpan { get { return _durationTimespan; } }
    public string Week { get { return _week; } }

    [JsonProperty("user")]
    public string User { get; set; }

    [JsonProperty("use_stop")]
    public bool UseStop { get; set; }

    [JsonProperty("client")]
    public string Client { get; set; }

    [JsonProperty("project")]
    public string Project { get; set; }

    [JsonProperty("project_color")]
    public string ProjectColor { get; set; }

    [JsonProperty("project_hex_color")]
    public string ProjectHexColor { get; set; }

    [JsonProperty("task")]
    public string Task { get; set; }

    [JsonProperty("billable")]
    public string Billable { get; set; }

    [JsonProperty("is_billable")]
    public bool IsBillable { get; set; }

    [JsonProperty("cur")]
    public string Cur { get; set; }

    [JsonProperty("Tags")]
    public string[] Tags { get; set; }
}

public class ApiService
{
    public TimeSpan _timeout = TimeSpan.FromSeconds(20);
    private static string _jsonMediaType = "application/json";

    public T GetFromApi<T>(string url, Dictionary<string, string> kvp = null, string token = "")
    {
        // Token must be base64 encoded
        token = Convert.ToBase64String(Encoding.UTF8.GetBytes(token));

        var json = string.Empty;
        Stopwatch sw = new Stopwatch();
        sw.Start();

        var requestUri = kvp == null ?
            new Uri(url) :
            new Uri(string.Format("{0}?{1}",
                url,
                string.Join("&",
                    kvp.Keys
                    .Where(key => !string.IsNullOrWhiteSpace(kvp[key]))
                    .Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(kvp[key]))))
                )
            );

        var requestMessage = new HttpRequestMessage()
        {
            RequestUri = requestUri,
            Method = HttpMethod.Get
        };

        if (!string.IsNullOrWhiteSpace(token))
        {
            requestMessage.AttachBearerToken(token);
        }

        return SendRequest<T>(requestMessage);
    }

    private T SendRequest<T>(HttpRequestMessage requestMessage)
    {
        HttpResponseMessage response = null;
        var json = string.Empty;
        Stopwatch sw = new Stopwatch();
        sw.Start();

        try
        {
            using (var client = new HttpClient() { Timeout = _timeout })
            {
                // Assume we're dealing with JSON
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_jsonMediaType));

                response = client.SendAsync(requestMessage).Result;
                response.EnsureSuccessStatusCode();
                Task<Stream> streamTask = response.Content.ReadAsStreamAsync();
                Stream stream = streamTask.Result;
                var sr = new StreamReader(stream);
                json = sr.ReadToEnd();
                var retValue = Deserialize<T>(json);
                return retValue;
            }
        }
        catch (AggregateException ex)
        {
            if (ex.InnerException is TaskCanceledException)
            {
                throw ex.InnerException;
            }
            else
            {
                throw ex;
            }
        }
        catch (Exception ex)
        {
			throw ex;
        }
    }

    private T Deserialize<T>(string json)
    {
        T retValue;
        // Deserialize the token response
        var type = typeof(T);
        if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(string))
        {
            json = HttpUtility.UrlDecode(json);
            retValue = (T)Convert.ChangeType(json, typeof(T));
        }
        else
        {
            if (type == typeof(ExpandoObject))
            {
                var converter = new ExpandoObjectConverter();
                var obj = JsonConvert.DeserializeObject<T>(json, converter);
                return obj;
            }
            retValue = JsonConvert.DeserializeObject<T>(json);
        }

        return retValue;
    }
}

public static class RequestMessageExtensions
{
    public static HttpRequestMessage AttachBearerToken(this HttpRequestMessage requestMessage, string token)
    {
        requestMessage.Headers.Add("Authorization", string.Format("Basic {0}", token));
        return requestMessage;
    }
}

With the LINQPad working, I get a nice HTML table report:

Project Week Duration
Project1 2016-31 005:54:35
Project2 2016-31 039:46:34
Project2 2016-32 032:49:40
Project1 2016-32 012:27:56
Project2 2016-33 043:19:37
Project1 2016-33 021:25:09
Project2 2016-34 045:15:47
Project1 2016-34 010:24:28
Project2 2016-35 029:26:13
Project1 2016-35 009:30:00
Summary 250:19:59

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.