Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ux): ✨ implement reports command (#2) #13

Closed
wants to merge 53 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
f7c301c
chore(assets): :bento: add view icon
JamesNZL May 14, 2023
e2f4286
feat(view): :construction: implement foundations of `tgl view` comman…
JamesNZL May 14, 2023
5d663a7
refactor(view): :recycle: refactor `CommandArgument` configuration class
JamesNZL May 15, 2023
742e59d
Merge branch 'main' into tgl-view
JamesNZL May 15, 2023
d8e2ca2
feat(view): :construction: implement report grouping selection
JamesNZL May 15, 2023
091f5be
feat(toggl): :sparkles: implement list project users reports api method
JamesNZL May 15, 2023
f801621
feat(view): :construction: use `Dictionary` for collection of `Comman…
JamesNZL May 15, 2023
8e4d33c
fix(toggl): :bug: `start_date` may not be null
JamesNZL May 15, 2023
4c78d72
feat(toggl): :bug: use reports api base url
JamesNZL May 15, 2023
cdfdf43
refactor(view): :recycle: rename durations -> spans
JamesNZL May 15, 2023
217f8f1
fix(view): :bug: set `CommandArgument` members to be `init` only
JamesNZL May 15, 2023
3c5b2f0
feat(view): :sparkles: finish rough implementation of `tgl view day p…
JamesNZL May 15, 2023
6bb5d8f
feat(view): :children_crossing: rank groupings as projects -> clients…
JamesNZL May 16, 2023
67f9d56
refactor: :art: remove hardcoded literal indices for command arguments
JamesNZL May 16, 2023
861e77d
perf: :zap: avoid reconstructing query string with `string.Join()` wh…
JamesNZL May 16, 2023
a99d16e
Merge branch 'main' into tgl-view
JamesNZL May 16, 2023
98f84f9
fix(view): :bug: fix incorrect time strings when longer than 1 day
JamesNZL May 16, 2023
48894da
Merge branch 'main' into tgl-view
JamesNZL May 16, 2023
db659d2
feat(view): :construction: use `POST` search time entries endpoint
JamesNZL May 16, 2023
59a0c5c
feat(view): :sparkles: extend implementation to `tgl view <span> clie…
JamesNZL May 16, 2023
eaea4a0
fix(view): :bug: fix year span start date calculation
JamesNZL May 16, 2023
b4ed9ce
Merge branch 'main' into tgl-view
JamesNZL May 16, 2023
6a701fa
feat(view): :sparkles: implement `tgl view <span> entries`
JamesNZL May 16, 2023
60af653
feat(view): :lipstick: use most tracked project colour for client icon
JamesNZL May 16, 2023
114e8bd
Merge branch 'main' into tgl-view
JamesNZL May 17, 2023
bf42eff
feat(view): :sparkles: include running timer in `tgl view` reports
JamesNZL May 17, 2023
b61a4ab
refactor(view): :pencil2: rename `timeEntries` to `summary`
JamesNZL May 17, 2023
07bf460
Merge branch 'main' into tgl-view
JamesNZL May 17, 2023
32a5e68
feat(view): :construction: cache summary time entries requests
JamesNZL May 17, 2023
5653f6d
fix(view): :bug: fix mutation of cached report data with currently ru…
JamesNZL May 17, 2023
8dee4b4
Merge branch 'main' into tgl-view
JamesNZL May 17, 2023
04d0b70
perf(view): :zap: do not re-create background fetches when searching …
JamesNZL May 17, 2023
a766df3
refactor: :mute: remove `cacheKey` log
JamesNZL May 17, 2023
86d47c4
feat(view): :children_crossing: implement searching for result title …
JamesNZL May 17, 2023
5eebf82
feat(view): :children_crossing: display selected project's time entries
JamesNZL May 17, 2023
3cfe32a
fix(view): :bug: display total time tracked for selected project
JamesNZL May 17, 2023
7a90598
feat(view): :children_crossing: time entries `Action` passes to `star…
JamesNZL May 17, 2023
6f4293e
feat(view): :children_crossing: set `AutoCompleteText` for totals result
JamesNZL May 17, 2023
8bd7bd9
feat(view): :children_crossing: display selected clients's projects
JamesNZL May 17, 2023
be8b068
feat(view): :lipstick: add subtitle to subtotal results with project/…
JamesNZL May 17, 2023
50148e5
fix(view): :bug: ensure total results have highest score if only one …
JamesNZL May 17, 2023
2d0a793
feat(view): :card_file_box: invalidate reports caches on command actions
JamesNZL May 18, 2023
7d2cc3f
perf: :zap: use semaphores to disallow new fetch while another is in …
JamesNZL May 18, 2023
0d09619
Merge branch 'main' into tgl-view
JamesNZL May 18, 2023
a8bd335
fix(view): :bug: fix autocomplete of `projects`/`clients` sub selection
JamesNZL May 18, 2023
e28ffca
refactor(reports): :truck: rename `view` -> `reports` (#2)
JamesNZL May 18, 2023
94f7723
style: :art: add parentheses around boolean expressions
JamesNZL May 18, 2023
5a3bb60
Merge branch 'main' into tgl-view
JamesNZL May 18, 2023
34df66f
refactor(reports): :rotating_light: remove `pragma` directive
JamesNZL May 18, 2023
ff8b231
Merge branch 'main' into tgl-view
JamesNZL May 18, 2023
934acee
fix(reports): :speech_balloon: fix incorrect time strings when 0 (#11)
JamesNZL May 18, 2023
b6e4a0d
feat(reports): :sparkles: implement viewing of past reports (#2)
JamesNZL May 18, 2023
0da4d1f
fix(reports): :bug: fix missed name kebaberisation
JamesNZL May 18, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assets/reports.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions assets/svg/reports.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 11 additions & 1 deletion src/Main.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Windows.Controls;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Flow.Launcher.Plugin.TogglTrack.ViewModels;
Expand All @@ -18,6 +19,14 @@ public class Main : IAsyncPlugin, ISettingProvider

internal TogglTrack? _togglTrack;

public static string ExtractFromQuery(Query query, int index)
{
return (index == 1)
// Expect slight performance improvement by using query.SecondToEndSearch directly
? query.SecondToEndSearch
: string.Join(" ", query.SearchTerms.Skip(index));
}

/// <summary>
/// Runs on plugin initialisation.
/// Expensive operations should be performed here.
Expand Down Expand Up @@ -72,13 +81,14 @@ public async Task<List<Result>> QueryAsync(Query query, CancellationToken token)
return await this._togglTrack.GetDefaultHotKeys();
}

return query.FirstSearch.ToLower() switch
return (query.FirstSearch.ToLower()) switch
{
Settings.StartCommand => await this._togglTrack.RequestStartEntry(token, query),
Settings.EditCommand => await this._togglTrack.RequestEditEntry(token, query),
Settings.StopCommand => await this._togglTrack.RequestStopEntry(token, query),
Settings.DeleteCommand => await this._togglTrack.RequestDeleteEntry(token),
Settings.ContinueCommand => await this._togglTrack.RequestContinueEntry(token, query),
Settings.ReportsCommand => await this._togglTrack.RequestViewReports(token, query),
_ => (await this._togglTrack.GetDefaultHotKeys())
.FindAll(result =>
{
Expand Down
187 changes: 187 additions & 0 deletions src/Settings.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace Flow.Launcher.Plugin.TogglTrack
{
/// <Summary>
Expand All @@ -10,15 +14,198 @@ public class Settings
internal const string StopCommand = "stop";
internal const string DeleteCommand = "delete";
internal const string ContinueCommand = "continue";
internal const string ReportsCommand = "reports";
internal const string BrowserCommand = "browser";
internal const string RefreshCommand = "refresh";

internal const string EditProjectFlag = "-p";
internal const string TimeSpanFlag = "-t";

internal enum ReportsSpanKeys
{
Day,
Week,
Month,
Year,
}
internal static readonly Regex ReportsSpanOffsetRegex = new Regex(@"-(\d+)");
internal static readonly List<ReportsSpanCommandArgument> ReportsSpanArguments = new List<ReportsSpanCommandArgument>
{
new ReportsSpanCommandArgument
{
Argument = "day",
Interpolation = offset =>
{
switch (offset)
{
case (0):
{
return "today";
}
case (1):
{
return "yesterday";
}
default:
{
return $"{offset} days ago";
}
}
},
Score = 400,
// Offsetted day
Start = (referenceDate, offset) => referenceDate.AddDays(-offset),
End = (referenceDate, offset) => referenceDate.AddDays(-offset),
},
new ReportsSpanCommandArgument
{
Argument = "week",
Interpolation = offset =>
{
switch (offset)
{
case (0):
{
return "this week";
}
case (1):
{
return "last week";
}
default:
{
return $"{offset} weeks ago";
}
}
},
Score = 300,
// Monday of the offsetted week
Start = (referenceDate, offset) => referenceDate.AddDays((-(int)referenceDate.DayOfWeek + 1) - (7 * offset)),
// Sunday of the offsetted week
End = (referenceDate, offset) => referenceDate.AddDays((-(int)referenceDate.DayOfWeek + 7) - (7 * offset)),
},
new ReportsSpanCommandArgument
{
Argument = "month",
Interpolation = offset =>
{
switch (offset)
{
case (0):
{
return "this month";
}
case (1):
{
return "last month";
}
default:
{
return $"{offset} months ago";
}
}
},
Score = 200,
// First day of the offsetted month
Start = (referenceDate, offset) => new DateTimeOffset(referenceDate.Year, referenceDate.Month, 1, 0, 0, 0, referenceDate.Offset).AddMonths(-offset),
// Last day of the offsetted month
End = (referenceDate, offset) => new DateTimeOffset(referenceDate.Year, referenceDate.Month, DateTime.DaysInMonth(referenceDate.Year, referenceDate.Month), 0, 0, 0, referenceDate.Offset).AddMonths(-offset),
},
new ReportsSpanCommandArgument
{
Argument = "year",
Interpolation = offset =>
{
switch (offset)
{
case (0):
{
return "this year";
}
case (1):
{
return "last year";
}
default:
{
return $"{offset} years ago";
}
}
},
Score = 100,
// First day of the offsetted year
Start = (referenceDate, offset) => new DateTimeOffset(referenceDate.Year - offset, 1, 1, 0, 0, 0, referenceDate.Offset),
// Last day of the offsetted year
End = (referenceDate, offset) => new DateTimeOffset(referenceDate.Year - offset, 1, 1, 0, 0, 0, referenceDate.Offset),
},
};

public enum ReportsGroupingKeys
{
Projects,
Clients,
Entries,
}
private const string ReportsGroupingProjectsArgument = "projects";
private const string ReportsGroupingClientsArgument = "clients";
private const string ReportsGroupingEntriesArgument = "entries";
internal static readonly List<ReportsGroupingCommandArgument> ReportsGroupingArguments = new List<ReportsGroupingCommandArgument>
{
new ReportsGroupingCommandArgument
{
Argument = Settings.ReportsGroupingProjectsArgument,
Interpolation = "View tracked time grouped by project",
Score = 300,
Grouping = Settings.ReportsGroupingKeys.Projects,
SubArgument = null,
},
new ReportsGroupingCommandArgument
{
Argument = Settings.ReportsGroupingClientsArgument,
Interpolation = "View tracked time grouped by client",
Score = 200,
Grouping = Settings.ReportsGroupingKeys.Clients,
SubArgument = Settings.ReportsGroupingProjectsArgument,
},
new ReportsGroupingCommandArgument
{
Argument = Settings.ReportsGroupingEntriesArgument,
Interpolation = "View tracked time entries",
Score = 100,
Grouping = Settings.ReportsGroupingKeys.Entries,
SubArgument = null,
},
};

/// <Summary>
/// Toggl Track API Token.
/// </Summary>
public string ApiToken { get; set; } = string.Empty;
}

public class CommandArgument
{
#nullable disable
public string Argument { get; init; }
public string Interpolation { get; init; }
public int Score { get; init; }
#nullable enable
}

public class ReportsSpanCommandArgument : CommandArgument
{
#nullable disable
public new Func<int, string> Interpolation { get; init; }
public Func<DateTimeOffset, int, DateTimeOffset> Start { get; init; }
public Func<DateTimeOffset, int, DateTimeOffset> End { get; init; }
#nullable enable
}

public class ReportsGroupingCommandArgument : CommandArgument
{
#nullable disable
public Settings.ReportsGroupingKeys Grouping { get; init; }
public string SubArgument { get; init; }
#nullable enable
}
}
74 changes: 53 additions & 21 deletions src/Toggl/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,26 @@ namespace Flow.Launcher.Plugin.TogglTrack.TogglApi
public class TogglClient
{
private readonly static string _baseUrl = "https://api.track.toggl.com/api/v9/";
private readonly static string _reportsUrl = "https://api.track.toggl.com/reports/api/v3/";
private readonly AuthenticatedFetch _api;
private readonly AuthenticatedFetch _reportsApi;

public TogglClient(string token)
{
this._api = new AuthenticatedFetch(token, TogglClient._baseUrl);
this._reportsApi = new AuthenticatedFetch(token, TogglClient._reportsUrl);
}

public void UpdateToken(string token)
{
this._api.UpdateToken(token);
this._reportsApi.UpdateToken(token);
}

/*
* Standard API
*/

public async Task<Me?> GetMe()
{
return await this._api.Get<Me>("me?with_related_data=true");
Expand All @@ -42,16 +50,16 @@ public void UpdateToken(string token)
: DateTimeOffset.UtcNow;

return await this._api.Post<TimeEntry>($"workspaces/{workspaceId}/time_entries", new
{
billable,
created_with = "flow-toggl-plugin",
description,
duration = -1 * dateTimeOffset.ToUnixTimeSeconds(),
project_id = projectId ?? default(long?),
start = dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ssZ"),
tags,
workspace_id = workspaceId,
});
{
billable,
created_with = "flow-toggl-plugin",
description,
duration = -1 * dateTimeOffset.ToUnixTimeSeconds(),
project_id = projectId ?? default(long?),
start = dateTimeOffset.ToString("yyyy-MM-ddTHH:mm:ssZ"),
tags,
workspace_id = workspaceId,
});
}

public async Task<TimeEntry?> EditTimeEntry(TimeEntry timeEntry, long? projectId, string? description, DateTimeOffset? start, DateTimeOffset? stop)
Expand All @@ -67,17 +75,17 @@ public void UpdateToken(string token)
}

return await this._api.Put<TimeEntry>($"workspaces/{timeEntry.workspace_id}/time_entries/{timeEntry.id}", new
{
timeEntry.billable,
created_with = "flow-toggl-plugin",
description,
duration,
project_id = projectId,
start = start?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
stop = stop?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
timeEntry.tags,
timeEntry.workspace_id,
});
{
timeEntry.billable,
created_with = "flow-toggl-plugin",
description,
duration,
project_id = projectId,
start = start?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
stop = stop?.ToString("yyyy-MM-ddTHH:mm:ssZ"),
timeEntry.tags,
timeEntry.workspace_id,
});
}

public async Task<TimeEntry?> GetRunningTimeEntry()
Expand Down Expand Up @@ -109,5 +117,29 @@ public void UpdateToken(string token)
{
return await this._api.Get<List<TimeEntry>>($"me/time_entries");
}

/*
* Reports API
*/

public async Task<SummaryTimeEntry?> GetSummaryTimeEntries(long workspaceId, long userId, Settings.ReportsGroupingKeys reportGrouping, DateTimeOffset start, DateTimeOffset? end)
{
(string grouping, string sub_grouping) = (reportGrouping) switch
{
Settings.ReportsGroupingKeys.Projects => ("projects", "time_entries"),
Settings.ReportsGroupingKeys.Clients => ("clients", "projects"),
Settings.ReportsGroupingKeys.Entries => ("projects", "time_entries"),
_ => ("projects", "time_entries"),
};

return await this._reportsApi.Post<SummaryTimeEntry>($"workspace/{workspaceId}/summary/time_entries", new
{
user_ids = new long[] { userId },
start_date = start.ToString("yyyy-MM-dd"),
end_date = end?.ToString("yyyy-MM-dd"),
grouping,
sub_grouping,
});
}
}
}
Loading