-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
237 lines (195 loc) · 7.65 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
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A simple slash command for slack that reports the current revenue based
on mites time tracking and a simple revenue projection for the current year.
It is based on
- botkit: http://howdy.ai/botkit
- mite: http://mite.yo.lk
For more information consult the README.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// DEPENDENCIES
var _ = require('underscore')._;
var miteAPI = require('mite-api');
var Botkit = require('botkit');
// HELPER FUNCTIONS
var printHelp = function(missingEnvVariable) {
console.log("An error occurred. Environment Variable missing: " + missingEnvVariable)
console.log("Usage: MITE_API_KEY=[MITE API KEY] CLIENT_ID=[SLACK CLIENT_ID] CLIENT_SECRET=[SLACK CLIENT SECRET] VERIFICATION_TOKEN=[SLACK VERIFICATION TOKEN] PORT=[PORT] npm start")
}
var goodJobArray = [
"Great!",
"You are so awesome",
"Nice job!",
"Keep up the great work!",
"You rock!",
"Can you spend all this money?",
"http://giphy.com/gifs/homer-simpson-the-simpsons-season-6-DTywu7YYjWCVW",
"https://media3.giphy.com/media/l3UcA1HpL5kLuiWOc/giphy.gif",
"http://media3.giphy.com/media/plrhd7RveGGZy/giphy.gif"
]
var okButCanBeBetterArray = [
"Not bad!",
"Good! Not great, but good!",
"http://giphy.com/gifs/not-bad-bill-and-ted-JyjWw4ZLdSPE4",
"http://giphy.com/gifs/season-11-the-simpsons-11x3-l2JdXjyFmZj1Ijb6o",
"http://giphy.com/gifs/DnAMdo0dZrlm"
]
var youShouldWorkMoreArray = [
"What's going on? Are you ok?",
"Next week will be better... probably",
"Come on, let's go!",
"I am sure, you can do better than that!",
"Whatever, I'll do what I want...",
"¯\_(ツ)_/¯"
]
// the projected revenue in thousands
var getFeedback = function(projectedRevenue) {
var array;
if (projectedRevenue > process.env.FEEDBACK_H) {
array = goodJobArray;
} else if (projectedRevenue >= process.env.FEEDBACK_L && projectedRevenue <= process.env.FEEDBACK_H) {
array = okButCanBeBetterArray;
} else if (projectedRevenue < process.env.FEEDBACK_L) {
array = youShouldWorkMoreArray;
}
return array[Math.floor(Math.random() * array.length)];
}
var shouldDisplayFeedback = function() {
return (process.env.FEEDBACK == "true" && process.env.FEEDBACK_H && process.env.FEEDBACK_L)
}
// MITE FUNCTIONS
var getDayInCurrentYear = function() {
var now = new Date();
var start = new Date(now.getFullYear(), 0, 0);
var diff = now - start;
var oneDay = 1000 * 60 * 60 * 24;
return Math.floor(diff / oneDay);
}
var getDaysInCurrentYear = function() {
var year = new Date().getFullYear();
if(year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
// Leap year
return 366;
} else {
// Not a leap year
return 365;
}
}
var getFinancialMetrics = function(resultCallback) {
var year = new Date().getFullYear();
mite.getTimeEntries({"year": year}, function(error, time_entry_wrappers) {
var days_remaining_this_year = getDaysInCurrentYear() - getDayInCurrentYear();
var fourWeeksAgo = new Date();
fourWeeksAgo.setDate(fourWeeksAgo.getDate() - 28);
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
var entries = _.map(time_entry_wrappers, function(time_entry_wrapper) { return time_entry_wrapper.time_entry; });
var entries_this_year = _.filter(entries, function(time_entry) { return time_entry.date_at.indexOf(year) == 0; });
var entries_last_4_weeks = _.filter(entries_this_year, function(time_entry) {
return new Date(time_entry.created_at) > fourWeeksAgo;
});
var entries_last_week = _.filter(entries_last_4_weeks, function(time_entry) {
return new Date(time_entry.created_at) > oneWeekAgo;
});
var rev_this_year = _.reduce(entries_this_year, function(memo, time_entry) {
return memo + time_entry.hourly_rate * (time_entry.minutes / 60.0);
}, 0);
var rev_last_4_weeks = _.reduce(entries_last_4_weeks, function(memo, time_entry) {
return memo + time_entry.hourly_rate * (time_entry.minutes / 60.0);
}, 0);
var rev_per_day_in_last_4_weeks = rev_last_4_weeks / 28;
var rev_last_week = _.reduce(entries_last_week, function(memo, time_entry) {
return memo + time_entry.hourly_rate * (time_entry.minutes / 60.0);
}, 0);
var rev_per_day_in_last_week = rev_last_week / 7;
var projection_per_year = Math.round(rev_this_year * (getDaysInCurrentYear() / getDayInCurrentYear() / 100.0));
var projection_per_last_4_weeks = Math.round((rev_this_year + rev_per_day_in_last_4_weeks * days_remaining_this_year) / 100.0);
var projection_per_last_7_days = Math.round((rev_this_year + rev_per_day_in_last_week * days_remaining_this_year) / 100.0);
var current_revenue = Math.round(rev_this_year / 100.0)
resultCallback(projection_per_year, projection_per_last_4_weeks, projection_per_last_7_days, current_revenue);
});
};
// START
var env_variables = ["CLIENT_ID", "CLIENT_SECRET", "VERIFICATION_TOKEN", "MITE_API_KEY", "PORT"]
for (i in env_variables) {
env_var = env_variables[i]
if (!process.env[env_var]) {
printHelp(env_var)
process.exit(1)
}
}
var config = {}
if (process.env.MONGODB_URI) {
var BotkitStorage = require('botkit-storage-mongo');
config = {
storage: BotkitStorage({mongoUri: process.env.MONGODB_URI}),
};
} else {
config = {
json_file_store: './db_slackbutton_slash_command/',
};
}
var controller = Botkit.slackbot(config).configureSlackApp(
{
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
scopes: ['commands'],
}
);
var mite = miteAPI(
{
account: 'creativepragmatics',
apiKey: process.env.MITE_API_KEY,
applicationName: 'MiteRevenueReport4Slack'
}
);
controller.setupWebserver(process.env.PORT, function (err, webserver) {
controller.createWebhookEndpoints(controller.webserver);
controller.createOauthEndpoints(controller.webserver, function (err, req, res) {
if (err) {
res.status(500).send('ERROR: ' + err);
} else {
res.send('Success! Now go to Slack and type /revenue');
}
});
});
controller.on('slash_command', function (slashCommand, message) {
switch (message.command) {
case "/revenue":
// ignore the message if the token does not match.
if (message.token !== process.env.VERIFICATION_TOKEN) return;
if (message.text == "") {
var immediate = {
"text": "Please hold the line, while I do some magic!",
"username": "MiteRevenueReport4Slack",
"mrkdwn": true
}
slashCommand.replyPublic(message, immediate, function() {
getFinancialMetrics(
function(projection_per_year, projection_per_last_4_weeks, projection_per_last_7_days, rev_this_year) {
yearly = Math.round(projection_per_year / 1000)
monthly = Math.round(projection_per_last_4_weeks / 1000)
weekly = Math.round(projection_per_last_7_days / 1000)
report = "Revenue: *EUR " + rev_this_year + "*"
report += "\n\n_Projection_:\n"
report += "This year: *EUR " + yearly + "K*\n"
report += "Last 4 weeks: *EUR " + monthly + "K*\n"
report += "Last week: *EUR " + weekly + "K*"
if (shouldDisplayFeedback()) {
report += "\n\n"
report += getFeedback(yearly)
}
var result = {
"text": report,
"username": "MiteRevenueReport4Slack",
"mrkdwn": true
}
slashCommand.replyPublicDelayed(message, result)
}
);
})
}
break
default:
slashCommand.replyPrivate(message, "/shrug I am sorry, but I have no idea what this means " + message.command)
}
});