34387-vm/assets/js/main.js
2025-09-25 15:14:38 +00:00

93 lines
3.2 KiB
JavaScript

document.addEventListener('DOMContentLoaded', function () {
const timeElement = document.getElementById('current-time');
const statusMessage = document.getElementById('status-message');
const clockInButton = document.getElementById('clock-in-btn');
const clockOutButton = document.getElementById('clock-out-btn');
function updateTime() {
const now = new Date();
timeElement.textContent = now.toLocaleTimeString('es-ES');
}
setInterval(updateTime, 1000);
updateTime();
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.classList.add('show');
}, 100);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => {
document.body.removeChild(toast);
}, 300);
}, 3000);
}
async function handleClockAction(action) {
clockInButton.disabled = true;
clockOutButton.disabled = true;
try {
const response = await fetch('api/track_time.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ action: action, employee_id: 1 }) // Hardcoded employee_id
});
const result = await response.json();
if (result.success) {
showToast(result.message);
statusMessage.textContent = result.status;
if (result.action === 'clock_in') {
clockOutButton.disabled = false;
} else {
clockInButton.disabled = false;
}
} else {
showToast(result.message, 'error');
// Re-enable buttons based on assumed last state if error
if(action === 'clock_in') clockInButton.disabled = false; else clockOutButton.disabled = false;
}
} catch (error) {
showToast('Error de conexión con el servidor.', 'error');
if(action === 'clock_in') clockInButton.disabled = false; else clockOutButton.disabled = false;
}
}
clockInButton.addEventListener('click', () => handleClockAction('clock_in'));
clockOutButton.addEventListener('click', () => handleClockAction('clock_out'));
// Initial state check
async function checkInitialState() {
try {
const response = await fetch('api/track_time.php?employee_id=1');
const result = await response.json();
if(result.status) {
statusMessage.textContent = result.status;
if(result.last_action === 'clock_in'){
clockInButton.disabled = true;
clockOutButton.disabled = false;
} else {
clockInButton.disabled = false;
clockOutButton.disabled = true;
}
}
} catch(e) {
// assume default state
clockOutButton.disabled = true;
}
}
checkInitialState();
});