import wixData from 'wix-data';
import wixUsers from 'wix-users';
// Replace 'TimeLog' and 'Staff' with your actual collection IDs
const TIME_COLLECTION = 'TimeLog';
const STAFF_COLLECTION = 'Staff';
$w.onReady(function () {
// Get the current user's ID
const userId = wixUsers.currentUser.id;
// --- CLOCK IN FUNCTION ---
$w('#clockInButton').onClick(async () => {
if (!userId) {
console.error("User not logged in.");
return;
}
const now = new Date();
const today = now.toDateString(); // Get a date string for filtering
// 1. Check if the user has already clocked in today
let logQuery = await wixData.query(TIME_COLLECTION)
.eq('employeeLink', userId)
.eq('date', today)
.find();
if (logQuery.items.length > 0) {
$w('#statusText').text = "You have already clocked in today.";
return;
}
// 2. Insert new time entry
let newEntry = {
"employeeLink": userId,
"inTime": now,
"date": today // Store the date string for easy filtering
};
try {
await wixData.insert(TIME_COLLECTION, newEntry);
$w('#statusText').text = `Clocked In at: ${now.toLocaleTimeString()}`;
// Refresh dataset here to update the user's log history
$w('#timeLogDataset').refresh();
} catch (error) {
console.error("Error clocking in:", error);
$w('#statusText').text = "Error clocking in. Please try again.";
}
});
// --- CLOCK OUT FUNCTION ---
$w('#clockOutButton').onClick(async () => {
if (!userId) {
console.error("User not logged in.");
return;
}
const now = new Date();
const today = now.toDateString();
// 1. Find today's existing Clock In entry
let logQuery = await wixData.query(TIME_COLLECTION)
.eq('employeeLink', userId)
.eq('date', today)
.find();
if (logQuery.items.length === 0) {
$w('#statusText').text = "You must clock in before clocking out.";
return;
}
// 2. Update the existing entry with outTime
let existingEntry = logQuery.items[0];
// Check if already clocked out
if (existingEntry.outTime) {
$w('#statusText').text = "You have already clocked out for today.";
return;
}
existingEntry.outTime = now;
try {
await wixData.update(TIME_COLLECTION, existingEntry);
$w('#statusText').text = `Clocked Out at: ${now.toLocaleTimeString()}`;
// Refresh dataset to show the new time
$w('#timeLogDataset').refresh();
} catch (error) {
console.error("Error clocking out:", error);
$w('#statusText').text = "Error clocking out. Please try again.";
}
});
});