-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
331 lines (298 loc) · 9.58 KB
/
index.js
File metadata and controls
331 lines (298 loc) · 9.58 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
const express = require('express')
require('dotenv').config()
const bodyParser = require('body-parser')
const mysql = require('mysql2/promise')
const { WebClient } = require('@slack/web-api')
const app = express()
const port = process.env.PORT || 3000
const db = mysql.createPool({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_NAME,
})
// Slack Web API Client
const web = new WebClient(process.env.SLACK_BOT_TOKEN)
// Middleware
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
// Endpoint
app.get('/send-reminders', async (req, res) => {
try {
await sendReminderWithButton()
res.send('Reminders sent successfully!')
} catch (error) {
console.error('Error sending reminders:', error)
res.status(500).send('Failed to send reminders')
}
})
app.get('/sync-users', async (req, res) => {
try {
const response = await web.users.list()
console.log('response---------------------', response)
const users = response.members.filter((user) => !user.is_bot && !user.deleted)
const [rows] = await db.query('SELECT * FROM users')
//save to database
const newUsers = users
.filter((user) => {
if (user.id == 'USLACKBOT') {
return false
} else if (rows.some((u) => u.slack_id == user.id)) {
return false
}
return true
})
.map((user) => ({
email: user.name,
name: user.real_name,
slack_id: user.id,
is_active: false,
}))
//insert new users into db
if (newUsers.length > 0) {
const values = newUsers.map((user) => [user.email, user.name, user.slack_id, user.is_active])
await db.query('INSERT INTO users (email, name, slack_id, is_active) VALUES ?', [values])
}
res.send('Users synced')
} catch (error) {
console.error('Error sync users:', error)
res.status(500).send('Failed to sync users: ' + JSON.stringify(error))
}
})
// Endpoint to handle Slack interactions
app.post('/slack/interactions', async (req, res) => {
const payload = JSON.parse(req.body.payload)
try {
if (payload.type === 'block_actions' && payload.actions[0].action_id === 'open_timesheet_modal') {
await handleButtonClick(res, payload)
} else if (payload.type === 'view_submission' && payload.view.callback_id === 'submit_timesheet') {
await handleModalResponse(res, payload)
} else {
console.log('unable to understand the action:', payload)
res.status(500).send('unable to understand the action')
return
}
} catch (error) {
console.error('unable to understand the action with errors:', error)
res.status(500).send('unable to understand the action with errors')
}
})
//handlers
async function sendReminderWithButton() {
const [definedUsers] = await db.query(`
SELECT DISTINCT users.* FROM users
WHERE users.is_active = 1
AND users.slack_id NOT IN (
SELECT t.user_slack_id
FROM timesheets t
WHERE DATE(t.created_at) = CURDATE()
)
`)
for (const user of definedUsers) {
try {
await web.chat.postMessage({
channel: user.slack_id,
text: 'Please fill out your timesheet!',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: 'Hi, please fill out your daily task details by clicking the button below:',
},
},
{
type: 'actions',
elements: [
{
type: 'button',
text: {
type: 'plain_text',
text: 'Fill Timesheet',
emoji: true,
},
action_id: 'open_timesheet_modal', // Action triggers the modal
},
],
},
],
})
console.log(`Reminder sent to user ${user.slack_id}`)
} catch (error) {
console.error(`Error sending reminder to user ${user.slack_id}:`, error)
}
}
}
async function handleButtonClick(res, payload) {
if (!(await canUserSubmit(payload.user.id))) {
res.sendStatus(200)
return
}
try {
await web.views.open({
trigger_id: payload.trigger_id,
view: {
type: 'modal',
callback_id: 'submit_timesheet',
title: {
type: 'plain_text',
text: 'Timesheet',
},
blocks: [
{
type: 'input',
block_id: 'timesheet_details',
element: {
type: 'plain_text_input',
multiline: true,
action_id: 'input_timesheet',
},
label: {
type: 'plain_text',
text: 'Enter your daily task details:',
},
},
],
submit: {
type: 'plain_text',
text: 'Submit',
},
},
})
res.sendStatus(200)
} catch (error) {
console.error('Error opening modal:', error)
res.status(500).send('Failed to open modal')
}
}
async function handleModalResponse(res, payload) {
if (!(await canUserSubmit(payload.user.id))) {
res.send({ response_action: 'clear' }) // Clears the modal
return
}
const userInput = payload.view.state.values.timesheet_details.input_timesheet.value
// Simulating posting to an endpoint
try {
console.log(`Timesheet input from user ${payload.user.id}:`, userInput)
console.log('Payload:', {
user: payload.user.id,
timesheet: userInput,
})
// insert data into timesheet table, get the column with created_at date
const [result] = await db.query('INSERT INTO timesheets (user_slack_id, task_details) VALUES (?, ?)', [payload.user.id, userInput])
const [row] = await db.query('SELECT * FROM timesheets WHERE id = ?', [result.insertId])
console.log('Row inserted:', row)
res.send({ response_action: 'clear' }) // Clears the modal
await web.chat.postMessage({
channel: payload.user.id,
text: `Thank you for submitting your timesheet! [id: ${row[0].id}, time: ${convertToKolkataTimezone(
row[0].created_at,
)}] And Your message is: \`\`\`${row[0].task_details}\`\`\``,
})
} catch (error) {
console.error('Error handling timesheet submission:', error)
res.status(500).send('Failed to handle timesheet submission')
}
}
async function sendUserReportsToAdmin() {
const [users] = await db.query(`select * from users where is_admin = true`)
if (users.length == 0) {
return
}
const [row] = await db.query(`
SELECT
users.*,
timesheets.id AS timesheet_id,
timesheets.task_details,
timesheets.created_at AS timesheet_created_at
FROM users
LEFT JOIN timesheets
ON
users.slack_id = timesheets.user_slack_id
AND DATE(timesheets.created_at) = CURDATE()
WHERE
users.is_active = 1
`)
const message = row
.map((r) => {
if (r.task_details) {
return '<@' + r.slack_id + '> ```' + r.task_details?.replaceAll('\\n', '\n') + '``` '
} else {
return '<@' + r.slack_id + '> `NOT FILLED TODAY`'
}
})
.join('\n')
for (let user of users) {
await web.chat.postMessage({
channel: user.slack_id,
text: message,
})
}
}
app.get('/send-reports', async (req, res) => {
try {
await sendUserReportsToAdmin()
res.send('Users Sheets sent successfully!')
} catch (error) {
console.error('user sheet sending error:', error)
res.status(500).send('Slack Failed to send user sheets')
}
})
async function canUserSubmit(userSlackId) {
if (new Date().getHours() >= 21) {
await web.chat.postMessage({
channel: userSlackId,
text: 'You cannot fill the timesheet, time exceeded, you can fill this till 9PM!',
})
return false
}
const [row] = await db.query(
`
SELECT timesheets.*
FROM timesheets
INNER JOIN users
ON users.slack_id = timesheets.user_slack_id
WHERE users.is_active = 1
AND timesheets.user_slack_id = ?
AND DATE(timesheets.created_at) = CURDATE();
`,
[userSlackId],
)
if (row.length > 0) {
await web.chat.postMessage({
channel: userSlackId,
text: `You already filled the timesheet, thankyou! [id: ${row[0].id}, time: ${convertToKolkataTimezone(
row[0].created_at,
)}]\n And Your message is: \`\`\`${row[0].task_details}\`\`\``,
})
return false
}
return true
}
const moment = require('moment-timezone')
function convertToKolkataTimezone(createdAt) {
console.log('createdAt', createdAt)
return moment.utc(createdAt).tz('Asia/Kolkata').format('YYYY-MM-DD HH:mm:ss')
}
// Start the server
app.listen(port, () => {
console.log(`Slack app listening at http://localhost:${port}`)
})
//RUNNING the main engine.
if (process.env.AWS_LAMBDA_FUNCTION_NAME) {
//lambda handling
const serverless = require('serverless-http')
const handler = serverless(app)
exports.handler = async (event, context, callback) => {
const response = handler(event, context, callback)
return response
}
} else {
// Run the cron job
const cron = require('node-cron')
cron.schedule('30 18 * * 1-5', sendReminderWithButton, { timezone: 'Asia/Kolkata' }) //6:30PM
cron.schedule('45 18 * * 1-5', sendReminderWithButton, { timezone: 'Asia/Kolkata' }) //6:45PM
cron.schedule('0 19 * * 1-5', sendReminderWithButton, { timezone: 'Asia/Kolkata' }) //7:00PM
cron.schedule('0 20 * * 1-5', sendReminderWithButton, { timezone: 'Asia/Kolkata' }) //8:00PM
cron.schedule('1 21 * * 1-5', sendUserReportsToAdmin, { timezone: 'Asia/Kolkata' }) //9:00PM
}