keronblackdev's picture
create the login page
8304476 verified
Raw History Blame Contribute Delete
9.54 kB
// Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
// Initialize IndexedDB
function initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('LodgeMasterDB', 1);
request.onerror = (event) => {
console.error('Database error:', event.target.error);
reject(event.target.error);
};
request.onsuccess = (event) => {
const db = event.target.result;
resolve(db);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object stores
if (!db.objectStoreNames.contains('bookings')) {
const bookingsStore = db.createObjectStore('bookings', { keyPath: 'id', autoIncrement: true });
bookingsStore.createIndex('roomNumber', 'roomNumber', { unique: false });
bookingsStore.createIndex('status', 'status', { unique: false });
}
if (!db.objectStoreNames.contains('payments')) {
const paymentsStore = db.createObjectStore('payments', { keyPath: 'id', autoIncrement: true });
paymentsStore.createIndex('bookingId', 'bookingId', { unique: false });
paymentsStore.createIndex('date', 'date', { unique: false });
}
if (!db.objectStoreNames.contains('rooms')) {
db.createObjectStore('rooms', { keyPath: 'number' });
}
if (!db.objectStoreNames.contains('settings')) {
db.createObjectStore('settings', { keyPath: 'key' });
}
};
});
}
// Check online status
function checkOnlineStatus() {
if (!navigator.onLine) {
showOfflineAlert();
}
window.addEventListener('online', () => {
hideOfflineAlert();
syncData();
});
window.addEventListener('offline', showOfflineAlert);
}
function showOfflineAlert() {
const alert = document.createElement('div');
alert.className = 'fixed bottom-4 left-4 bg-yellow-500 text-white px-4 py-2 rounded-md shadow-md z-50';
alert.id = 'offline-alert';
alert.innerHTML = '⚠️ You are currently offline. Changes will be synced when you reconnect.';
document.body.appendChild(alert);
}
function hideOfflineAlert() {
const alert = document.getElementById('offline-alert');
if (alert) {
alert.remove();
}
}
// Sync data when coming back online
async function syncData() {
const db = await initDB();
const tx = db.transaction(['bookings', 'payments'], 'readwrite');
// TODO: Implement actual sync logic with backend
console.log('Syncing data with server...');
// Show sync success message
const syncAlert = document.createElement('div');
syncAlert.className = 'fixed bottom-4 left-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-md z-50';
syncAlert.innerHTML = '✓ Data synced successfully!';
document.body.appendChild(syncAlert);
setTimeout(() => {
syncAlert.remove();
}, 3000);
}
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
checkOnlineStatus();
// Add click handlers for all buttons
document.querySelectorAll('button').forEach(button => {
if (!button.hasAttribute('data-no-handler')) {
button.addEventListener('click', handleButtonClick);
}
});
// Initialize form submissions
document.querySelectorAll('form').forEach(form => {
form.addEventListener('submit', handleFormSubmit);
});
// Initialize tooltips
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
tooltipTriggerList.map(tooltipTriggerEl => {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
// Load offline data if needed
if (!navigator.onLine) {
loadOfflineData();
}
// Initialize real-time room updates
if (window.location.pathname === '/dashboard.html') {
setInterval(fetchRoomStatus, 30000); // Update every 30 seconds
}
});
// Fetch room status from API
async function fetchRoomStatus() {
try {
const response = await fetch('/api/rooms/status');
const data = await response.json();
updateRoomCards(data);
} catch (error) {
console.error('Error fetching room status:', error);
}
}
// Update room cards with fresh data
function updateRoomCards(rooms) {
rooms.forEach(room => {
const card = document.querySelector(`room-card[room-number="${room.number}"]`);
if (card) {
card.setAttribute('status', room.status);
card.setAttribute('booking-type', room.bookingType || '');
card.setAttribute('guest-name', room.guestName || '');
card.setAttribute('checkout-time', room.checkoutTime || '');
}
});
}
// Handle offline booking submission
async function submitOfflineBooking(bookingData) {
const db = await initDB();
const tx = db.transaction('bookings', 'readwrite');
const store = tx.objectStore('bookings');
return new Promise((resolve, reject) => {
const request = store.add({
...bookingData,
offline: true,
syncStatus: 'pending',
createdAt: new Date().toISOString()
});
request.onsuccess = () => resolve();
request.onerror = (event) => reject(event.target.error);
});
}
async function loadOfflineData() {
const db = await initDB();
const tx = db.transaction(['bookings', 'payments', 'rooms'], 'readonly');
const bookings = await tx.objectStore('bookings').getAll();
const payments = await tx.objectStore('payments').getAll();
const rooms = await tx.objectStore('rooms').getAll();
return { bookings, payments, rooms };
}
function handleButtonClick(e) {
const button = e.currentTarget;
const action = button.dataset.action;
switch(action) {
case 'new-booking':
window.location.href = '/bookings.html?new=true';
break;
case 'check-out':
const roomNumber = button.dataset.room;
handleCheckOut(roomNumber);
break;
case 'print-report':
window.print();
break;
case 'record-payment':
const bookingId = button.dataset.booking;
window.location.href = `/payments.html?booking=${bookingId}`;
break;
case 'view-details':
const id = button.dataset.id;
window.location.href = `/booking-details.html?id=${id}`;
break;
case 'edit-booking':
const editId = button.dataset.id;
window.location.href = `/bookings.html?edit=${editId}`;
break;
default:
console.log('Button clicked:', button.textContent);
}
}
async function handleFormSubmit(e) {
e.preventDefault();
const form = e.currentTarget;
const formData = new FormData(form);
const formAction = form.getAttribute('action') || form.dataset.action;
const formMethod = form.getAttribute('method') || 'POST';
try {
if (navigator.onLine) {
const response = await fetch(formAction, {
method: formMethod,
body: formData
});
const result = await response.json();
showToast('Success: ' + result.message);
} else {
await saveFormDataOffline(formData, formAction);
showToast('Saved offline. Will sync when online.');
}
} catch (error) {
showToast('Error: ' + error.message, 'error');
}
}
async function saveFormDataOffline(formData, action) {
const db = await initDB();
const tx = db.transaction('pendingActions', 'readwrite');
const store = tx.objectStore('pendingActions');
const pendingAction = {
action: action,
data: Object.fromEntries(formData),
timestamp: new Date().toISOString()
};
await store.add(pendingAction);
}
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded-md shadow-md z-50 ${
type === 'success' ? 'bg-green-500' : 'bg-red-500'
} text-white`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.remove();
}, 3000);
}
// Utility function for currency formatting
function formatUGX(amount) {
return new Intl.NumberFormat('en-UG', {
style: 'currency',
currency: 'UGX',
minimumFractionDigits: 0
}).format(amount);
}
// Login form validation
function validateLoginForm(email, password) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { valid: false, message: 'Please enter a valid email address' };
}
if (password.length < 6) {
return { valid: false, message: 'Password must be at least 6 characters' };
}
return { valid: true };
}