Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Mara Martini committed Dec 7, 2023
1 parent 48ebb08 commit 18cae9a
Show file tree
Hide file tree
Showing 8 changed files with 330 additions and 181 deletions.
14 changes: 14 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"cSpell.words": [
"CDRN",
"Jeudi",
"Lundi",
"Mercredi",
"mockdate",
"NEWWEEK",
"Semaine",
"Vendredi",
"vvxx",
"xxvv"
]
}
184 changes: 5 additions & 179 deletions bots/attendance/attendanceV2.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const { App } = require('@slack/bolt');
require('dotenv').config();
const { newWeek } = require('./newweek');
const { presences } = require('./presences');

const app = new App({
token: process.env.SLACK_BOT_TOKEN,
Expand All @@ -8,188 +10,12 @@ const app = new App({

app.start(process.env.PORT || 3000);

const userAttendances = [];
let emojiResponse = [];
const weekResponse = [];
const days = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi'];
const presenceValue = 'v';
const absenceValue = 'x';
const optionalValue = '?';

app.command('/attendance', async ({ ack, body, client }) => {
app.command('/presences', async ({ ack, body, client }) => {
await ack();

const userAttendance = normalizeUserAttendance(body.text);
const userId = body.user_id;

const userInfo = await client.users.info({
user: userId,
});

const userName = userInfo.user.profile.first_name;
const userLastName = userInfo.user.profile.last_name;

if (userAttendances[userId]) {
userAttendances[userId] = [];

if (emojiResponse.length > 0) {
emojiResponse = emojiResponse.filter((message) => !message.startsWith(`${userName} ${userLastName}`));
}
}

updateUserAttendance(userId, userAttendance);

const userResponse = generateEmojiResponse(userAttendance);

emojiResponse.push(`${userName} ${userLastName} : ${userResponse}`);

let allResponses = '';
for (const element of emojiResponse) {
allResponses += `${element}\n`;
}

const channelHistory = await client.conversations.history({
channel: 'C062C79CDRN',
});

for (const message of channelHistory.messages) {
if (message.ts) {
if (message.text && message.text.includes('[NEWWEEK]')) {
continue;
}

await client.chat.delete({
channel: 'C062C79CDRN',
ts: message.ts,
});
}
}

const message = `${allResponses}`;
const weekResponseText = generateWeekResponse();
await client.chat.postMessage({
channel: 'C062C79CDRN',
text: `${message}\n${weekResponseText}`,
});
await presences(body, client);
});

app.command('/newweek', async ({ ack, client }) => {
await ack();

const formattedStartDate = formatDate(nextMonday);
const formattedEndDate = formatDate(nextFriday);
// const formattedStartDate = nextMonday.toLocaleDateString('fr-FR', {
// day: 'numeric',
// month: 'numeric',
// year: 'numeric',
// });

// const formattedEndDate = nextFriday.toLocaleDateString('fr-FR', {
// day: 'numeric',
// month: 'numeric',
// year: 'numeric',
// });

const weekMessage = `Semaine du ${formattedStartDate} au ${formattedEndDate} [NEWWEEK]`;

await client.chat.postMessage({
channel: 'C062C79CDRN',
text: weekMessage,
});
await newWeek(client);
});

const today = new Date();
const nextMonday = new Date(today);
nextMonday.setDate(today.getDate() + ((8 - today.getDay()) % 7));
const nextFriday = new Date(nextMonday);
nextFriday.setDate(nextMonday.getDate() + 4);
function formatDate(date) {
return date.toLocaleDateString('fr-FR', {
day: 'numeric',
month: 'numeric',
year: 'numeric',
});
}

for (const day of days) {
weekResponse[day] = 0;
}

function updateUserAttendance(userId, textAfterCommand) {
if (!userAttendances[userId]) {
userAttendances[userId] = [];
}

userAttendances[userId].push(textAfterCommand);
}

function generateEmojiResponse(textAfterCommand) {
const emojiArray = [];

for (const char of textAfterCommand) {
if (char === presenceValue) {
emojiArray.push('✅');
} else if (char === absenceValue) {
emojiArray.push('❌');
} else {
emojiArray.push('❓');
}
}
return emojiArray.join('');
}

function generateWeekResponseString(day, presenceCount, optionalCount) {
let response = `${day}: ${presenceCount}`;
if (optionalCount) {
response += ` (ou `;
if (optionalCount > 1) {
response += ' ';
}
response += `${presenceCount + optionalCount}`;
response += ')';
}
return response;
}

function generateWeekResponse() {
for (const day of days) {
weekResponse[day] = { presenceCount: 0, optionalCount: 0 };
}

for (const userId of Object.keys(userAttendances)) {
const userAttendance = userAttendances[userId];
for (const [index, day] of days.entries()) {
for (const attendance of userAttendance) {
switch (attendance[index]) {
case presenceValue: {
weekResponse[day].presenceCount++;
break;
}
case '?': {
weekResponse[day].optionalCount++;
break;
}
}
}
}
}
const weekResponseArray = days.map((day) => {
return generateWeekResponseString(day, weekResponse[day].presenceCount, weekResponse[day].optionalCount);
});

return weekResponseArray.join('\n');
}

function normalizeUserAttendance(value) {
let result = '';
for (const dayAttendance of value) {
if (dayAttendance === 'v' || dayAttendance === 'V' || dayAttendance === '1') {
result += presenceValue;
} else if (dayAttendance === 'x' || dayAttendance === 'X' || dayAttendance === '0') {
result += absenceValue;
} else {
result += optionalValue;
}
}
return result;
}
44 changes: 44 additions & 0 deletions bots/attendance/newweek.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
async function newWeek(client) {
const today = new Date();
const weekDay = today.toLocaleString('en-us', { weekday: 'long' });
let mondayDate;

// eslint-disable-next-line unicorn/prefer-switch
if (weekDay === 'Monday') {
mondayDate = today;
} else if (weekDay === 'Tuesday') {
mondayDate = new Date();
mondayDate.setDate(mondayDate.getDate() - 1);
} else if (weekDay === 'Wednesday') {
mondayDate = new Date();
mondayDate.setDate(mondayDate.getDate() - 2);
} else if (weekDay === 'Thursday') {
mondayDate = new Date();
mondayDate.setDate(mondayDate.getDate() - 3);
} else if (weekDay === 'Friday' || weekDay === 'Saturday' || weekDay === 'Sunday') {
mondayDate = new Date();
mondayDate.setDate(mondayDate.getDate() + ((8 - today.getDay()) % 7));
}

const nextFriday = new Date(mondayDate);
nextFriday.setDate(mondayDate.getDate() + 4);
const formattedStartDate = formatDate(mondayDate);
const formattedEndDate = formatDate(nextFriday);
const weekMessage = `Semaine du ${formattedStartDate} au ${formattedEndDate} [NEWWEEK]`;

await client.chat.postMessage({
channel: process.env.SLACK_CHANNEL,
text: weekMessage,
});
return weekMessage;
}

function formatDate(date) {
return date.toLocaleDateString('fr-FR', {
day: 'numeric',
month: 'numeric',
year: 'numeric',
});
}

module.exports = { newWeek };
60 changes: 60 additions & 0 deletions bots/attendance/newweek.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const { newWeek } = require('./newweek');
const MockDate = require('mockdate');
const fakeClient = {
chat: {
postMessage: () => {
/*nothing to do*/
},
},
};

const currentWeekMessage = 'Semaine du 04/12/2023 au 08/12/2023 [NEWWEEK]';
const nextWeekMessage = 'Semaine du 11/12/2023 au 15/12/2023 [NEWWEEK]';

test('Test today is tuesday', async () => {
MockDate.set('2023-12-05');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(currentWeekMessage);
});

test('Test today is wednesday', async () => {
MockDate.set('2023-12-06');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(currentWeekMessage);
});

test('Test today is monday', async () => {
MockDate.set('2023-12-04');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(currentWeekMessage);
});

test('Test today is thursday', async () => {
MockDate.set('2023-12-07');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(currentWeekMessage);
});

test('Test today is friday', async () => {
MockDate.set('2023-12-08');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(nextWeekMessage);
});

test('Test today is saturday', async () => {
MockDate.set('2023-12-09');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(nextWeekMessage);
});

test('Test today is sunday', async () => {
MockDate.set('2023-12-10');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(nextWeekMessage);
});

test('Test today is monday', async () => {
MockDate.set('2023-12-11');
const weekMessage = await newWeek(fakeClient);
expect(weekMessage).toBe(nextWeekMessage);
});
Loading

0 comments on commit 18cae9a

Please sign in to comment.