-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
395 lines (329 loc) · 9.43 KB
/
helpers.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
const { CommandInteraction, EmbedBuilder, UserSelectMenuInteraction } = require('discord.js');
const moment = require("moment");
const { GoogleSpreadsheet } = require("google-spreadsheet");
const client = require('./index');
const { logInfo, logError, logSuccess } = require("./helpers/log");
let roster;
let hr;
let trainings = [
{ name: 'Driving', key: 'DRIVING' },
{ name: 'Comms', key: 'COMMS' },
{ name: 'First Aid', key: 'FIRSTAID' },
{ name: 'Water', key: 'WATER' },
{ name: 'RTC', key: 'RTC' },
{ name: 'Tech Veh', key: 'TECHVEH' },
{ name: 'Fire Safety', key: 'FIRESAFETY' },
{ name: 'Co-Pilot', key: 'COPILOT' },
{ name: 'Pilot', key: 'PILOT' },
{ name: 'SC', key: 'SC' },
{ name: 'Dispatch', key: 'DISPATCH' },
{ name: 'FI', key: 'FI' },
{ name: 'S&R', key: 'S&R' },
{ name: 'Trainer', key: 'TRAINER' },
]
let rankColors = {
"Commissioner": 0xd80000,
"Deputy Commissioner": 0xe74c3c,
"Asst. Commissioner": 0xe74c3c,
"Area Manager": 0xad1457,
"Red Watch Manager": 0x1abc9c,
"Blue Watch Manager": 0x1abc9c,
"Crew Manager": 0x3498db,
"Lead Firefighter": 0x9b59b6,
"Advanced Firefighter": 0xe91e63,
"Firefighter": 0xf1c40f,
"Trainee Firefighter": 0xe67e22,
"Retained Firefighter": 0xe74c3c,
}
let rankRoles = {
"Commissioner": 1023688801966628891,
"Deputy Commissioner": "1023688801966628889",
"Asst. Commissioner": "1023688801966628888",
"Area Manager": "1023688801966628887",
"Red Watch Manager": "1023688801966628886",
"Blue Watch Manager": "1023688801966628885",
"Lead Firefighter": "1023688801945649171",
"Advanced Firefighter": "1023688801945649170",
"Firefighter": "1023688801945649169",
"Trainee Firefighter": "1023688801945649168",
"Retained Firefighter": "1023688801945649167",
"Red": "1064239790842728540",
"Blue": "1064239889928945736",
"Trainer": "1023688801916309623",
"LFB": "1023688801945649166",
}
let stations = [
{
name: "Rockford Drive (Main HQ)",
postal: "505",
map: "https://cdn.ninjalabs.dev/vGhIk.png"
},
{
name: "Seaview Road",
postal: "2018",
map: "https://cdn.ninjalabs.dev/LvT5F.png"
}
]
let units = [];
let _unitsLastUpdated = null;
authSheets();
setTimeout(() => {
updateUnits()
}, 5000);
// Sync units every 30 seconds
// setInterval(async () => {
// syncUnits()
// }, 1000 * process.env.UNIT_UPDATE_RATE)
function updateUnits() {
syncUnits()
}
async function syncUnits() {
let _units = [];
let mainRows = await roster.sheetsByTitle['Main Roster'].getRows();
mainRows.forEach((row, i) => {
if(row['First Name']) {
let unitTrainings = [];
trainings.forEach(training => {
unitTrainings.push({
name: training.name,
value: row[training.name],
key: training.key
});
})
_units.push({
row: i,
name: row['Full Name'],
isHR: row['HR'] === "TRUE",
isTrainer: row['Trainer'] === "TRUE",
callsign: row['Callsign'],
badge: row['Badge'],
rank: row['Rank'],
tenure: row['Tenure'],
nameBadge: row['Name and Badge'],
watch: row['Watch'],
training: unitTrainings,
hr: {
citizen: 'Unknown',
bank: 'Unknown',
contact: 'Unknown',
birth: 'Unknown',
photo: 'Unknown'
}
});
}
})
let trainingRows = await roster.sheetsByTitle['Training History'].getRows();
trainingRows.forEach(row => {
if(row['Unit']) {
let unit = _units.find(u => u.nameBadge === row['Unit'])
if(unit) {
unit.training.forEach(unitTraining => {
if (unitTraining.name === row['Training']) {
unitTraining.trainer = row['Trainer']
unitTraining.date = row['Training Date']
}
})
}
}
})
let hrRows = await hr.sheetsByTitle['Personnel Info'].getRows();
hrRows.forEach(row => {
if(row['Badge']) {
let unit = _units.find(u => u.badge === row['Badge'])
if(unit) {
unit.hr.citizen = row['Citizen ID'];
unit.hr.bank = row['Bank Account'];
unit.hr.contact = row['Contact Number'];
unit.hr.birth = row['DOB'];
unit.hr.photo = row['Photo'];
}
}
})
logInfo(`Updated units at: ${new Date().toISOString()}`)
units = _units;
_unitsLastUpdated = new Date();
}
async function getRowByValue(column, value, sheet = "Main Roster") {
let page = await roster.sheetsByTitle[sheet].getRows();
let row = null
page.forEach((r, rn) => {
if(r[column] === value) {
row = r;
console.log(`[INFO] Successfully found ${value} on row ${rn}`);
}
})
return [row, page];
}
async function getUnits() {
await syncUnits();
return units;
}
function unitsLastUpdated() {
return _unitsLastUpdated;
}
/**
* @param { CommandInteraction } interaction
*/
function getUserDisplayName(interaction) {
return `${interaction.user.username}#${interaction.user.discriminator} (${interaction.user.id})`
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* @param unit array
* @param training array
* @param interaction {CommandInteraction|UserSelectMenuInteraction}
*/
async function assignTraining(unit, training, interaction) {
let trainer = getUser(interaction.user.id, interaction);
if(!trainer) {
return interaction.editReply({
content: "There was an error doing this.",
ephemeral: true
})
}
let trainingSheet = await roster.sheetsByTitle['Training History']
let rows = await trainingSheet.getRows({
offset: 1
});
let rowNumber = 2;
let foundNumber = false
rows.forEach(row => {
if(!row['Unit'] && !foundNumber) {
rowNumber = row._rowNumber;
foundNumber = true
}
})
await trainingSheet.loadCells(`A${rowNumber}:F${rowNumber}`);
let _unit = trainingSheet.getCellByA1(`B${rowNumber}`);
_unit.value = `[${unit.badge}] ${unit.name}`;
let date = trainingSheet.getCellByA1(`C${rowNumber}`);
date.value = moment().format('DD/M/y');
let _trainer = trainingSheet.getCellByA1(`D${rowNumber}`);
_trainer.value = `[${trainer.badge}] ${trainer.name}`;
let _training = trainingSheet.getCellByA1(`E${rowNumber}`);
_training.value = training.name;
await trainingSheet.saveUpdatedCells();
}
/**
* @param unit array
* @param training array
* @param interaction {CommandInteraction|UserSelectMenuInteraction}
*/
async function removeTraining(unit, training, interaction) {
let rows = await roster.sheetsByTitle['Training History'].getRows({ offset: 1 });
rows.forEach(row => {
if(row['Unit'] === unit.nameBadge && row['Training'] === training.name) {
row['Unit'] = '';
row['Training Date'] = '';
row['Trainer'] = '';
row['Training'] = '';
row.save();
}
})
}
async function authSheets() {
const rosterCredentials = require('./lfb-bot-00cf901ff71c.json');
const rosterDoc = new GoogleSpreadsheet(process.env.SHEET_ID);
rosterDoc.useServiceAccountAuth(rosterCredentials).then(async () => {
roster = rosterDoc;
await roster.loadInfo();
const hrDoc = new GoogleSpreadsheet(process.env.HR_SHEET_ID);
hrDoc.useServiceAccountAuth(rosterCredentials).then(async () => {
hr = hrDoc;
await hr.loadInfo();
logSuccess(`Successfully connected to HR Sheet`)
return true;
}).catch(() => {
logError(`Unable to connect to HR Sheet`)
});
logSuccess(`Successfully connected to Roster Sheet`)
return true;
}).catch(() => {
logError(`Unable to connect to Roster Sheet`)
});
}
/**
* @param action string
* @param interaction {CommandInteraction}
*/
async function logAction(action, interaction) {
if(!process.env.LOG_CHANNEL) {
return console.log('[MAJOR] No log channel has been set!')
}
let channel = interaction.guild.channels.cache.get(process.env.LOG_CHANNEL);
if(!channel) {
return console.log("[MAJOR] Log channel is set but can't be found!");
}
let fields = [
{ name: 'User', value: interaction.member.displayName, inline: true },
{ name: 'Channel', value: '#' + interaction.channel.name, inline: true },
{ name: 'Action', value: action }
]
let logEmbed = new EmbedBuilder()
.setColor(0xe74c3c)
.setTitle('Action Log')
.addFields(fields)
.setTimestamp();
channel.send({
embeds: [logEmbed]
});
}
function getRosterData() {
return roster;
}
/**
* @param term string
* @param interaction { UserSelectMenuInteraction|CommandInteraction }
*/
function getUser(term, interaction) {
if(term.includes('-')) {
let callsign = term.toUpperCase();
let unit = units.find(u => u.callsign === callsign);
return unit ?? false;
}
if(term.length >= 18) {
let user = client.getDiscordUser(term, interaction.guild);
if(user) {
let _callsign = user.displayName?.match(/(?<=\[).+?(?=\])/g);
if(_callsign && _callsign.length) {
let unit = units.find(u => u.callsign === _callsign[0]);
return unit ?? false;
}
return false;
}
return false;
}
if(term.length === 3) {
let badge = term;
let unit = units.find(u => u.badge === badge);
return unit ?? false;
}
return false;
}
function hasTraining(user, trainingName) {
user.training.forEach(training => {
if(training.name === trainingName || training.key === trainingName) {
return true;
}
})
return false;
}
exports.getUser = getUser;
exports.getUserDisplayName = getUserDisplayName;
exports.rankColors = rankColors;
exports.getUnits = getUnits;
exports.syncUnits = syncUnits;
exports.unitsLastUpdated = unitsLastUpdated;
exports.trainings = trainings;
exports.capitalizeFirstLetter = capitalizeFirstLetter;
exports.updateUnits = updateUnits;
exports.assignTraining = assignTraining;
exports.removeTraining = removeTraining;
exports.logAction = logAction;
exports.getRosterData = getRosterData;
exports.getRowByValue = getRowByValue;
exports.stations = stations;
exports.hasTraining = hasTraining;
exports.rankRoles = rankRoles;