This repository has been archived by the owner on Jan 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Toggl.ts
executable file
·422 lines (379 loc) · 12.1 KB
/
Toggl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import * as qs from 'querystring';
import chalk from 'chalk';
import { format, isSameYear, lastDayOfYear } from 'date-fns';
import { flatten, get, isNil, reverse, sortBy, uniq } from 'lodash';
import fetch from 'node-fetch';
import ConfigFile from '../utils/ConfigFile';
import JsonFile from '../utils/JsonFile';
import { Config, ConfigWorkspace, GeneralWorkspace } from '../types/common';
import {
ClientResponse,
ProjectResponse,
TimeEntryResponse,
WorkspaceEntities,
WorkspaceResponse,
} from '../types/toggl';
enum ContextUrl {
Reports = 'https://toggl.com/reports/api/v2',
Toggl = 'https://www.toggl.com/api/v8',
}
interface WorkspaceDetails extends WorkspaceEntities {
workspaceName: string;
}
/**
* Performs required functions associated with Toggl.
* @class
*/
export default class Toggl {
private readonly config: Config;
private currentPage: number;
private workspaceIndex: number;
private yearIndex: number;
constructor(configFilePath: string) {
this.config = ConfigFile.loadEntriesFromFile(configFilePath);
this.currentPage = 1;
this.workspaceIndex = 0;
this.yearIndex = 0;
}
/**
* Performs `fetch` call to Toggl API with the appropriate headers, endpoint,
* and authorization.
* @param contextUrl Base URL to make requests to (Reports or Toggl).
* @param endpoint Endpoint for fetch call (prefixed with base URL).
*/
private async makeApiRequest(contextUrl: ContextUrl, endpoint: string) {
const authString = `${this.config.togglApiToken}:api_token`;
const encodedAuth = Buffer.from(authString).toString('base64');
const fullUrl = `${contextUrl}${endpoint}`;
const response = await fetch(fullUrl, {
headers: {
Authorization: `Basic ${encodedAuth}`,
'Content-Type': 'application/json',
},
});
return await response.json();
}
/**
* Pauses execution for the specified number of seconds.
* @param [seconds=1] Number of seconds to pause for.
*/
private pause(seconds: number = 1): Promise<void> {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, seconds * 1000);
});
}
private printError(message: string) {
console.log(chalk.red(message));
}
private printStatus(message: string) {
console.log(chalk.cyan(message));
}
/**
* Returns an object with date ranges that get passed to the fetch call. It
* should either return from the first day of the year for since and the
* last day of the year if the `activeYear` specified is a previous year,
* otherwise it sets `until` to the current date.
* @param activeYear Current year to fetch data for (this changes as more
* data is fetched).
*/
private getDateRangesForYear(activeYear: number) {
const now = new Date();
const firstDayOfYear = new Date(activeYear, 0, 1);
const untilDate = isSameYear(now, firstDayOfYear)
? now
: lastDayOfYear(firstDayOfYear);
return {
since: format(firstDayOfYear, 'YYYY-MM-DD'),
until: format(untilDate, 'YYYY-MM-DD'),
};
}
/**
* Fetches data from Toggl Reports API and returns details based on specified
* year and page number.
* @param workspace Workspace to fetch data for.
* @param activeYear Limiting year for report records.
* @param page Page for report records.
*/
private async getDetailedReportForWorkspace(
workspace: GeneralWorkspace,
activeYear: number,
page: number = 1,
) {
const queryString = qs.stringify({
workspace_id: workspace.id,
user_agent: this.config.email,
page,
...this.getDateRangesForYear(activeYear),
});
try {
return await this.makeApiRequest(
ContextUrl.Reports,
`/details?${queryString}`,
);
} catch ({ message }) {
this.printError(
`Error getting detailed report for workspace: ${message}`,
);
return {
total_grand: 0,
total_billable: 0,
total_count: 0,
per_page: 0,
total_currencies: [],
data: [],
};
}
}
/**
* Returns the page count for the specified year
* @param workspace Workspace to fetch data for.
* @param activeYear Limiting year for report records.
*/
private async extrapolatePagination(
workspace: GeneralWorkspace,
activeYear: number,
): Promise<number> {
const { per_page, total_count } = await this.getDetailedReportForWorkspace(
workspace,
activeYear,
);
if (per_page === 0 || total_count === 0) return 0;
return Math.ceil(total_count / per_page);
}
private async *getTimeEntriesForYearIterable(
workspace: GeneralWorkspace,
activeYear: number,
): AsyncIterableIterator<TimeEntryResponse[]> {
while (true as any) {
const timeEntries = await this.getDetailedReportForWorkspace(
workspace,
activeYear,
this.currentPage,
);
await this.pause();
this.currentPage += 1;
yield timeEntries.data as TimeEntryResponse[];
}
}
private printTimeEntriesStatus(workspaceName: string, activeYear: number) {
this.printStatus(
`Getting time entries for page ${this.currentPage} for ` +
`${workspaceName} for the year of ${activeYear}...`,
);
}
/**
* Returns an array of Toggl entries from the API that correspond with the
* specified year.
* @param workspace Workspace to fetch data for.
* @param activeYear Limiting year for report records.
*/
private async getWorkspaceTimeEntriesForYear(
workspace: GeneralWorkspace,
activeYear: number,
): Promise<TimeEntryResponse[]> {
const totalPageCount = await this.extrapolatePagination(
workspace,
activeYear,
);
const entriesForAllPages: any = [];
// Ensure the first page is printed:
this.printTimeEntriesStatus(workspace.name, activeYear);
for await (const timeEntriesForPage of this.getTimeEntriesForYearIterable(
workspace,
activeYear,
)) {
this.printTimeEntriesStatus(workspace.name, activeYear);
entriesForAllPages.push(timeEntriesForPage);
if (
timeEntriesForPage.length === 0 ||
this.currentPage === totalPageCount
) {
this.currentPage = 1;
break;
}
}
return flatten(entriesForAllPages) as TimeEntryResponse[];
}
private async *getTimeEntriesForWorkspaceIteratable(
workspace: ConfigWorkspace,
) {
while (true as any) {
const yearEntries = await this.getWorkspaceTimeEntriesForYear(
workspace,
workspace.years[this.yearIndex],
);
await this.pause();
yield yearEntries;
}
}
/**
* Returns all Toggl time entries for the specified workspace (for all years).
* @param workspace Workspace to fetch data for.
*/
private async getTimeEntriesForWorkspace(
workspace: ConfigWorkspace,
): Promise<TimeEntryResponse[]> {
const timeEntriesForYear: any = [];
for await (const yearEntries of this.getTimeEntriesForWorkspaceIteratable(
workspace,
)) {
timeEntriesForYear.push(yearEntries);
this.yearIndex += 1;
if (this.yearIndex === workspace.years.length) {
this.yearIndex = 0;
break;
}
}
const sortedEntries: any = sortBy(flatten(timeEntriesForYear), 'start');
return reverse(sortedEntries);
}
/**
* Fetches projects from the Toggl API for the specified workspace.
* @param workspace Workspace to fetch data for.
*/
private async getProjectsInWorkspace(
workspace: GeneralWorkspace,
): Promise<ProjectResponse[]> {
try {
return await this.makeApiRequest(
ContextUrl.Toggl,
`/workspaces/${workspace.id}/projects`,
);
} catch ({ message }) {
this.printError(`Error getting projects in workspace: ${message}`);
return [];
}
}
/**
* Fetches clients from the Toggl API for the specified workspace.
* @param workspace Workspace to fetch data for.
*/
private async getClientsInWorkspace(
workspace: GeneralWorkspace,
): Promise<ClientResponse[]> {
try {
return await this.makeApiRequest(
ContextUrl.Toggl,
`/workspaces/${workspace.id}/clients`,
);
} catch ({ message }) {
this.printError(`Error getting clients in workspace: ${message}`);
return [];
}
}
private extrapolateTags(
timeEntries: TimeEntryResponse[],
): { id: string; name: string }[] {
if (timeEntries.length === 0) return [];
const allTags: any = [];
timeEntries.forEach(({ tags }) => {
if (tags.length !== 0) allTags.push(tags);
});
const flattenedTags = flatten(allTags) as string[];
return uniq(flattenedTags).map(tagName => ({ id: tagName, name: tagName }));
}
/**
* Fetches time entries and projects from the specified Toggl workspace.
* @param workspace Workspace to fetch data for.
*/
private async getWorkspaceDetails(
workspace: ConfigWorkspace,
): Promise<WorkspaceDetails> {
this.printStatus(
`Fetching time entries and projects in workspace: ${workspace.name}...`,
);
const clients = await this.getClientsInWorkspace(workspace);
const projects = await this.getProjectsInWorkspace(workspace);
const timeEntries = await this.getTimeEntriesForWorkspace(workspace);
const tags = this.extrapolateTags(timeEntries);
return {
workspaceName: workspace.name,
clients,
projects,
timeEntries,
tags,
};
}
private async *getWorkspaceDetailsIteratable(workspaces: ConfigWorkspace[]) {
while (true as any) {
const details = await this.getWorkspaceDetails(
workspaces[this.workspaceIndex],
);
await this.pause();
yield details;
}
}
/**
* Fetches Toggl workspaces and returns array of records with ID, name, and
* associated contents from config file.
*/
private async getWorkspaces(): Promise<ConfigWorkspace[]> {
let results = [];
try {
results = await this.makeApiRequest(ContextUrl.Toggl, '/workspaces');
} catch ({ message }) {
this.printError(`Error getting workspaces: ${message}`);
}
if (results.length === 0) return [];
// Only return workspaces specified in config file:
return (results as any).reduce((acc, { id, name }: WorkspaceResponse) => {
const configWorkspace = this.config.workspaces.find(
workspace => get(workspace, 'name', '') === name,
) as GeneralWorkspace;
if (isNil(configWorkspace)) return acc;
return [
...acc,
{
...configWorkspace,
id,
name,
},
];
}, []);
}
private validateWorkspaces(workspaces: GeneralWorkspace[]) {
if (workspaces.length > 0) return true;
const message = [
'No workspaces matching your configuration file were found!',
'\n',
'Check your configuration file to ensure you specified workspaces and ',
`that the "name" is an ${chalk.underline('exact')} match to Toggl`,
'\n',
'Refer to the README.md file for additional details',
].join('');
this.printError(message);
return false;
}
/**
* Writes clients, projects, and time entries for all workspaces to the
* specified target path.
* @param targetPath Output path to write JSON file data.
*/
public async writeDataToJson(targetPath: string): Promise<void> {
this.printStatus('Fetching workspaces from Toggl...');
const workspaces = await this.getWorkspaces();
if (!this.validateWorkspaces(workspaces)) return;
const entitiesByWorkspace: any = [];
this.workspaceIndex = 0;
for await (const entitiesInWorkspace of this.getWorkspaceDetailsIteratable(
workspaces,
)) {
entitiesByWorkspace.push(entitiesInWorkspace);
this.workspaceIndex += 1;
if (this.workspaceIndex === workspaces.length) break;
}
const dataToWrite = entitiesByWorkspace.reduce(
(acc, { workspaceName, ...rest }: WorkspaceDetails) => ({
...acc,
[workspaceName]: rest,
}),
{},
);
this.printStatus('Writing Toggl data to JSON file...');
const jsonFile = new JsonFile(targetPath);
await jsonFile.write(dataToWrite);
console.log(chalk.green('Toggl processing complete'));
}
}