Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 20 additions & 25 deletions nodejs-functions/src/handlers/automatic-clock-outs/clock_out.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
const _ = require("lodash");
const CosmosClient = require("@azure/cosmos").CosmosClient;
const config = require("./config");
const TimeEntry = require("./time_entry");
const MsalClient = require("./msal_client");
const TimeEntryDao = require("./time_entry_dao");
const SlackClient = require("./slack_client");
const { CLOCK_OUT_MESSAGE, CLOCK_OUT_MESSAGE_MIDNIGHT } = require("./constants");
const _ = require('lodash');
const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('./config');
const TimeEntry = require('./time_entry');
const MsalClient = require('./msal_client');
const TimeEntryDao = require('./time_entry_dao');
const SlackClient = require('./slack_client');
const { CLOCK_OUT_MESSAGE, CLOCK_OUT_MESSAGE_MIDNIGHT } = require('./constants');

const doClockOut = async (context) => {
context.log(
`I am going to check how many entries were not clocked out ${new Date()}`
);
context.log(`I am going to check how many entries were not clocked out ${new Date()}`);

const { endpoint, key, databaseId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);
const container = database.container("time_entry");
const container = database.container('time_entry');
const timeEntryDao = new TimeEntryDao(database);

const response = await MsalClient.findUsersInMS();
const users = response.data.value;
const users = response.data;
const slackUsers = await SlackClient.findUsersInSlack();

const { resources: entries } = await timeEntryDao.getEntriesWithNoEndDate();
Expand All @@ -30,7 +28,7 @@ const doClockOut = async (context) => {
await Promise.all(
entries.map(async (timeEntryAsJson) => {
const timeEntry = new TimeEntry(timeEntryAsJson);
const { userName, userEmail } = findUserData(users, timeEntry.timeEntry.owner_id);
const { userName, userEmail } = findUserData( users, timeEntry.timeEntry.owner_id);
const userId = findSlackUserId(slackUsers, userEmail);

if (timeEntry.needsToBeClockedOut()) {
Expand All @@ -40,11 +38,10 @@ const doClockOut = async (context) => {
timeEntryAsJson.end_date = timeEntry.getTimeToClockOut();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
totalClockOutsExecuted++;
}

else if (timeEntry.needsToBeClockedOutMidnight()) {

} else if (timeEntry.needsToBeClockedOutMidnight()) {
if (userId) {
SlackClient.sendMessageToUser(userId, CLOCK_OUT_MESSAGE_MIDNIGHT.replace('%user_name%', userName));
SlackClient.sendMessageToUser(userId,CLOCK_OUT_MESSAGE_MIDNIGHT.replace('%user_name%', userName));
}
timeEntryAsJson.end_date = timeEntry.getTimeToClockOutMidnight();
await container.item(timeEntryAsJson.id, timeEntryAsJson.tenant_id).replace(timeEntryAsJson);
Expand All @@ -53,19 +50,17 @@ const doClockOut = async (context) => {
})
);

context.log(
`I just clocked out ${totalClockOutsExecuted} entries, thanks are not needed...`
);
context.log(`I just clocked out ${totalClockOutsExecuted} entries, thanks are not needed...`);
};

const findUserData = (users, id) => {
const user = users.find((user) => user.objectId === id);
return user ? { userName: user.displayName.split(" ")[0], userEmail: _.first(user.otherMails) } : {};
const targetUser = users.find((user) => user.id === id);
return targetUser ? { userName: targetUser.name.split(' ')[0], userEmail: targetUser.email } : {};
};

const findSlackUserId = (slackUsers, email) => {
const user = slackUsers.find((slackUser) => slackUser.email === email);
return user ? user.id : null;
const slackTargetUser = slackUsers.find((slackUser) => slackUser.email === email);
return slackTargetUser ? slackTargetUser.id : null;
};

module.exports = { doClockOut };
5 changes: 4 additions & 1 deletion nodejs-functions/src/handlers/automatic-clock-outs/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ const config = {
clientId: process.env["CLIENT_ID"],
authority: process.env["AUTHORITY"],
clientSecret: process.env["CLIENT_SECRET"],
slackApiToken: process.env["SLACK_TOKEN_NOTIFY"]
slackApiToken: process.env["SLACK_TOKEN_NOTIFY"],
userNameMS: process.env["USER_NAME_MS"],
userPasswordMS: process.env["USER_PASSWORD_MS"]

};

module.exports = config;
71 changes: 45 additions & 26 deletions nodejs-functions/src/handlers/automatic-clock-outs/msal_client.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
const axios = require("axios")
const msal = require('@azure/msal-node');
const config = require("./config");

const findUsersInMS = async() => {
const {clientId, authority, clientSecret} = config;
const endpoint = 'https://graph.windows.net/ioetec.onmicrosoft.com'
const configuration = {
auth: {
clientId: clientId,
authority: authority,
clientSecret: clientSecret
}
};

const cca = new msal.ConfidentialClientApplication(configuration);
const clientCredentialRequest = {
scopes: ['https://graph.windows.net/.default'],
};
const response = await cca.acquireTokenByClientCredential(clientCredentialRequest)
const token = response.accessToken
return axios.get(`${endpoint}/users?api-version=1.6&$select=displayName,otherMails,objectId`,
{ 'headers': { 'Authorization': token } })
}

module.exports = { findUsersInMS };
const axios = require('axios');
const config = require('./config');

const getToken = async () => {
const { clientId, userNameMS, userPasswordMS } = config;
const endpoint =
'https://ioetec.b2clogin.com/ioetec.onmicrosoft.com/B2C_1_accesstoken/oauth2/v2.0/token';

const params = new URLSearchParams();

params.append('username', userNameMS);
params.append('password', userPasswordMS);
params.append('grant_type', 'password');
params.append('scope', clientId);
params.append('client_id', clientId);
params.append('response_type', 'token');

const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};

return axios.post(endpoint, params, headers)
.then((result) => {
return result.data.access_token;
})
.catch((err) => {
console.log(`Invalid request to: ${endpoint}`);
});
};

const findUsersInMS = async () => {
const endpoint = 'https://timetracker-api.azurewebsites.net/';
const token = await getToken();

const headers = {
headers: {
Authorization: `Bearer ${token}`,
},
};

return axios.get(`${endpoint}/users`, headers);
};

module.exports = { findUsersInMS };
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const moment = require("moment")
const moment = require('moment')

class TimeEntry {

Expand All @@ -15,7 +15,7 @@ class TimeEntry {
}

getMidnightInTimeEntryZone(){
return moment(this.timeEntry.start_date).utcOffset(this.timeEntry.timezone_offset * -1).endOf('day');
return moment(this.timeEntry.start_date).utc().subtract(this.timeEntry.timezone_offset, 'minutes').endOf('day')
}

getTimeToClockOutMidnight(){
Expand Down