-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
210 lines (165 loc) · 5.62 KB
/
utils.js
File metadata and controls
210 lines (165 loc) · 5.62 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
const readline = require('node:readline');
const moment = require('moment')
const BASE_URL = 'https://api.track.toggl.com/api/v9'
function question(question) {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(question, answer => {
resolve(answer)
rl.close();
});
})
}
async function getEntries(startDate, endDate, projectId, authorization) {
const response = await fetch(`${BASE_URL}/me/time_entries?start_date=${startDate}&end_date=${endDate}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': authorization
}
})
const entries = await response.json()
return projectId ? entries.filter(entry => entry.project_id === projectId) : entries
}
const groupByDay = entries => {
const days = {}
entries.forEach(entry => {
const date = moment(entry.start)
const dateStr = date.format('YYYY-MM-DD')
let day = days[dateStr]
if (!day) {
day = []
days[dateStr] = day
}
const startTime = date.format('HH:mm')
const endTime = moment(entry.stop).format('HH:mm')
const record = {
startTime,
endTime,
description: entry.description
}
day.push(record)
})
const ordered = []
Object.keys(days).forEach(day => {
const records = [...days[day]]
records.sort((record1, record2) => (record1.startTime.localeCompare(record2.startTime)))
ordered.push({
day,
records
})
})
ordered.sort((day1, day2) => new Date(day1.day) - new Date(day2.day))
return ordered
}
const addTimeBlocks = days => {
days.forEach(day => {
day.timeBlocks = []
let currentTimeBlock = null
let lastRecord = null
day.records.forEach(record => {
if (!currentTimeBlock) {
currentTimeBlock = {
startTime: record.startTime,
endtime: null
}
} else if (lastRecord && lastRecord.endTime !== record.startTime) {
currentTimeBlock.endTime = lastRecord.endTime
day.timeBlocks.push(currentTimeBlock)
currentTimeBlock = {
startTime: record.startTime
}
}
lastRecord = record
})
if (currentTimeBlock) {
currentTimeBlock.endTime = lastRecord.endTime
day.timeBlocks.push(currentTimeBlock)
}
})
}
const getDuration = timeBlock => moment.duration(
moment(timeBlock.endTime, 'HH:mm').diff(moment(timeBlock.startTime, 'HH:mm'))
)
const formatDuration = duration => moment.utc(duration.asMilliseconds()).format('HH:mm')
const getTotalDurationSum = day =>
day.records.reduce((acc, record) => {
const currentDurationSum = moment.duration(acc, 'hh:mm')
const duration = getDuration(record)
const newDurationSum = moment.duration(currentDurationSum.asMilliseconds() + duration.asMilliseconds())
return formatDuration(newDurationSum)
}, '00:00')
// dayArg: YYYY-MM-DD
const getEntriesForDay = async (dayArg, authorization) => {
const projectId = parseInt(getEnvVar('TOGGL_PROJECT_ID'), 10)
const startDate = dayArg
const endDate = moment(startDate, 'YYYY-MM-DD').add(1, 'day').format('YYYY-MM-DD')
const entries = await getEntries(startDate, endDate, projectId, authorization)
const byDay = groupByDay(entries)
addTimeBlocks(byDay)
addDailyHoursTotal(byDay)
return byDay
}
// monthArg: YYYY-MM
const getEntriesByDay = async (monthArg, authorization) => {
const projectId = parseInt(getEnvVar('TOGGL_PROJECT_ID'), 10)
const startDate = monthArg + '-01'
const endDate = moment(startDate, 'YYYY-MM-DD').add(1, 'months').format('YYYY-MM-DD')
const entries = await getEntries(startDate, endDate, projectId, authorization)
const byDay = groupByDay(entries)
addTimeBlocks(byDay)
addDailyHoursTotal(byDay)
return byDay
}
// Function to convert HH:MM to decimal with 2 decimal places
const timeToDecimal = timeStr => {
const [hours, minutes] = timeStr.split(':').map(Number);
const decimalTime = hours + minutes / 60;
return Math.round(decimalTime * 100) / 100;
}
const addDailyHoursTotal = days => {
days.forEach(day => {
day.hoursTotal = getTotalDurationSum(day)
day.hoursTotalDecimal = timeToDecimal(day.hoursTotal)
})
}
const getEnvVar = (name, mandatory) => {
const variable = process.env[name]
if (!variable && mandatory) {
throw new Error(`Variable ${name} is not set in the environment`)
}
return variable
}
const getArgs = () => process.argv.slice(2) // Remove the first two arguments
const getMonthArg = (inputArg) => {
const args = getArgs()
const monthArg = inputArg || args[0]
// Check if the argument exists and is in the format 'yyyy-mm'
if (monthArg && /^\d{4}-\d{2}$/.test(monthArg)) {
return monthArg
}
return null
}
const getDayArg = (inputArg) => {
const args = getArgs()
const dayArg = inputArg || args[0]
// Check if the argument exists and is in the format 'yyyy-mm-dd'
if (dayArg && /^\d{4}-\d{2}-\d{2}$/.test(dayArg)) {
return dayArg
}
return null
}
const base64 = str => Buffer.from(str).toString('base64')
module.exports = {
getEntriesByDay,
getEntriesForDay,
getEnvVar,
getArgs,
getMonthArg,
getDayArg,
base64,
question
}