|
| 1 | +import os |
| 2 | +import pprint |
| 3 | +from datetime import datetime, timedelta |
| 4 | + |
| 5 | +from toggl.TogglPy import Toggl |
| 6 | + |
| 7 | +# init a pretty printer |
| 8 | +pp = pprint.PrettyPrinter(indent=4) |
| 9 | + |
| 10 | +# gather the api token from environment |
| 11 | +api_token = os.environ["TOGGL_API_TOKEN"] |
| 12 | + |
| 13 | +# form the toggl client |
| 14 | +toggl = Toggl() |
| 15 | +toggl.setAPIKey(api_token) |
| 16 | + |
| 17 | + |
| 18 | +def get_flattened_summary_data(toggl: Toggl, date: str) -> dict: |
| 19 | + """ |
| 20 | + Find and return data structure which includes flattened |
| 21 | + summary stats from toggl workday based on date str provided |
| 22 | + """ |
| 23 | + |
| 24 | + # gather a workspace for making report requests |
| 25 | + workspaces = toggl.getWorkspaces() |
| 26 | + default_workspace_id = workspaces[0]["id"] |
| 27 | + |
| 28 | + # specify that we want reports from this week |
| 29 | + req_data = { |
| 30 | + "workspace_id": default_workspace_id, |
| 31 | + "since": date, |
| 32 | + "until": date, |
| 33 | + } |
| 34 | + |
| 35 | + # gather the report data |
| 36 | + report_data = toggl.getSummaryReport(req_data) |
| 37 | + |
| 38 | + # filter the report data |
| 39 | + filtered_report_data = [ |
| 40 | + {"title": item["title"]["project"].split(" - ")[0], "time": item["time"]} |
| 41 | + for item in report_data["data"] |
| 42 | + ] |
| 43 | + |
| 44 | + # group time values together |
| 45 | + grouped = {} |
| 46 | + for item in filtered_report_data: |
| 47 | + if item["title"] not in grouped.keys(): |
| 48 | + grouped[item["title"]] = item["time"] |
| 49 | + else: |
| 50 | + grouped[item["title"]] += item["time"] |
| 51 | + |
| 52 | + # percentage of total time for grouped values |
| 53 | + return { |
| 54 | + key: round((val / (report_data["total_grand"])) * 100, 2) |
| 55 | + for key, val in grouped.items() |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +# gather the last 3 days of work as flattened report data |
| 60 | +for num in range(1, 4): |
| 61 | + date = (datetime.now() - timedelta(num)).strftime("%Y-%m-%d") |
| 62 | + print(date) |
| 63 | + pp.pprint(get_flattened_summary_data(toggl, date)) |
0 commit comments