def test_headers(): t = Toggl("*****@*****.**", "secret", 99) assert t.headers == { "Authorization": "Basic c2VjcmV0OmFwaV90b2tlbg==", "Content-Type": "application/json", "Accept": "*/*", "User-Agent": "python/urllib", }
def test_default_state(): t = Toggl("*****@*****.**", "secret", 99) assert t.email == "*****@*****.**" assert t._api_key == "secret" assert t._verbose is False assert t.workspace == 99 assert t._current_page == 1 assert t._pages == 1 assert t._current_records_acquired == 0
def test_reset_pagination(): t = Toggl("*****@*****.**", "secret", 99) t._current_records_acquired = 33 t._current_page = 2 t._pages = 2 t._reset_instance_pagination() assert t._current_page == 1 assert t._pages == 1 assert t._current_records_acquired == 0
def __init__(self): self.config = Config() self.slackbot = SlackerAdapter() self.logger = Logger().get_logger() self.toggl = Toggl() self.toggl.setAPIKey(self.config.open_api['toggl']['TOKEN']) wid = self.toggl.getWorkspace( name=self.config.open_api['toggl']['WORKSPACE_NAME'])['id'] self.toggl.setWorkspaceId(wid) self.entity = TogglProjectEntity().entity
def __init__(self): # timeframe for report end_date = datetime.datetime.now() start_date = end_date - settings.timeframe # create report report_builder = Toggl(settings.api_token) workspaces = report_builder.get_workspaces() reports = [] for ws_name, ws_id in workspaces: if ws_name in settings.workspace2meta.keys(): metaproject = settings.workspace2meta[ws_name] for record in report_builder.detailed_report( ws_id, start_date, end_date): # record duration is in milliseconds # divide by 3600000 to convert to hours reports.append({ 'user': record['user'], 'team': ws_name, 'project': metaproject, 'subproject': record['project'], # example of record['start']: 2015-05-29T16:07:20+03:00 'start': record['start'][:19], 'duration': round(float(record['dur']) / 3600000, 2) }) self.df = pd.DataFrame(reports) self.df['start'] = pd.to_datetime(self.df['start']) self.total_weeks = set(self.df.set_index('start').index.week) self.first_timestamp = self.df.min(axis=1) self.projects = list( self.df.set_index('project').index.get_level_values(0).unique()) self.users = list( self.df.set_index('user').index.get_level_values(0).unique())
def test_repr(): t = Toggl("*****@*****.**", "secret", 99) assert ( str(t) == "Toggl([email protected], api_key=secret, workspace=99, verbose=False)" )
def test_raise_error_if_email_alone(): with pytest.raises(RuntimeError): Toggl(email="foo")
def test_params(): t = Toggl("*****@*****.**", "secret", 99) assert t.params == {"user_agent": "*****@*****.**", "workspace_id": 99}
def test_raise_error_if_api_key_alone(): with pytest.raises(RuntimeError): Toggl(api_key="bar")
def __init__(self, toggl_api_key=TOGGL_API_KEY, redmine_api_key=REDMINE_API_KEY): self.toggle_api = Toggl(toggl_api_key) self.redmine_api = Redmine(REDMINE_URL, key=redmine_api_key) self.issue_re = re.compile(r'#(?P<issue_id>\w+)')
""" Toggl Example. This example assumes you have a `config.yml` file. Usage: `python example.py` """ from toggl import Toggl toggl = Toggl(verbose=True) toggl.report(start="2018-08-10") # detailed_report = toggl.detailed_report(start='2018-01-01', end='2018-01-15') # simple_report = toggl.report(start='2018-01-01', end='2018-01-15') # intacct_format = toggl.intacct_report(start='2018-01-01', end='2018-01-15') # # print('\n\ndetailed_report\n') # print(detailed_report) # # print('\n\nsimple_report\n') # print(simple_report) # # print('\n\nintacct_format\n') # print(intacct_format)
def main(): args = parse_args() toggl = Toggl(settings.TOGGL_TOKEN) startDate = (datetime.now(timezone.utc) - timedelta(days=90)).isoformat() endDate = datetime.now(timezone.utc).isoformat() timeEntries = toggl.getTimeEntries(startDate, endDate) entriesByWeekday = {str(k): {} for k in range(6)} for te in timeEntries: startDate = dateutil.parser.parse(te['start']) te['startDate'] = startDate weekDay = str(startDate.weekday()) key = ("%s!%s!%s!%s" % (te['description'], startDate.hour, startDate.minute, te['duration'])) if weekDay not in entriesByWeekday: entriesByWeekday[weekDay] = {} if key not in entriesByWeekday[weekDay]: entriesByWeekday[weekDay][key] = { 'wid': te['wid'], 'pid': te.get('pid', None), 'description': te['description'], 'start': time(te['startDate'].hour, te['startDate'].minute, tzinfo=timezone.utc), 'duration': te['duration'], 'tags': te.get('tags', []), 'count': 0 } entriesByWeekday[weekDay][key]['count'] += 1 for day, entries in entriesByWeekday.items(): entriesByWeekday[day] = { k: entries[k] for k in entries if entries[k]['count'] > 1 } weekday = str(args.date.weekday()) entries = sorted(entriesByWeekday[weekday].values(), key=lambda entry: entry['start']) for te in entries: startDate = datetime.combine(args.date, te['start']) endDate = startDate + timedelta(seconds=te['duration']) prompt = "Add {} from {} to {} (duration {} sec)?".format( te['description'], startDate, endDate, te['duration']) newTe = copy.deepcopy(te) newTe['start'] = startDate if query_yes_no(prompt, "no"): res = toggl.createTimeEntry(newTe) if 'data' in res and 'id' in res['data'] and res['data']['id'] > 0: eprint("OK!") else: eprint("WARNING: Check output - " + str(res))
if args.date is None: logging.debug("No date specified, using system date: %s", today.strftime(date_format)) else: try: today = datetime.datetime.strptime(args.date, date_format) except ValueError: parser.exit(1, "Invalid date\n") if today < start_date: parser.exit( 1, "Start date ({0}) has not yet come.\n Check dates in" "the settings.py\n".format(start_date)) # create report toggl = Toggl(settings.api_token) workspaces = [(w['name'], w['id']) for w in toggl.get_workspaces()] weeks = week_list(start_date, today) report_writer = csv.DictWriter( args.output, ['user', 'team', 'project', 'start', 'duration']) report_writer.writeheader() for (monday, sunday) in weeks: if sunday > today: break for ws_name, ws_id in workspaces: inactive_users = set() if args.all else \ set(u['name'] for u in
except ValueError: parser.exit(1, "Invalid date\n") start_date = datetime.datetime.strptime(settings.start_date, settings.date_format) end_date = datetime.datetime.strptime(settings.end_date, settings.date_format) if today < start_date or today > end_date: parser.exit( 1, "Date {0} is out of the {1}..{2} range.\n Check dates in" " settings.py\n".format(today.strftime(settings.date_format), settings.start_date, settings.end_date)) # create report report_builder = Toggl(settings.api_token) workspaces = report_builder.get_workspaces() weeks = week_list(start_date, end_date) last_records = {} # last_records[user] = last_record report_writer = csv.DictWriter( sys.stdout, ['user', 'team', 'project', 'start', 'duration']) report_writer.writeheader() for (monday, sunday) in weeks: if sunday > today: break for ws_name, ws_id in workspaces:
def __init__(self): Application.__init__(self) self.log = logging.getLogger("TogglApp") self.toggl = Toggl()