This repository was archived by the owner on Feb 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
424 lines (368 loc) · 13.6 KB
/
Copy pathmain.js
File metadata and controls
424 lines (368 loc) · 13.6 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
'use strict';
const fs = require('fs');
const util = require('util');
const {
google
} = require('googleapis');
const commandLineArgs = require('command-line-args');
const commandLineUsage = require('command-line-usage')
const config = require('./config.js');
const trello = require('./trello.js');
const SCOPES = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets',
];
const optionDefinitions = [{
name: 'operation',
alias: 'o',
type: String,
description: "Operation you want to perform on your google spreadsheet. Current operations are: {blue.bold get} - {cyan.italic get list of entries in google spreatsheet (take additional option --sheet)}, {blue.bold addSprintLabel} - {cyan.italic add sprint label, default: Planned, to cards in trello board (perform this at starting of sprint)}, {blue.bold createBacklog} - {cyan.italic fetch cards in current sprint from trello board and write them to google spreadsheet (perform this at starting of each sprint)}, {blue.bold addToUnplanned} - {cyan.italic update unplanned google spreadsheet for cards added in between sprint}, {blue.bold updateSheet} - {cyan.italic Read current entries present in sheet then fetch corresponding card details from trello and update values} and {blue.bold clear} - {cyan.italic clear list of cards in google spreadsheet (take additional option --sheet)}"
}, {
name: 'sheet',
alias: 's',
type: String,
defaultValue: "backlog",
description: "Name of sheet in google spreadsheet on which you want to perform operation. Allowed - {blue.bold backlog, unplanned}, {cyan default: backlog}."
}, {
name: 'help',
alias: 'h',
type: Boolean,
description: "Display this usage guide.",
}, ];
const sections = [{
header: 'Trello google sheet integration for sprint',
content: 'Integrate trello and google sheet for handling sprint for your team.'
},
{
header: 'Synopsis',
content: '$ node index.js <options>'
},
{
header: 'Options',
optionList: optionDefinitions,
tableOptions: {
columns: [{
name: 'option',
noWrap: true,
width: 30
},
{
name: 'description',
width: 50,
}
]
}
}
]
const options = commandLineArgs(optionDefinitions, {
stopAtFirstUnknown: true
});
const usage = commandLineUsage(sections)
const help = options.help;
if (help) {
console.log(usage);
return;
}
// validates
if (!process.env.NODE_CONFIG_DIR) throw 'Missing NODE_CONFIG_DIR. Please pass the config directory path where config file is present. To set config file please make use "setdefaults.js".';
if (!process.env.GOOGLE_PRIVATE_KEY_FILE_PATH) throw 'Missing GOOGLE_PRIVATE_KEY_FILE_PATH. Please get JWT private key file from your account. Refer https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth.';
if (!process.env.GOOGLE_SPREADSHEET_ID) throw 'Missing GOOGLE_SPREADSHEET_ID, Please provide spreadsheet id to track sprint.';
if (!process.env.TRELLO_API_KEY) throw 'Missing TRELLO_API_KEY. Please provide your trello user API key.';
if (!process.env.TRELLO_API_TOKEN) throw 'Missing TRELLO_API_TOKEN. Please provide your trello user API token.';
const operation = options.operation;
const sheetName = options.sheet ? options.sheet : "backlog";
const googlesheetConfig = config.getGooglesheetConfig;
if (options.sheet && !/^(?:backlog|unplanned)$/.test(options.sheet)) {
console.log("Invalid sheet name provided. Only backlog and unplanned are allowed");
return;
}
if (!operation) {
console.log("No operation provided! Usage <script> --<operation_name>");
console.log("Operations allowed: get|clear|createBacklog|addToUnplanned|updateSheet|addSprintLabel");
} else if (/^(?:get|clear|createBacklog|addToUnplanned|addSprintLabel|updateSheet)$/.test(operation)) {
switch (operation) {
case "get":
authorize().then(get);
break;
case "clear":
authorize().then(clear);
break;
case "createBacklog":
authorize().then(writeSprintBacklog);
break;
case "addToUnplanned":
authorize().then(addToUnplanned);
break;
case "addSprintLabel":
trello.addSprintLabel()
break;
case "updateSheet":
authorize().then(updateSheet);
break;
}
}
/**
* Read google sheet jwt credentials from file
*/
async function readCredentialsFile() {
const readFile = util.promisify(fs.readFile);
return await readFile(process.env.GOOGLE_PRIVATE_KEY_FILE_PATH, 'utf8');
}
/**
* Get google auth JWT client with specified scopes
* @param {privatekey} contains content of jwt credentials file
*/
async function getAuthenticatedClient(privatekey) {
return await new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
SCOPES);
}
/**
* Return an authenticated client to be used for current operation
*/
async function authorize() {
const data = await readCredentialsFile()
return await getAuthenticatedClient(JSON.parse(data));
}
/**
* Get and print to console the rows fetched for
* google sheet
* @param {auth} The google authentication client based on JWT
*/
function get(auth) {
const sheets = google.sheets({
version: 'v4',
});
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"][sheetName]["name"] + googlesheetConfig["sheets"][sheetName]["range"],
}, (err, response) => {
if (err) {
console.error(err);
return;
}
console.log("Status", response.status);
console.log(JSON.stringify(response.data, null, 2));
});
}
/**
* Fetch trello cards marked with sprint label and
* write to sprint backlog google sheet
* @param {auth} The google authentication client based on JWT
*/
async function writeSprintBacklog(auth) {
const sheets = google.sheets({
version: 'v4',
auth
});
let cards = await getTrelloCards("planned");
if (!cards || cards.length === 0) {
console.log("No cards. Nothing updated!");
return;
}
sheets.spreadsheets.values.get({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"]["backlog"]["name"] + googlesheetConfig["sheets"]["backlog"]["range"],
}, (err, response) => {
if (err) {
console.error(err);
return;
}
if (response.status == 200 && response.data.values && response.data.values.length > 0) {
console.error("Sprint backlog already contains data. If it's for new sprint please clear data first using clear operation.");
} else {
sheets.spreadsheets.values.update({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"]["backlog"]["name"] + '!A2',
valueInputOption: 'USER_ENTERED',
resource: {
majorDimension: "ROWS",
values: cards,
},
}, (err, response) => {
if (err) {
console.error(err);
return;
}
console.log("Status", response.status);
console.log(JSON.stringify(response.data, null, 2));
});
}
});
}
/**
* Clear out the google sheet based on sheet name passed
* @param {auth} The google authentication client based on JWT
*/
function clear(auth) {
const sheets = google.sheets({
version: 'v4',
auth
});
sheets.spreadsheets.values.clear({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"][sheetName]["name"] + googlesheetConfig["sheets"][sheetName]["range"],
}, (err, response) => {
if (err) {
console.error(err);
return;
}
console.log("Status", response.status);
console.log(JSON.stringify(response.data, null, 2));
});
}
/**
* Fetch trello cards not marked with sprint label and
* write to unplanned google sheet cards that are not
* already added to the sheet
* @param {auth} The google authentication client based on JWT
*/
async function addToUnplanned(auth) {
const sheets = google.sheets({
version: 'v4',
auth
});
const unplannedCards = await getTrelloCards("unplanned");
if (!unplannedCards || unplannedCards.length === 0) {
console.log("No cards. Nothing updated!");
return;
}
sheets.spreadsheets.values.get({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"]["unplanned"]["name"] + googlesheetConfig["sheets"]["unplanned"]["range"],
}, (err, response) => {
if (err) {
console.error(err);
return;
}
const existingEntries = response.data.values;
let cardIdentifiers = {};
if (existingEntries && existingEntries.length > 0) {
existingEntries.forEach((entry) => {
cardIdentifiers[entry[1]] = entry[1]
});
}
let cards = unplannedCards.filter((card) => {
return !cardIdentifiers[card[1]]
});
sheets.spreadsheets.values.append({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"]["unplanned"]["name"] + '!A3',
valueInputOption: 'USER_ENTERED',
insertDataOption: 'INSERT_ROWS',
responseDateTimeRenderOption: 'FORMATTED_STRING',
resource: {
majorDimension: "ROWS",
values: cards,
},
}, (err, response) => {
if (err) {
console.error(err);
return;
}
console.log("Status", response.status);
console.log(JSON.stringify(response.data, null, 2));
});
});
}
/**
* Read current entries present in sheet then fetch
* corresponding card details from trello and update values
* fetched from trello.
* @param {auth} The google authentication client based on JWT
*/
let detailsToUpdate = [];
async function updateSheet(auth) {
const sheets = google.sheets({
version: 'v4',
auth
});
let promiseArray = [];
sheets.spreadsheets.values.get({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
range: googlesheetConfig["sheets"][sheetName]["name"] + googlesheetConfig["sheets"][sheetName]["range"],
}, (err, response) => {
if (err) {
console.error(err);
return;
}
const existingEntries = response.data.values;
if (existingEntries && existingEntries.length > 0) {
let count = 2;
let rangeNumberMatch = googlesheetConfig["sheets"][sheetName]["range"].match(/\d+/);
if (rangeNumberMatch && rangeNumberMatch.length > 0) {
count = rangeNumberMatch[0];
}
existingEntries.forEach((entry) => {
promiseArray.push(getDetailsInSheetFormat(entry, count));
count++;
});
Promise.all(promiseArray).then(() => {
sheets.spreadsheets.values.batchUpdate({
spreadsheetId: process.env.GOOGLE_SPREADSHEET_ID,
resource: {
valueInputOption: 'USER_ENTERED',
responseDateTimeRenderOption: 'FORMATTED_STRING',
data: detailsToUpdate
},
}, (err, response) => {
if (err) {
console.error(err);
return;
}
console.log("Status", response.status);
console.log(JSON.stringify(response.data, null, 2));
});
}, (reason) => {
console.log(reason);
});
} else {
console.log("No data present in sheet to be updated.");
}
});
}
/**
* Get all trello cards of board, for particular
* label
* @param {label} label for which filtering needs to be done
*/
async function getTrelloCards(label) {
let cards = await trello.getCards();
let values = [];
cards[label].forEach((card) => {
values.push(filterDetailsOfCard(card));
});
return values;
};
/**
* Filter details of trello card that are required to be populated
* in sheet and return in particular order
* @param {card} card for which filtering needs to be done
*/
function filterDetailsOfCard(card) {
return [card.name, card.identifier, card.url, card.estimate, card.consumed, card.member, card.status, card.due]
}
/**
* Get details of card in particular format required for batch update
* operation of google sheet api
* @param {entry} row in googlesheet
* @param {currentRangeIndex} current range for entry in google sheet
*/
async function getDetailsInSheetFormat(entry, currentRangeIndex) {
let details = await trello.getCardDetails(entry[1]);
let processedDetails = entry;
if (details) {
processedDetails = filterDetailsOfCard(details);
}
processedDetails = processedDetails.map((value) => [value])
detailsToUpdate.push({
range: googlesheetConfig["sheets"][sheetName]["name"] + '!A' + currentRangeIndex + ':H' + currentRangeIndex,
majorDimension: "COLUMNS",
values: processedDetails
});
return;
}