-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclockify.ts
More file actions
246 lines (219 loc) · 6.84 KB
/
Copy pathclockify.ts
File metadata and controls
246 lines (219 loc) · 6.84 KB
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
import { AxiosInstance } from 'axios';
import { HttpClient } from './lib/http-client.js';
import { logSessionStart } from './lib/db.js';
import { v4 as uuidv4 } from 'uuid';
import { notify, type NotifyCallback } from './lib/notifier.js';
import { getJiraTicket } from './lib/jira.js';
interface ClockifyProject {
id: string;
name: string;
}
export class Clockify {
private readonly httpClient: AxiosInstance;
constructor() {
this.httpClient = new HttpClient().getClient();
}
private sendNotification(subtitle: string, message: string, actions?: string[], callback?: NotifyCallback) {
notify({ subtitle, message, actions }, callback);
}
async getUser() {
try {
const response = await this.httpClient.get('/user');
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('[clockify] Could not connect to Clockify. Please check your API key.', error.message);
} else {
console.error('[clockify] An unknown error occurred.');
}
return null;
}
}
async getProjects(workspaceId: string): Promise<ClockifyProject[]> {
try {
let allProjects: ClockifyProject[] = [];
let page = 1;
const pageSize = 50;
let hasMore = true;
while (hasMore) {
const response = await this.httpClient.get(`/workspaces/${workspaceId}/projects`, {
params: {
page: page,
'page-size': pageSize,
archived: false,
},
});
if (response.data.length > 0) {
allProjects = allProjects.concat(response.data);
page++;
} else {
hasMore = false;
}
}
return allProjects;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching projects:', error.message);
} else {
console.error('Error fetching projects: An unknown error occurred.');
}
return [];
}
}
async getProjectById(workspaceId: string, projectId: string): Promise<ClockifyProject | null> {
try {
const response = await this.httpClient.get(`/workspaces/${workspaceId}/projects/${projectId}`);
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching project:', error.message);
} else {
console.error('Error fetching project: An unknown error occurred.');
}
return null;
}
}
async startTimer(
workspaceId: string,
projectId: string,
description = 'Working on a task...',
jiraTicket?: string,
billable = true,
) {
try {
const user = await this.getUser();
if (!user) {
return null;
}
let finalDescription = description;
if (jiraTicket) {
const ticket = await getJiraTicket(jiraTicket);
if (ticket) {
finalDescription = `${jiraTicket} ${ticket.fields.summary}`;
}
}
const startedAt = new Date().toISOString();
const response = await this.httpClient.post(`/workspaces/${workspaceId}/time-entries`, {
projectId: projectId,
description: finalDescription,
start: startedAt,
billable,
});
const sessionId = (response.data as { id?: string }).id ?? uuidv4();
// Log session to SQLite
logSessionStart(sessionId, projectId, finalDescription, startedAt, jiraTicket);
const project = await this.getProjectById(workspaceId, projectId);
this.sendNotification(
`Timer started for ${project ? project.name : 'a project'}`,
finalDescription,
['Stop'],
(err, response, metadata) => {
if (err) {
console.error(err);
return;
}
if (metadata.activationValue === 'Stop') {
this.stopTimer(workspaceId, user.id);
}
},
);
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error starting timer:', error.message);
} else {
console.error('Error starting timer: An unknown error occurred.');
}
return null;
}
}
async stopTimer(workspaceId: string, userId: string) {
try {
const response = await this.httpClient.patch(`/workspaces/${workspaceId}/user/${userId}/time-entries`, {
end: new Date().toISOString(),
});
this.sendNotification('Timer stopped', 'Your timer has been stopped.');
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error stopping timer:', error.message);
} else {
console.error('Error stopping timer: An unknown error occurred.');
}
return null;
}
}
async getActiveTimer(workspaceId: string, userId: string) {
try {
const response = await this.httpClient.get(
`/workspaces/${workspaceId}/user/${userId}/time-entries?in-progress=true`,
);
return response.data[0];
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching active timer:', error.message);
} else {
console.error('Error fetching active timer: An unknown error occurred.');
}
return null;
}
}
async getTimeEntries(
workspaceId: string,
userId: string,
start: string,
end: string,
): Promise<Array<{ description: string; timeInterval: { start: string; end: string } }>> {
try {
const response = await this.httpClient.get(`/workspaces/${workspaceId}/user/${userId}/time-entries`, {
params: { start, end, 'page-size': 200 },
});
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching time entries:', error.message);
}
return [];
}
}
async deleteTimeEntry(workspaceId: string, entryId: string): Promise<boolean> {
try {
await this.httpClient.delete(`/workspaces/${workspaceId}/time-entries/${entryId}`);
return true;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error deleting time entry:', error.message);
}
return false;
}
}
async logTime(
workspaceId: string,
projectId: string | null,
start: string,
end: string,
description: string,
billable = true,
) {
if (!projectId) {
return null;
}
try {
const response = await this.httpClient.post(`/workspaces/${workspaceId}/time-entries`, {
projectId: projectId,
start: start,
end: end,
description: description,
billable,
});
return response.data;
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error logging time:', error.message);
} else {
console.error('Error logging time: An unknown error occurred.');
}
return null;
}
}
}