diff --git a/.DS_Store b/.DS_Store index d7dbeb01..bacb21e3 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/modules/data-service.js b/modules/data-service.js index 11433cf5..d31a0541 100644 --- a/modules/data-service.js +++ b/modules/data-service.js @@ -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}; @@ -45,8 +41,6 @@ async function timeIn(client, userId) { workedDays: { shift: { fullDateIn: currentDate, - date: day, - timeIn: timeIn, timeInNum: timeInNum, } } @@ -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, }, }; @@ -131,6 +161,8 @@ async function deleteUserById(client, userId) { } } + + export { timeIn, timeOut, @@ -138,5 +170,7 @@ export { addNewUser, queryAllRecords, deleteUserById, - checkLastShift + checkLastShift, + breakIn, + breakOut }; \ No newline at end of file diff --git a/modules/user.js b/modules/user.js deleted file mode 100644 index e69de29b..00000000 diff --git a/public/jsForPages/shiftTracker.js b/public/jsForPages/shiftTracker.js index 1c773bb8..227611ee 100644 --- a/public/jsForPages/shiftTracker.js +++ b/public/jsForPages/shiftTracker.js @@ -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; @@ -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"); @@ -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 }; + // } }); @@ -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) + } +}); \ No newline at end of file diff --git a/routes/root.js b/routes/root.js index c7c993af..d5d7182b 100644 --- a/routes/root.js +++ b/routes/root.js @@ -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"; @@ -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" }); } @@ -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) { @@ -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) => {