Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Henrique Sagara authored and Henrique Sagara committed Mar 11, 2024
1 parent 7229166 commit 43c30e6
Show file tree
Hide file tree
Showing 5 changed files with 186 additions and 82 deletions.
Binary file modified .DS_Store
Binary file not shown.
56 changes: 45 additions & 11 deletions modules/data-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,14 @@ async function checkLastShift(client, userId){
const result = await client.db(dbName).collection(collectionName).findOne(user, projection);
const workedDaysArray = result.workedDays;
const index = workedDaysArray.length - 1;
const endTime = result.workedDays[index].shift.timeOutNum;
//const endTime = result.workedDays[index].shift.timeOutNum;

console.log(endTime)

return endTime;
return result.workedDays[index].shift;
}


async function timeIn(client, userId) {
const currentDate = new Date();
const day = currentDate.toLocaleDateString('en-US')
const timeIn = currentDate.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: false });
const timeInNum = currentDate.getTime();

const user = {_id: userId};
Expand All @@ -45,8 +41,6 @@ async function timeIn(client, userId) {
workedDays: {
shift: {
fullDateIn: currentDate,
date: day,
timeIn: timeIn,
timeInNum: timeInNum,
}
}
Expand All @@ -56,16 +50,52 @@ async function timeIn(client, userId) {
await client.db(dbName).collection(collectionName).updateOne(user, update)
}

async function breakIn(client, userId) {
const currentDate = new Date();
const breakInNum = currentDate.getTime();
const user = {_id: userId};

const update = {
$push: {
workedDays: {
shift: {
fullBreakIn: currentDate,
breakInNum: breakInNum,
}
}
}
}

await client.db(dbName).collection(collectionName).updateOne(user, update)
}

async function breakOut(client, userId){
const currentDate = new Date();
const breakOutNum = currentDate.getTime();
const user = {_id: userId};

const update = {
$push: {
workedDays: {
shift: {
fullBreakOut: currentDate,
breakOutNum: breakOutNum,
}
}
}
}

await client.db(dbName).collection(collectionName).updateOne(user, update)
}

async function timeOut(client, userId) {
const currentDate = new Date();
const timeOut = currentDate.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: false });
const timeOutNum = currentDate.getTime();

const user = { _id: userId };
const update = {
$set: {
'workedDays.$[day].shift.fullDateOut': currentDate,
'workedDays.$[day].shift.timeOut': timeOut,
'workedDays.$[day].shift.timeOutNum': timeOutNum,
},
};
Expand Down Expand Up @@ -131,12 +161,16 @@ async function deleteUserById(client, userId) {
}
}



export {
timeIn,
timeOut,
calculateWorkedHours,
addNewUser,
queryAllRecords,
deleteUserById,
checkLastShift
checkLastShift,
breakIn,
breakOut
};
Empty file removed modules/user.js
Empty file.
168 changes: 112 additions & 56 deletions public/jsForPages/shiftTracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,21 @@ document.addEventListener("DOMContentLoaded", function () {
let totalBreakDuration = 0; // Variable to track total break duration
let isBreakActive = false;
// Event handler for the "Time In" button click
document.getElementById("timeInBtn").onclick = function () {
if (!isTimeInClicked) {
// Get the current time
startTime = new Date();

// Format the time as HH:mm:ss
formattedTime = startTime.toLocaleTimeString();
document.getElementById("timeInTime").innerHTML = `Your shift started at :${formattedTime}`;
shift = true;
isTimeInClicked = true;
}
};
// document.getElementById("timeInBtn").onclick = function () {
// if (!isTimeInClicked) {
// // Get the current time
// startTime = new Date();

// // Format the time as HH:mm:ss
// formattedTime = startTime.toLocaleTimeString();
// document.getElementById("timeInTime").innerHTML = `Your shift started at :${formattedTime}`;
// shift = true;
// isTimeInClicked = true;
// }
// };

// Event handler for the "Time Out" button click
document.getElementById("timeOutBtn").onclick = function () {
// document.getElementById("timeOutBtn").onclick = function () {
// if (shift) {
// isTimeOutClicked = true;

Expand All @@ -64,41 +64,41 @@ document.addEventListener("DOMContentLoaded", function () {

// twilio API for sending sms messages

console.log('Sending confirmation message...');
const accountSid = 'AC76be89cce69a7705839035004025d6eb';
const authToken = '3b3743d083ccc4b19fbdf18f49473cd6';
const twilioPhoneNumber = '+15168149425';
const recipientPhoneNumber = '+';

const message = 'Your shift has ended.';

fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(`${accountSid}:${authToken}`)
},
body: new URLSearchParams({
'To': recipientPhoneNumber,
'From': twilioPhoneNumber,
'Body': message
})
})
.then(response => {
if (response.ok) {
console.log('Message sent successfully.');
// Handle success
} else {
console.error('Failed to send message:', response.status, response.statusText);
response.text().then(errorMessage => console.error('Error details:', errorMessage));
// Handle error
}
})
.catch(error => {
console.error('Error:', error);
});

};
// console.log('Sending confirmation message...');
// const accountSid = 'AC76be89cce69a7705839035004025d6eb';
// const authToken = '3b3743d083ccc4b19fbdf18f49473cd6';
// const twilioPhoneNumber = '+15168149425';
// const recipientPhoneNumber = '+';

// const message = 'Your shift has ended.';

// fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Authorization': 'Basic ' + btoa(`${accountSid}:${authToken}`)
// },
// body: new URLSearchParams({
// 'To': recipientPhoneNumber,
// 'From': twilioPhoneNumber,
// 'Body': message
// })
// })
// .then(response => {
// if (response.ok) {
// console.log('Message sent successfully.');
// // Handle success
// } else {
// console.error('Failed to send message:', response.status, response.statusText);
// response.text().then(errorMessage => console.error('Error details:', errorMessage));
// // Handle error
// }
// })
// .catch(error => {
// console.error('Error:', error);
// });

// };

// Get the break button element
const breakButton = document.getElementById("break");
Expand Down Expand Up @@ -148,17 +148,17 @@ document.addEventListener("DOMContentLoaded", function () {
}

// Function to calculate total worked hours
function totalHourCalculator(startTime, endTime, totalBreakDuration) {
const time1InSeconds = startTime.getTime() / 1000;
const time2InSeconds = endTime.getTime() / 1000;
// function totalHourCalculator(startTime, endTime, totalBreakDuration) {
// const time1InSeconds = startTime.getTime() / 1000;
// const time2InSeconds = endTime.getTime() / 1000;

let totalHours = (time2InSeconds - time1InSeconds) / 3600;
// let totalHours = (time2InSeconds - time1InSeconds) / 3600;

// Deduct total break duration from the total hours
totalHours -= totalBreakDuration / 60;
// // Deduct total break duration from the total hours
// totalHours -= totalBreakDuration / 60;

return { totalHours: totalHours.toFixed(2), breakDuration: totalBreakDuration };
}
// return { totalHours: totalHours.toFixed(2), breakDuration: totalBreakDuration };
// }

});

Expand Down Expand Up @@ -230,4 +230,60 @@ document.getElementById("timeOutBtn").addEventListener("click", async () => {
}
});

document.getElementById("break").addEventListener("click", async () => {
try {
const response = await fetch("/break-in", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({userId: 1}),
});

if(response.ok) {
const data = await response.json();
console.log(data.message);
breakInTime = new Date();

formattedTime = breakInTime.toLocaleTimeString();
document.getElementById("break").innerHTML = `Your break has started at :${formattedTime}`
} else{
const errorData = await response.json();
if(errorData.message) {
alert(errorData.message);
}
console.error("Error recording break-in", errorData.message);
}
} catch (error){
console.error(error)
}
});

document.getElementById("break").addEventListener("click", async () => {
try {
const response = await fetch("/break-in", {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({userId: 1}),
});

if(response.ok) {
const data = await response.json();
console.log(data.message);
breakInTime = new Date();

formattedTime = breakInTime.toLocaleTimeString();
document.getElementById("break").innerHTML = `Your break has started at :${formattedTime}`
} else{
const errorData = await response.json();
if(errorData.message) {
alert(errorData.message);
}
console.error("Error recording break-in", errorData.message);
}
} catch (error){
console.error(error)
}
});
44 changes: 29 additions & 15 deletions routes/root.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from "path";
import bodyParser from "body-parser";
import bcrypt from 'bcrypt';
import { client, authenticateUser } from "../modules/database.js";
import { deleteUserById, addNewUser, timeIn, timeOut, checkLastShift} from "../modules/data-service.js";
import { deleteUserById, addNewUser, timeIn, timeOut, checkLastShift, breakIn, breakOut} from "../modules/data-service.js";
import { createUser, getUserByEmail, getUserByName, getUserBySin } from "../modules/data-service-auth.js";


Expand All @@ -17,10 +17,8 @@ router.post("/time-in", authenticateUser, async (req, res) => {
// const userId = req.body.userId;
const userId = req.session.user.id

console.log(userId)

const shiftCheck = await checkLastShift(client, userId)
if (shiftCheck === undefined) {
const lastShift = await checkLastShift(client, userId)
if (lastShift.workedHours === undefined) {
return res.status(400).json({ message: "Previous shift time-out hasn't been recorded" });
}

Expand All @@ -34,20 +32,40 @@ router.post("/time-in", authenticateUser, async (req, res) => {
});


router.get("/time-in", authenticateUser, (req, res) => {
res.sendFile(path.resolve(currentDir, 'views', 'time-in.html'));
});
router.post("/break-in", authenticateUser, async (req, res) => {
const userId = req.session.user.id;

// const shiftCheck = await checkLastShift(client, userId);
const lastShift = await checkLastShift(client, userId);
if(lastShift.timeInNum != undefined && lastShift.workedHours != undefined){
return res.status(400).json({ message: "You haven't started a shift yet." });
}

try{
await breakIn(client, userId);
res.status(200).json({message: "Break-in recorded successfully"});
} catch (error) {
console.log(error);
res.status(500).json({ message: "Internal Server Error" });
}

})



router.post("/time-out", authenticateUser, async (req, res) => {
const userId = req.session.user.id;

const shiftCheck = await checkLastShift(client, userId)
if (shiftCheck != undefined) {
const lastShift = await checkLastShift(client, userId)
console.log(lastShift)
if (lastShift.timeInNum === undefined) {
return res.status(400).json({ message: "You haven't started a shift yet." });
}
else if(lastShift.breakInNum != undefined && lastShift.breakOutNum === undefined){
return res.status(400).json({ message: "You didn't finish your break. Time-out anyway?" });
}

try {

await timeOut(client, userId);
res.status(200).json({message: "Time-out recorded successfully"})
} catch (e) {
Expand All @@ -56,10 +74,6 @@ router.post("/time-out", authenticateUser, async (req, res) => {
}
});

router.get("/time-out", authenticateUser, (req, res) => {
res.sendFile(path.resolve(currentDir, 'views', 'time-out.html'))
})

// Route to handle creating a new user
router.post("/create-user", async (req, res) => {

Expand Down

0 comments on commit 43c30e6

Please sign in to comment.