-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
434 lines (391 loc) · 12.2 KB
/
index.js
File metadata and controls
434 lines (391 loc) · 12.2 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
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
423
424
425
426
427
428
429
430
431
432
433
434
require('dotenv').config();
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const puppeteer = require('puppeteer');
const delayObject = { delay: 20 };
let PROJEKTRON_LINK;
let PROJEKTRON_USER;
let PROJEKTRON_PWD;
const tableSelector =
'table[class=" list fixableTableHeader_jq ListDisplay sizable orderable"] > tbody';
let toSave;
async function run() {
await checkEnvVariables();
try {
toSave = require('./export.json');
if (!Array.isArray(toSave)) {
console.log('Converting from Logbook.com format');
toSave = convertFromLogminionFormat(toSave);
}
} catch (e) {
console.log(e);
}
if (!toSave || toSave.length === 0) {
console.log('No data to book. Exiting...');
process.exit();
}
const browser = await puppeteer.launch({
headless: false
});
const page = (await browser.pages())[0];
await page.goto(PROJEKTRON_LINK);
await performLogin(page);
await dismissNotificationDialog(page);
await goToWeeklyLogs(page);
let rowsHandles = await getLogRowsHandles(page);
let rowInfo = await getRequiredTaskRowsInfo(rowsHandles, page);
await fillWeek(page, rowInfo);
await page.waitFor(100);
await page.waitForSelector('input[data-bcs-button-name="Apply"]');
await page.click('input[data-bcs-button-name="Apply"]');
await page.waitFor(2000);
await browser.close();
console.log('Done!');
process.exit();
}
async function performLogin(page) {
await page.waitForSelector('input[id=label_user]');
await page.type('input[id=label_user]', PROJEKTRON_USER, {
delay: 10
});
await page.type('input[id=label_pwd]', PROJEKTRON_PWD, {
delay: 10
});
await page.click('input[type=submit]');
}
async function dismissNotificationDialog(page) {
await page.waitForSelector(
'input[class="button notificationPermissionLater"]'
);
await page.click('input[class="button notificationPermissionLater"]');
}
async function goToWeeklyLogs(page) {
await page.click('a[id="PageTab_Link_jq_multidaytimerecording"]');
}
async function getLogRowsHandles(page) {
await page.waitForSelector(
'td[class="listheader blueMarkRow ui-draggable-handle"]'
);
const rowSelector = tableSelector + ' > tr td:nth-child(1) .hover.toBlur';
return await page.$$(rowSelector);
}
function getWeekStartTimeStamp() {
let ts = getCurrentMondayDate(new Date());
ts.setHours(0, 0, 0, 0);
ts = ts.getTime();
return ts;
}
const getInformationToFillForProject = function(projectData) {
const [project, task] = projectData;
for (let k = 0; k < toSave.length; k++) {
const toBook = toSave[k];
if (
toBook.project.trim() === project.trim() &&
toBook.task.trim() === task.trim()
) {
return toBook;
}
}
return undefined;
};
const isProjectInFillScope = function(project, task) {
let isInScope = false;
toSave.forEach(toBook => {
if (
toBook.project.trim() === project.trim() &&
toBook.task.trim() === task.trim()
) {
isInScope = true;
return true;
}
});
return isInScope;
};
function getCurrentMondayDate(d) {
d = new Date(d);
let day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
function addDaysToDate(date, days) {
let result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
function isEmpty(toTest) {
return !toTest || toTest === '';
}
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
async function getRequiredTaskRowsInfo(elements, page) {
let data = [];
let cell = [];
let indexesToReturn = [];
await asyncForEach(elements, async (el, idx) => {
const text = await page.evaluate(element => element.textContent, el);
cell.push(text);
if (idx % 2 != 0) {
data.push(cell);
if (isProjectInFillScope(cell[0], cell[1])) {
indexesToReturn.push({ index: Math.floor(idx / 2), data: cell });
}
cell = [];
}
});
return indexesToReturn;
}
async function fillWeek(page, projectRowData) {
let mondayTimeStamp = getWeekStartTimeStamp();
await asyncForEach(projectRowData, async projectData => {
let informationsToFill = getInformationToFillForProject(projectData.data);
let projectRowIndex = projectData.index;
console.log(
'Processing project: ',
projectData.data[0] + ' ' + projectData.data[1]
);
await asyncForEach(informationsToFill.hours, async (hour, dayIndex) => {
console.log('Processing day: ', getWeekDayString(dayIndex));
await fillDay(page, hour, dayIndex, projectRowIndex, mondayTimeStamp);
});
});
}
function getWeekDayString(day) {
switch (day + 1) {
case 1:
return 'Mon';
case 2:
return 'Tue';
case 3:
return 'Wed';
case 4:
return 'Thu';
case 5:
return 'Fri';
case 6:
return 'Sat';
case 7:
return 'Sun';
}
}
async function fillDay(page, hour, dayIndex, projectRowIndex, mondayTimeStamp) {
let currentTimestamp = addDaysToDate(mondayTimeStamp, dayIndex).getTime();
let timeSplit = hour.time.split(':');
const comment = hour.comment;
const hourCount = timeSplit[0];
const minutesCount = timeSplit[1];
if (isEmpty(comment) || isEmpty(hourCount) || isEmpty(minutesCount)) {
console.log('nothing to process');
return;
}
if (parseInt(hourCount, 10) === 0 && parseInt(minutesCount, 10) === 0) {
console.log('no time booked for that day');
return;
}
await page.waitFor(1000);
await fillHours(page, projectRowIndex, dayIndex, hourCount);
await fillMinutes(page, projectRowIndex, dayIndex, minutesCount);
await openComment(page, projectRowIndex, currentTimestamp);
await fillComment(page, comment);
await closeCommentDialog(page);
}
async function fillHours(page, projectRowIndex, dayIndex, hourCount) {
let hoursInputKey = `0_${projectRowIndex}_${5 + dayIndex}_0`;
await page.waitFor(500);
await page.focus(`input[id="${hoursInputKey}"]`);
await page.keyboard.press('Backspace');
await page.type(`input[id="${hoursInputKey}"]`, hourCount, delayObject);
await page.keyboard.press('Backspace');
await page.type(`input[id="${hoursInputKey}"]`, hourCount, delayObject);
}
async function fillMinutes(page, projectRowIndex, dayIndex, minutesCount) {
let minutesInputKey = `0_${projectRowIndex}_${5 + dayIndex}_1`;
await page.waitFor(500);
await page.focus(`input[id="${minutesInputKey}"]`);
await page.keyboard.press('Backspace');
await page.type(`input[id="${minutesInputKey}"]`, minutesCount, delayObject);
await page.keyboard.press('Backspace');
await page.type(`input[id="${minutesInputKey}"]`, minutesCount, delayObject);
}
async function openComment(page, projectRowIndex, currentTimestamp) {
await page.click(
`${tableSelector} > tr:nth-child(${projectRowIndex +
1}) > td[data-date~="${currentTimestamp}"] button`,
delayObject
);
}
async function fillComment(page, comment) {
await page.waitFor(50);
const textAreaSelector = `.textAttributeShort textarea`;
await page.waitForSelector(textAreaSelector);
await page.waitFor(100);
await page.$eval(textAreaSelector, el => el.focus());
await page.keyboard.type(comment, { delay: 10 });
}
async function closeCommentDialog(page) {
await page.waitFor(500);
await page.keyboard.press('Tab', {
delay: 100
});
await page.waitFor(1000);
await page.keyboard.press('Enter', {
delay: 100
});
await page.waitFor(500);
}
function convertFromLogminionFormat(file) {
let toBook = [];
Object.keys(file).forEach(dayKey => {
let processingDayDate = new Date(parseInt(dayKey, 10));
if (!isDateThisWeek(processingDayDate)) {
return;
}
let dayInfo = file[dayKey];
Object.keys(dayInfo).forEach(taskName => {
if (!taskName.includes('|')) {
return;
}
const taskParts = taskName.split('|');
let botProject = taskParts[0].trim();
let botTask = taskParts[1].trim();
toBook = addTaskIfNotInArray(toBook, botProject, botTask);
const logs = dayInfo[taskName];
const dayNumber = processingDayDate.getDay();
toBook = addLogsToBook(toBook, botProject, botTask, dayNumber, logs);
});
});
return toBook;
}
function isDateThisWeek(date) {
//SUNDAY is 0
const MS_IN_DAY = 86400 * 1000;
const today = new Date();
today.setHours(0, 0, 0, 0);
const diff = today.getTime() - date.getTime();
const daysDiff = diff / MS_IN_DAY;
const maxDiff = today.getDay() - 1;
if (daysDiff <= maxDiff && daysDiff >= 0) {
return true;
} else {
return false;
}
}
function addTaskIfNotInArray(toBook, projectName, taskName) {
let found = false;
toBook.forEach(task => {
if (found) {
return;
}
found = task.project === projectName && task.task === taskName;
});
if (!found) {
toBook.push({
project: projectName,
task: taskName,
hours: [
{ comment: '', time: '0:00' },
{ comment: '', time: '0:00' },
{ comment: '', time: '0:00' },
{ comment: '', time: '0:00' },
{ comment: '', time: '0:00' }
]
});
}
return toBook;
}
function addLogsToBook(toBook, projectName, taskName, day, logs) {
const arrayIndexDay = day - 1;
if (arrayIndexDay > 4 || arrayIndexDay < 0) {
console.log('task is not during week');
return;
}
toBook.forEach(task => {
if (task.project === projectName && task.task === taskName) {
let totalDuration = getLogsTotalDuration(logs);
let stringDuration =
String((totalDuration - (totalDuration % 60)) / 60) +
':' +
String(totalDuration % 60);
let summary = getSummaryDescription(logs);
task.hours[arrayIndexDay].comment = summary;
task.hours[arrayIndexDay].time = stringDuration;
}
});
return toBook;
}
function getLogsTotalDuration(logs) {
let totalDurationInMinutes = 0;
logs.forEach(log => {
totalDurationInMinutes += Math.floor(log.duration / 60);
});
return totalDurationInMinutes;
}
function getSummaryDescription(logs) {
let summary = '';
logs.forEach(log => {
summary += log.description + ', ';
});
return summary;
}
async function checkEnvVariables() {
let disrupted = false;
if (!process.env.PROJEKTRON_LINK || process.env.PROJEKTRON_LINK === '') {
console.error('Missing PROJEKTRON_LINK env variable');
disrupted = true;
} else {
PROJEKTRON_LINK = process.env.PROJEKTRON_LINK;
}
if (!process.env.PROJEKTRON_USER || process.env.PROJEKTRON_USER === '') {
console.error('Missing PROJEKTRON_USER env variable');
disrupted = true;
} else {
PROJEKTRON_USER = process.env.PROJEKTRON_USER;
}
if (!process.env.PROJEKTRON_PWD || process.env.PROJEKTRON_PWD === '') {
console.error('Missing PROJEKTRON_PWD env variable');
disrupted = true;
} else {
PROJEKTRON_PWD = process.env.PROJEKTRON_PWD;
}
if (disrupted) {
console.error(
'Missing ENV configuration. Enter values or set ENV variables first.'
);
let linkInput = await getInput('Give your Projektron link: ');
if (!isEmpty(linkInput)) {
PROJEKTRON_LINK = linkInput.trim();
}
let usernameInput = await getInput(
'Give your Projektron username(or email): '
);
if (!isEmpty(usernameInput)) {
PROJEKTRON_USER = usernameInput.trim();
}
let passwordInput = await getInput('Give your Projektron password: ');
if (!isEmpty(passwordInput)) {
PROJEKTRON_PWD = passwordInput.trim();
}
rl.close();
if (
isEmpty(PROJEKTRON_LINK) ||
isEmpty(PROJEKTRON_USER) ||
isEmpty(PROJEKTRON_PWD)
) {
console.error('Invalid configuration. Try again...');
process.exit();
}
}
}
function getInput(question) {
return new Promise(resolve => {
rl.question(question, answer => {
resolve(answer);
});
});
}
run();