-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
213 lines (181 loc) · 5.97 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
const { App, ExpressReceiver } = require("@slack/bolt");
const ExcelJS = require("exceljs");
require("dotenv").config();
const fs = require("fs");
const { google } = require("googleapis");
const apikeys = require("./apikey.json");
const moment = require("moment-timezone");
// Authorize with Google
const SCOPE = ["https://www.googleapis.com/auth/drive"];
const authorizeGoogleConnection = async () => {
const jwtClient = new google.auth.JWT(apikeys.client_email, null, apikeys.private_key, SCOPE);
await jwtClient.authorize();
return jwtClient;
};
const uploadFile = async (authClient) => {
return new Promise(async (resolve, reject) => {
const drive = google.drive({ version: "v3", auth: authClient });
const fileName = "employees_attendance.xlsx";
const folderId = process.env.FOLDER_ID;
let fileId = null;
const fileMetaData = {
name: fileName,
parents: [folderId],
};
try {
const searchResponse = await drive.files.list({
q: `name='${fileName}' and '${folderId}' in parents`,
fields: "files(id, name)",
spaces: "drive",
});
if (searchResponse.data.files.length > 0) {
fileId = searchResponse.data.files[0].id;
}
} catch (error) {
return reject("Error searching for file: " + error.message);
}
const media = {
body: fs.createReadStream(fileName),
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
try {
if (fileId) {
const updateResponse = await drive.files.update({
fileId: fileId,
media: media,
});
resolve(updateResponse.data);
} else {
const createResponse = await drive.files.create({
resource: fileMetaData,
media: media,
fields: "id",
});
resolve(createResponse.data);
}
} catch (error) {
reject("Error uploading file: " + error.message);
}
});
};
const receiver = new ExpressReceiver({
signingSecret: process.env.SIGNING_SECRET,
});
const app = new App({
token: process.env.SLACK_TOKEN,
receiver,
});
const employees = {
Afaq: {},
Ammar: {},
Nouman: {},
Aalee: {},
Hadi: {},
};
// Mapping between Slack usernames and employee names in the employees object
const userMapping = {
"afaq.codrivity": "Afaq",
afaqatofficial: "Ammar",
mughalfasih75: "Nouman",
aalee_username: "Aalee", // Update with the actual Slack username
hadi_username: "Hadi", // Update with the actual Slack username
};
app.message(async ({ message, context }) => {
const userId = message.user;
const text = message.text.toLowerCase();
const timestamp = parseFloat(message.ts);
const messageTime = moment(timestamp * 1000)
.tz("Asia/Karachi")
.format("hh:mm:ss A");
const currentDate = moment(timestamp * 1000)
.tz("Asia/Karachi")
.format("YYYY-MM-DD");
try {
const userInfo = await app.client.users.info({
token: context.botToken,
user: userId,
});
const userName = userInfo.user.name;
console.log("user:",userId)
console.log("message:", text);
const employeeName = userMapping[userName]; // Map the username to the employee name
if (employeeName) {
if (!employees[employeeName][currentDate]) {
employees[employeeName][currentDate] = {
"In Time": "",
"Out Time": "",
"Break Start": "",
"Break End": "",
};
}
if (["in", "reached", "online"].includes(text)) {
employees[employeeName][currentDate]["In Time"] = messageTime;
}
if (["out", "leaving", "left", "offline"].includes(text)) {
employees[employeeName][currentDate]["Out Time"] = messageTime;
}
if (["break start", "taking break"].includes(text)) {
employees[employeeName][currentDate]["Break Start"] = messageTime;
}
if (["break end", "back from break"].includes(text)) {
employees[employeeName][currentDate]["Break End"] = messageTime;
}
await updateExcelFile();
} else {
console.warn(`No mapping found for user: ${userName}`);
}
} catch (error) {
console.error("Error handling message:", error);
}
});
async function updateExcelFile() {
const filePath = "employees_attendance.xlsx";
const workbook = new ExcelJS.Workbook();
if (fs.existsSync(filePath)) {
await workbook.xlsx.readFile(filePath);
} else {
workbook.addWorksheet("Attendance");
}
const worksheet = workbook.getWorksheet("Attendance");
worksheet.columns = [
{ header: "Employee", key: "employee", width: 20 },
{ header: "Date", key: "date", width: 15 },
{ header: "In Time", key: "inTime", width: 30 },
{ header: "Out Time", key: "outTime", width: 30 },
{ header: "Break Start", key: "breakStart", width: 30 },
{ header: "Break End", key: "breakEnd", width: 30 },
];
for (const [employee, dates] of Object.entries(employees)) {
for (const [date, times] of Object.entries(dates)) {
let rowFound = false;
worksheet.eachRow({ includeEmpty: true }, (row) => {
if (row.getCell("employee").value === employee && row.getCell("date").value === date) {
row.getCell("inTime").value = times["In Time"];
row.getCell("outTime").value = times["Out Time"];
row.getCell("breakStart").value = times["Break Start"];
row.getCell("breakEnd").value = times["Break End"];
rowFound = true;
}
});
if (!rowFound) {
worksheet.addRow({
employee,
date,
inTime: times["In Time"],
outTime: times["Out Time"],
breakStart: times["Break Start"],
breakEnd: times["Break End"],
});
}
}
}
await workbook.xlsx.writeFile(filePath);
authorizeGoogleConnection().then(uploadFile).catch(console.error);
}
receiver.router.get("/status", (req, res) => {
res.status(200).send("Server is running!");
});
(async () => {
await app.start(process.env.PORT);
console.log("⚡️ Slack Bolt app is running!");
})();