-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathroom8lib.js
129 lines (126 loc) · 4.07 KB
/
room8lib.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
//////////////////////////////////////////////////////
// Dependencies & Configs
//////////////////////////////////////////////////////
require('dotenv').config();
const mailgun = require('mailgun-js');
//////////////////////////////////////////////////////
// Private functions
//////////////////////////////////////////////////////
subjectMaker = (template) => {
switch (template) {
case 'test_poll':
return 'Test Email!';
case 'new_poll':
return 'Your new poll has been created!';
case 'poll_ended':
return 'Your poll has ended, check out the results!';
default:
return 'Mail from room8';
}
}
//////////////////////////////////////////////////////
// Public Methods
//////////////////////////////////////////////////////
module.exports = (knex) => {
return {
sendMail: function (sendTo, templateData, ccAddresses) {
const DOMAIN = process.env.MAILGUN_DOMAIN;
const mg = mailgun({ apiKey: process.env.MAILGUN_KEY, domain: DOMAIN });
const { emailVars, templateName } = templateData;
const data = {
from: `Room8 <postmaster@${DOMAIN}>`,
to: sendTo,
cc: (ccAddresses ? ccAddresses : []),
subject: subjectMaker(templateName),
template: templateName,
"h:X-Mailgun-Variables": JSON.stringify(emailVars)
}
mg.messages().send(data, function (err, body) {
if (err) {
console.warn('Error occured while trying to send mail. Please see error stack below:\n', err);
}
console.log(body); // Log Mailgun API response
})
},
weightRow: function (row) {
if (!row) {
return null;
}
const results = new Array();
for (let i in row) {
results[i] = row[i] / row.length;
}
return results;
},
doTheBorda: function (response) {
for (var i in response){
if (response[i].answers){
var answerLength = response[i].answers.length
}
}
let results = new Array(answerLength);
const responded = {};
// Seed results with 0s
results.fill(0);
for (let row of response) {
let weighted = this.weightRow(row.answers);
responded[row.id] = (weighted ? true : false);
if (weighted) {
for (let i in weighted) {
results[i] += weighted[i];
}
}
}
// convert to percentages (4 sig-figs)
let totalScore = 0;
results.forEach( score => totalScore += score);
results = results.map( x => Math.round((x / totalScore) * 10000) / 10000);
return { "responses": responded, "scores": results };
},
getResults: function (poll_id, callback) {
knex
.select("answers", "id")
.from("submissions")
.where("poll_id", "=", poll_id)
.then((res) => {
if (res.length > 0) {
let calculated;
try{
calculated = this.doTheBorda(res);
}
catch (err){
console.log(err);
// Shorter error logging for expected error (i.e. when the poll is created there are no answers yet)
let reason = (res[0].answers === null ? "There are no answers yet!" : "An error occurred:\n" + err);
console.warn('Failed to calculate results because ' + reason);
}
callback(calculated);
} else {
callback(`No results found for ${poll_id}`);
}
})
.catch((err) => {
console.warn(err);
})
},
updatePollStatus: function (poll_id, still_active) {
knex.select("answers")
.from("submissions")
.where("poll_id", "=", poll_id)
.then( (rows) => {
const completed = new Array();
for (let row of rows) {
completed.push(row.answers ? true : false);
}
active = !(completed.indexOf(false) === -1)
knex("polls")
.where("id", "=", poll_id)
.update({"is_active": active})
.then(() => {
still_active = active;
console.log('Poll is active: ', active)
})
})
}
}
}