-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.js
543 lines (512 loc) · 13.5 KB
/
index.js
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
const { Client } = require("@notionhq/client");
const moment = require("moment");
const momentTz = require("moment-timezone");
const ChartJSImage = require("chart.js-image");
const log = require("loglevel");
const fs = require("fs");
const core = require("@actions/core");
log.setLevel("info");
require("dotenv").config();
const parseConfig = () => {
if (process.env.NODE_ENV === "offline") {
return {
notion: {
client: new Client({ auth: process.env.NOTION_KEY }),
databases: {
backlog: process.env.NOTION_DB_BACKLOG,
sprintSummary: process.env.NOTION_DB_SPRINT_SUMMARY,
dailySummary: process.env.NOTION_DB_DAILY_SUMMARY,
},
options: {
sprintProp: process.env.NOTION_PROPERTY_SPRINT,
estimateProp: process.env.NOTION_PROPERTY_ESTIMATE,
statusExclude: process.env.NOTION_PROPERTY_PATTERN_STATUS_EXCLUDE,
},
},
chartOptions: {
isIncludeWeekends: process.env.INCLUDE_WEEKENDS !== "false",
isSprintStart: process.env.SPRINT_START === "true",
},
};
}
return {
notion: {
client: new Client({ auth: core.getInput("NOTION_KEY") }),
databases: {
backlog: core.getInput("NOTION_DB_BACKLOG"),
sprintSummary: core.getInput("NOTION_DB_SPRINT_SUMMARY"),
dailySummary: core.getInput("NOTION_DB_DAILY_SUMMARY"),
},
options: {
sprintProp: core.getInput("NOTION_PROPERTY_SPRINT"),
estimateProp: core.getInput("NOTION_PROPERTY_ESTIMATE"),
statusExclude: core.getInput("NOTION_PROPERTY_PATTERN_STATUS_EXCLUDE"),
},
},
chartOptions: {
isIncludeWeekends: core.getInput("INCLUDE_WEEKENDS") !== "false",
isSprintStart: core.getInput("SPRINT_START") === "true",
},
};
};
const createNewSprintSummary = async (
notion,
sprintSummaryDb,
{ sprint, start, end }
) =>
notion.pages.create({
parent: {
database_id: sprintSummaryDb,
},
properties: {
Name: {
title: [
{
text: {
content: `Sprint ${sprint}`,
},
},
],
},
Sprint: {
number: sprint,
},
Start: {
date: {
start,
},
},
End: {
date: {
start: end,
},
},
},
});
const getLatestSprintSummary = async (
notion,
sprintSummaryDb,
{ sprintProp }
) => {
const response = await notion.databases.query({
database_id: sprintSummaryDb,
sorts: [
{
property: sprintProp,
direction: "descending",
},
],
});
const { properties } = response.results[0];
const { Sprint, Start, End } = properties;
return {
sprint: Sprint.number,
start: moment(Start.date.start),
end: moment(End.date.start),
};
};
const countPointsLeftInSprint = async (
notion,
backlogDb,
sprint,
{ sprintProp, estimateProp, statusExclude }
) => {
const response = await notion.databases.query({
database_id: backlogDb,
filter: {
property: sprintProp,
select: {
equals: `Sprint ${sprint}`,
},
},
});
const sprintStories = response.results;
const ongoingStories = sprintStories.filter(
(item) =>
!new RegExp(statusExclude).test(item.properties.Status.select.name)
);
return ongoingStories.reduce((accum, item) => {
if (item.properties[estimateProp]) {
const points = item.properties[estimateProp].number;
return accum + points;
}
return accum;
}, 0);
};
const updateDailySummaryTable = async (
notion,
dailySummaryDb,
sprint,
pointsLeft
) => {
const today = moment().startOf("day").format("YYYY-MM-DD");
await notion.pages.create({
parent: {
database_id: dailySummaryDb,
},
properties: {
Name: {
title: [
{
text: {
content: `Sprint ${sprint} - ${today}`,
},
},
],
},
Sprint: {
number: sprint,
},
Points: {
number: pointsLeft,
},
Date: {
date: { start: today, end: null },
},
},
});
};
const isWeekend = (date) => {
const dayOfWeek = moment(date).format("ddd");
return dayOfWeek === "Sat" || dayOfWeek === "Sun";
};
/**
* Calculates the number of weekdays from {@link start} to {@link end}
* @param {moment.Moment} start First day of sprint (inclusive)
* @param {moment.Moment} end Last day of sprint (inclusive)
* @returns number of weekdays between both dates
*/
const getNumberOfWeekdays = (start, end) => {
let weekdays = 0;
for (const cur = moment(start); !cur.isAfter(end); cur.add(1, "days")) {
if (!isWeekend(cur)) {
weekdays += 1;
}
}
return weekdays;
};
/**
* Calculates the points left for each day of the sprint so far
* @param {number} sprint Sprint number of current sprint
* @param {moment.Moment} start First day of sprint (inclusive)
* @returns {number[]} Array of points left each day from {@link start} till today (inclusive)
* */
const getPointsLeftByDay = async (
notion,
dailySummaryDb,
sprint,
start,
isIncludeWeekends
) => {
const response = await notion.databases.query({
database_id: dailySummaryDb,
filter: {
property: "Sprint",
number: {
equals: sprint,
},
},
sorts: [
{
property: "Date",
direction: "ascending",
},
],
});
const pointsLeftByDay = [];
response.results.forEach((result) => {
const { properties } = result;
const { Date, Points } = properties;
const day = moment(Date.date.start).diff(start, "days");
if (pointsLeftByDay[day]) {
log.warn(
JSON.stringify({
message: "Found duplicate entry",
date: Date.date.start,
points: Points.number,
})
);
}
pointsLeftByDay[day] = Points.number;
});
const numDaysSinceSprintStart = moment().startOf("day").diff(start, "days");
for (let i = 0; i < numDaysSinceSprintStart; i += 1) {
if (!pointsLeftByDay[i]) {
pointsLeftByDay[i] = 0;
}
}
log.info(JSON.stringify({ numDaysSinceSprintStart }));
if (!isIncludeWeekends) {
// remove weekend entries
let index = 0;
for (
const cur = moment(start);
index < pointsLeftByDay.length;
cur.add(1, "days")
) {
if (isWeekend(cur)) {
pointsLeftByDay.splice(index, 1);
} else {
index += 1;
}
}
}
return pointsLeftByDay;
};
/**
* Generates the ideal burndown line for the sprint. Work is assumed to be done on
* each weekday from {@link start} until the day before {@link end}. A data point is
* generated for {@link end} to show the final remaining points.
*
* A flat line is shown across weekends if {@link isWeekendsIncluded} is set to true,
* else, the weekends are not shown.
* @param {moment.Moment} start The start of the sprint (inclusive)
* @param {moment.Moment} end The end of the sprint (inclusive)
* @param {number} initialPoints Points the sprint started with
* @param {number} numWeekdays Number of working days in the sprint
* @returns {number[]} Array of the ideal points left per day
*/
const getIdealBurndown = (
start,
end,
initialPoints,
numWeekdays,
isIncludeWeekends
) => {
const pointsPerDay = initialPoints / numWeekdays;
log.info(
JSON.stringify({
initialPoints,
numWeekdays,
pointsPerDay,
})
);
const idealBurndown = [];
const cur = moment(start);
const afterEnd = moment(end).add(1, "days"); // to include the end day data point
let isPrevDayWeekday = false;
for (let index = 0; cur.isBefore(afterEnd); index += 1, cur.add(1, "days")) {
// if not including the weekends, just skip over the weekend days
if (!isIncludeWeekends) {
while (isWeekend(cur)) {
cur.add(1, "days");
}
}
if (index === 0) {
idealBurndown[index] = initialPoints;
} else {
idealBurndown[index] =
idealBurndown[index - 1] - (isPrevDayWeekday ? pointsPerDay : 0);
}
isPrevDayWeekday = !isWeekend(cur);
}
// rounds to 2 decimal places, which prevents the graph from getting jagged
// from overtruncation when there's less than 30 points
return idealBurndown.map((points) => +points.toFixed(2));
};
/**
* Generates the labels for the chart from 1 to {@link numberOfDays} + 1
* to have a data point for after the last day.
* @param {number} numberOfDays Number of workdays in the sprint
* @returns {number[]} Labels for the chart
*/
const getChartLabels = (numberOfDays) =>
// cool way to generate numbers from 1 to n
[...Array(numberOfDays).keys()].map((i) => i + 1);
/**
* Generates the data to be displayed on the chart. Work is assumed to be
* done on each day from the start until the day before {@link end}.
* @param {number} sprint Current sprint number
* @param {moment.Moment} start Start date of sprint (included)
* @param {moment.Moment} end End date of sprint (excluded)
* @returns The chart labels, data line, and ideal burndown line
*/
const getChartDatasets = async (
notion,
dailySummaryDb,
sprint,
start,
end,
{ isIncludeWeekends }
) => {
const numDaysInSprint = moment(end).diff(start, "days") + 1;
const lastFullDay = moment(end).add(-1, "days");
const numWeekdays = getNumberOfWeekdays(start, lastFullDay);
const pointsLeftByDay = await getPointsLeftByDay(
notion,
dailySummaryDb,
sprint,
start,
isIncludeWeekends
);
const idealBurndown = getIdealBurndown(
start,
end,
pointsLeftByDay[0],
numWeekdays,
isIncludeWeekends
);
const labels = getChartLabels(
isIncludeWeekends ? numDaysInSprint : numWeekdays + 1
);
return { labels, pointsLeftByDay, idealBurndown };
};
const generateChart = (data, idealBurndown, labels) => {
const chart = ChartJSImage()
.chart({
type: "line",
data: {
labels,
datasets: [
{
label: "Burndown",
borderColor: "#ef4444",
backgroundColor: "rgba(255,+99,+132,+.5)",
data,
},
{
label: "Constant",
borderColor: "#cad0d6",
backgroundColor: "rgba(54,+162,+235,+.5)",
data: idealBurndown,
},
],
},
options: {
title: {
display: true,
text: "Sprint Burndown",
},
legend: { display: false },
scales: {
xAxes: [
{
scaleLabel: {
display: true,
labelString: "Day",
},
},
],
yAxes: [
{
stacked: false,
scaleLabel: {
display: true,
labelString: "Points Left",
},
ticks: {
beginAtZero: true,
max: Math.max(...data),
},
},
],
},
},
}) // Line chart
.backgroundColor("white")
.width(500) // 500px
.height(300); // 300px
return chart;
};
const writeChartToFile = async (chart, dir, filenamePrefix) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
await chart.toFile(`${dir}/${filenamePrefix}-burndown.png`);
};
const run = async () => {
const { notion, chartOptions } = parseConfig();
let sprint;
let start;
let end;
({ sprint, start, end } = await getLatestSprintSummary(
notion.client,
notion.databases.sprintSummary,
{ sprintProp: notion.options.sprintProp }
));
log.info(
JSON.stringify({ message: "Found latest sprint", sprint, start, end })
);
const today = momentTz.tz(new Date(), "Asia/Singapore");
if (chartOptions.isSprintStart) {
if (today.isSameOrAfter(moment(end))) {
sprint += 1;
start = today.format("YYYY-MM-DD");
end = today.add(14, "days").format("YYYY-MM-DD");
await createNewSprintSummary(
notion.client,
notion.databases.sprintSummary,
{ sprint, start, end }
);
log.info(
JSON.stringify({
message: "Created new sprint summary",
sprint,
start,
end,
})
);
} else {
log.info(
JSON.stringify({
message: "Not sprint start. Skipping rest of steps.",
currSprintEnd: end,
today: today.format("YYYY-MM-DD"),
})
);
return;
}
}
const pointsLeftInSprint = await countPointsLeftInSprint(
notion.client,
notion.databases.backlog,
sprint,
{
sprintProp: notion.options.sprintProp,
estimateProp: notion.options.estimateProp,
statusExclude: notion.options.statusExclude,
}
);
log.info(
JSON.stringify({
message: "Counted points left in sprint",
sprint,
pointsLeftInSprint,
})
);
await updateDailySummaryTable(
notion.client,
notion.databases.dailySummary,
sprint,
pointsLeftInSprint
);
log.info(
JSON.stringify({
message: "Updated daily summary table",
sprint,
pointsLeftInSprint,
})
);
const {
labels,
pointsLeftByDay: data,
idealBurndown,
} = await getChartDatasets(
notion.client,
notion.databases.dailySummary,
sprint,
start,
end,
{
isIncludeWeekends: chartOptions.isIncludeWeekends,
}
);
log.info(JSON.stringify({ labels, data, idealBurndown }));
const chart = generateChart(data, idealBurndown, labels);
await writeChartToFile(chart, "./out/all", `sprint${sprint}-${Date.now()}`);
await writeChartToFile(chart, "./out/latest", `sprint${sprint}-latest`);
log.info(
JSON.stringify({ message: "Generated burndown chart", sprint, data })
);
};
run();